Add anchor output when we have HTLCs or a to_local output
[rust-lightning] / lightning / src / ln / functional_tests.rs
1 //! Tests that test standing up a network of ChannelManagers, creating channels, sending
2 //! payments/messages between them, and often checking the resulting ChannelMonitors are able to
3 //! claim outputs on-chain.
4
5 use chain::transaction::OutPoint;
6 use chain::keysinterface::{ChannelKeys, KeysInterface, SpendableOutputDescriptor};
7 use chain::chaininterface;
8 use chain::chaininterface::{ChainListener, ChainWatchInterfaceUtil, BlockNotifier};
9 use ln::channel::{COMMITMENT_TX_BASE_WEIGHT, COMMITMENT_TX_WEIGHT_PER_HTLC};
10 use ln::channelmanager::{ChannelManager,ChannelManagerReadArgs,HTLCForwardInfo,RAACommitmentOrder, PaymentPreimage, PaymentHash, PaymentSecret, PaymentSendFailure, BREAKDOWN_TIMEOUT};
11 use ln::channelmonitor::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ManyChannelMonitor, ANTI_REORG_DELAY};
12 use ln::channelmonitor;
13 use ln::channel::{Channel, ChannelError};
14 use ln::{chan_utils, onion_utils};
15 use routing::router::{Route, RouteHop, get_route};
16 use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
17 use ln::msgs;
18 use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler,HTLCFailChannelUpdate, ErrorAction};
19 use util::enforcing_trait_impls::EnforcingChannelKeys;
20 use util::{byte_utils, test_utils};
21 use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
22 use util::errors::APIError;
23 use util::ser::{Writeable, Writer, ReadableArgs, Readable};
24 use util::config::UserConfig;
25
26 use bitcoin::util::hash::BitcoinHash;
27 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
28 use bitcoin::hash_types::{Txid, BlockHash};
29 use bitcoin::util::bip143;
30 use bitcoin::util::address::Address;
31 use bitcoin::util::bip32::{ChildNumber, ExtendedPubKey, ExtendedPrivKey};
32 use bitcoin::blockdata::block::{Block, BlockHeader};
33 use bitcoin::blockdata::transaction::{Transaction, TxOut, TxIn, SigHashType, OutPoint as BitcoinOutPoint};
34 use bitcoin::blockdata::script::{Builder, Script};
35 use bitcoin::blockdata::opcodes;
36 use bitcoin::blockdata::constants::genesis_block;
37 use bitcoin::network::constants::Network;
38
39 use bitcoin::hashes::sha256::Hash as Sha256;
40 use bitcoin::hashes::Hash;
41
42 use bitcoin::secp256k1::{Secp256k1, Message};
43 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
44
45 use std::collections::{BTreeSet, HashMap, HashSet};
46 use std::default::Default;
47 use std::sync::{Arc, Mutex};
48 use std::sync::atomic::Ordering;
49 use std::{mem, io};
50
51 use rand::{thread_rng, Rng};
52
53 use ln::functional_test_utils::*;
54
55 #[test]
56 fn test_insane_channel_opens() {
57         // Stand up a network of 2 nodes
58         let chanmon_cfgs = create_chanmon_cfgs(2);
59         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
60         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
61         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
62
63         // Instantiate channel parameters where we push the maximum msats given our
64         // funding satoshis
65         let channel_value_sat = 31337; // same as funding satoshis
66         let channel_reserve_satoshis = Channel::<EnforcingChannelKeys>::get_remote_channel_reserve_satoshis(channel_value_sat);
67         let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
68
69         // Have node0 initiate a channel to node1 with aforementioned parameters
70         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
71
72         // Extract the channel open message from node0 to node1
73         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
74
75         // Test helper that asserts we get the correct error string given a mutator
76         // that supposedly makes the channel open message insane
77         let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
78                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &message_mutator(open_channel_message.clone()));
79                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
80                 assert_eq!(msg_events.len(), 1);
81                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
82                         match action {
83                                 &ErrorAction::SendErrorMessage { .. } => {
84                                         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), expected_error_str.to_string(), 1);
85                                 },
86                                 _ => panic!("unexpected event!"),
87                         }
88                 } else { assert!(false); }
89         };
90
91         use ln::channel::MAX_FUNDING_SATOSHIS;
92         use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
93
94         // Test all mutations that would make the channel open message insane
95         insane_open_helper("funding value > 2^24", |mut msg| { msg.funding_satoshis = MAX_FUNDING_SATOSHIS; msg });
96
97         insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
98
99         insane_open_helper("push_msat larger than funding value", |mut msg| { msg.push_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000 + 1; msg });
100
101         insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
102
103         insane_open_helper("Bogus; channel reserve is less than dust limit", |mut msg| { msg.dust_limit_satoshis = msg.channel_reserve_satoshis + 1; msg });
104
105         insane_open_helper("Minimum htlc value is full channel value", |mut msg| { msg.htlc_minimum_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000; msg });
106
107         insane_open_helper("They wanted our payments to be delayed by a needlessly long period", |mut msg| { msg.to_self_delay = MAX_LOCAL_BREAKDOWN_TIMEOUT + 1; msg });
108
109         insane_open_helper("0 max_accpted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
110
111         insane_open_helper("max_accpted_htlcs > 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
112 }
113
114 #[test]
115 fn test_async_inbound_update_fee() {
116         let chanmon_cfgs = create_chanmon_cfgs(2);
117         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
118         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
119         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
120         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
121         let logger = test_utils::TestLogger::new();
122         let channel_id = chan.2;
123
124         // balancing
125         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
126
127         // A                                        B
128         // update_fee                            ->
129         // send (1) commitment_signed            -.
130         //                                       <- update_add_htlc/commitment_signed
131         // send (2) RAA (awaiting remote revoke) -.
132         // (1) commitment_signed is delivered    ->
133         //                                       .- send (3) RAA (awaiting remote revoke)
134         // (2) RAA is delivered                  ->
135         //                                       .- send (4) commitment_signed
136         //                                       <- (3) RAA is delivered
137         // send (5) commitment_signed            -.
138         //                                       <- (4) commitment_signed is delivered
139         // send (6) RAA                          -.
140         // (5) commitment_signed is delivered    ->
141         //                                       <- RAA
142         // (6) RAA is delivered                  ->
143
144         // First nodes[0] generates an update_fee
145         nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
146         check_added_monitors!(nodes[0], 1);
147
148         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
149         assert_eq!(events_0.len(), 1);
150         let (update_msg, commitment_signed) = match events_0[0] { // (1)
151                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
152                         (update_fee.as_ref(), commitment_signed)
153                 },
154                 _ => panic!("Unexpected event"),
155         };
156
157         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
158
159         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
160         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
161         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
162         nodes[1].node.send_payment(&get_route(&nodes[1].node.get_our_node_id(), net_graph_msg_handler, &nodes[0].node.get_our_node_id(), None, &Vec::new(), 40000, TEST_FINAL_CLTV, &logger).unwrap(), our_payment_hash, &None).unwrap();
163         check_added_monitors!(nodes[1], 1);
164
165         let payment_event = {
166                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
167                 assert_eq!(events_1.len(), 1);
168                 SendEvent::from_event(events_1.remove(0))
169         };
170         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
171         assert_eq!(payment_event.msgs.len(), 1);
172
173         // ...now when the messages get delivered everyone should be happy
174         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
175         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
176         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
177         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
178         check_added_monitors!(nodes[0], 1);
179
180         // deliver(1), generate (3):
181         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
182         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
183         // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
184         check_added_monitors!(nodes[1], 1);
185
186         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
187         let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
188         assert!(bs_update.update_add_htlcs.is_empty()); // (4)
189         assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
190         assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
191         assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
192         assert!(bs_update.update_fee.is_none()); // (4)
193         check_added_monitors!(nodes[1], 1);
194
195         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
196         let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
197         assert!(as_update.update_add_htlcs.is_empty()); // (5)
198         assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
199         assert!(as_update.update_fail_htlcs.is_empty()); // (5)
200         assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
201         assert!(as_update.update_fee.is_none()); // (5)
202         check_added_monitors!(nodes[0], 1);
203
204         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
205         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
206         // only (6) so get_event_msg's assert(len == 1) passes
207         check_added_monitors!(nodes[0], 1);
208
209         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
210         let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
211         check_added_monitors!(nodes[1], 1);
212
213         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
214         check_added_monitors!(nodes[0], 1);
215
216         let events_2 = nodes[0].node.get_and_clear_pending_events();
217         assert_eq!(events_2.len(), 1);
218         match events_2[0] {
219                 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
220                 _ => panic!("Unexpected event"),
221         }
222
223         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
224         check_added_monitors!(nodes[1], 1);
225 }
226
227 #[test]
228 fn test_update_fee_unordered_raa() {
229         // Just the intro to the previous test followed by an out-of-order RAA (which caused a
230         // crash in an earlier version of the update_fee patch)
231         let chanmon_cfgs = create_chanmon_cfgs(2);
232         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
233         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
234         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
235         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
236         let channel_id = chan.2;
237         let logger = test_utils::TestLogger::new();
238
239         // balancing
240         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
241
242         // First nodes[0] generates an update_fee
243         nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
244         check_added_monitors!(nodes[0], 1);
245
246         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
247         assert_eq!(events_0.len(), 1);
248         let update_msg = match events_0[0] { // (1)
249                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
250                         update_fee.as_ref()
251                 },
252                 _ => panic!("Unexpected event"),
253         };
254
255         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
256
257         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
258         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
259         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
260         nodes[1].node.send_payment(&get_route(&nodes[1].node.get_our_node_id(), net_graph_msg_handler, &nodes[0].node.get_our_node_id(), None, &Vec::new(), 40000, TEST_FINAL_CLTV, &logger).unwrap(), our_payment_hash, &None).unwrap();
261         check_added_monitors!(nodes[1], 1);
262
263         let payment_event = {
264                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
265                 assert_eq!(events_1.len(), 1);
266                 SendEvent::from_event(events_1.remove(0))
267         };
268         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
269         assert_eq!(payment_event.msgs.len(), 1);
270
271         // ...now when the messages get delivered everyone should be happy
272         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
273         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
274         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
275         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
276         check_added_monitors!(nodes[0], 1);
277
278         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
279         check_added_monitors!(nodes[1], 1);
280
281         // We can't continue, sadly, because our (1) now has a bogus signature
282 }
283
284 #[test]
285 fn test_multi_flight_update_fee() {
286         let chanmon_cfgs = create_chanmon_cfgs(2);
287         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
288         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
289         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
290         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
291         let channel_id = chan.2;
292
293         // A                                        B
294         // update_fee/commitment_signed          ->
295         //                                       .- send (1) RAA and (2) commitment_signed
296         // update_fee (never committed)          ->
297         // (3) update_fee                        ->
298         // We have to manually generate the above update_fee, it is allowed by the protocol but we
299         // don't track which updates correspond to which revoke_and_ack responses so we're in
300         // AwaitingRAA mode and will not generate the update_fee yet.
301         //                                       <- (1) RAA delivered
302         // (3) is generated and send (4) CS      -.
303         // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
304         // know the per_commitment_point to use for it.
305         //                                       <- (2) commitment_signed delivered
306         // revoke_and_ack                        ->
307         //                                          B should send no response here
308         // (4) commitment_signed delivered       ->
309         //                                       <- RAA/commitment_signed delivered
310         // revoke_and_ack                        ->
311
312         // First nodes[0] generates an update_fee
313         let initial_feerate = get_feerate!(nodes[0], channel_id);
314         nodes[0].node.update_fee(channel_id, initial_feerate + 20).unwrap();
315         check_added_monitors!(nodes[0], 1);
316
317         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
318         assert_eq!(events_0.len(), 1);
319         let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
320                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
321                         (update_fee.as_ref().unwrap(), commitment_signed)
322                 },
323                 _ => panic!("Unexpected event"),
324         };
325
326         // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
327         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
328         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
329         let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
330         check_added_monitors!(nodes[1], 1);
331
332         // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
333         // transaction:
334         nodes[0].node.update_fee(channel_id, initial_feerate + 40).unwrap();
335         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
336         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
337
338         // Create the (3) update_fee message that nodes[0] will generate before it does...
339         let mut update_msg_2 = msgs::UpdateFee {
340                 channel_id: update_msg_1.channel_id.clone(),
341                 feerate_per_kw: (initial_feerate + 30) as u32,
342         };
343
344         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
345
346         update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
347         // Deliver (3)
348         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
349
350         // Deliver (1), generating (3) and (4)
351         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
352         let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
353         check_added_monitors!(nodes[0], 1);
354         assert!(as_second_update.update_add_htlcs.is_empty());
355         assert!(as_second_update.update_fulfill_htlcs.is_empty());
356         assert!(as_second_update.update_fail_htlcs.is_empty());
357         assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
358         // Check that the update_fee newly generated matches what we delivered:
359         assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
360         assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
361
362         // Deliver (2) commitment_signed
363         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
364         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
365         check_added_monitors!(nodes[0], 1);
366         // No commitment_signed so get_event_msg's assert(len == 1) passes
367
368         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
369         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
370         check_added_monitors!(nodes[1], 1);
371
372         // Delever (4)
373         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
374         let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
375         check_added_monitors!(nodes[1], 1);
376
377         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
378         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
379         check_added_monitors!(nodes[0], 1);
380
381         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
382         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
383         // No commitment_signed so get_event_msg's assert(len == 1) passes
384         check_added_monitors!(nodes[0], 1);
385
386         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
387         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
388         check_added_monitors!(nodes[1], 1);
389 }
390
391 #[test]
392 fn test_1_conf_open() {
393         // Previously, if the minium_depth config was set to 1, we'd never send a funding_locked. This
394         // tests that we properly send one in that case.
395         let mut alice_config = UserConfig::default();
396         alice_config.own_channel_config.minimum_depth = 1;
397         alice_config.channel_options.announced_channel = true;
398         alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
399         let mut bob_config = UserConfig::default();
400         bob_config.own_channel_config.minimum_depth = 1;
401         bob_config.channel_options.announced_channel = true;
402         bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
403         let chanmon_cfgs = create_chanmon_cfgs(2);
404         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
405         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(alice_config), Some(bob_config)]);
406         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
407
408         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
409         assert!(nodes[0].chain_monitor.does_match_tx(&tx));
410         assert!(nodes[1].chain_monitor.does_match_tx(&tx));
411
412         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
413         nodes[1].block_notifier.block_connected_checked(&header, 1, &[&tx; 1], &[tx.version; 1]);
414         nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &get_event_msg!(nodes[1], MessageSendEvent::SendFundingLocked, nodes[0].node.get_our_node_id()));
415
416         nodes[0].block_notifier.block_connected_checked(&header, 1, &[&tx; 1], &[tx.version; 1]);
417         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
418         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
419
420         for node in nodes {
421                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
422                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
423                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
424         }
425 }
426
427 fn do_test_sanity_on_in_flight_opens(steps: u8) {
428         // Previously, we had issues deserializing channels when we hadn't connected the first block
429         // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
430         // serialization round-trips and simply do steps towards opening a channel and then drop the
431         // Node objects.
432
433         let chanmon_cfgs = create_chanmon_cfgs(2);
434         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
435         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
436         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
437
438         if steps & 0b1000_0000 != 0{
439                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
440                 nodes[0].block_notifier.block_connected_checked(&header, 1, &Vec::new(), &[0; 0]);
441                 nodes[1].block_notifier.block_connected_checked(&header, 1, &Vec::new(), &[0; 0]);
442         }
443
444         if steps & 0x0f == 0 { return; }
445         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
446         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
447
448         if steps & 0x0f == 1 { return; }
449         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
450         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
451
452         if steps & 0x0f == 2 { return; }
453         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
454
455         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
456
457         if steps & 0x0f == 3 { return; }
458         nodes[0].node.funding_transaction_generated(&temporary_channel_id, funding_output);
459         check_added_monitors!(nodes[0], 0);
460         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
461
462         if steps & 0x0f == 4 { return; }
463         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
464         {
465                 let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
466                 assert_eq!(added_monitors.len(), 1);
467                 assert_eq!(added_monitors[0].0, funding_output);
468                 added_monitors.clear();
469         }
470         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
471
472         if steps & 0x0f == 5 { return; }
473         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
474         {
475                 let mut added_monitors = nodes[0].chan_monitor.added_monitors.lock().unwrap();
476                 assert_eq!(added_monitors.len(), 1);
477                 assert_eq!(added_monitors[0].0, funding_output);
478                 added_monitors.clear();
479         }
480
481         let events_4 = nodes[0].node.get_and_clear_pending_events();
482         assert_eq!(events_4.len(), 1);
483         match events_4[0] {
484                 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
485                         assert_eq!(user_channel_id, 42);
486                         assert_eq!(*funding_txo, funding_output);
487                 },
488                 _ => panic!("Unexpected event"),
489         };
490
491         if steps & 0x0f == 6 { return; }
492         create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx);
493
494         if steps & 0x0f == 7 { return; }
495         confirm_transaction(&nodes[0].block_notifier, &nodes[0].chain_monitor, &tx, tx.version);
496         create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
497 }
498
499 #[test]
500 fn test_sanity_on_in_flight_opens() {
501         do_test_sanity_on_in_flight_opens(0);
502         do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
503         do_test_sanity_on_in_flight_opens(1);
504         do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
505         do_test_sanity_on_in_flight_opens(2);
506         do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
507         do_test_sanity_on_in_flight_opens(3);
508         do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
509         do_test_sanity_on_in_flight_opens(4);
510         do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
511         do_test_sanity_on_in_flight_opens(5);
512         do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
513         do_test_sanity_on_in_flight_opens(6);
514         do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
515         do_test_sanity_on_in_flight_opens(7);
516         do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
517         do_test_sanity_on_in_flight_opens(8);
518         do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
519 }
520
521 #[test]
522 fn test_update_fee_vanilla() {
523         let chanmon_cfgs = create_chanmon_cfgs(2);
524         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
525         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
526         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
527         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
528         let channel_id = chan.2;
529
530         let feerate = get_feerate!(nodes[0], channel_id);
531         nodes[0].node.update_fee(channel_id, feerate+25).unwrap();
532         check_added_monitors!(nodes[0], 1);
533
534         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
535         assert_eq!(events_0.len(), 1);
536         let (update_msg, commitment_signed) = match events_0[0] {
537                         MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
538                         (update_fee.as_ref(), commitment_signed)
539                 },
540                 _ => panic!("Unexpected event"),
541         };
542         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
543
544         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
545         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
546         check_added_monitors!(nodes[1], 1);
547
548         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
549         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
550         check_added_monitors!(nodes[0], 1);
551
552         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
553         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
554         // No commitment_signed so get_event_msg's assert(len == 1) passes
555         check_added_monitors!(nodes[0], 1);
556
557         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
558         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
559         check_added_monitors!(nodes[1], 1);
560 }
561
562 #[test]
563 fn test_update_fee_that_funder_cannot_afford() {
564         let chanmon_cfgs = create_chanmon_cfgs(2);
565         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
566         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
567         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
568         let channel_value = 2357;
569         let push_msat = 800_000;
570
571         // First check that any smaller channel_value would result in an error as the funder cannot
572         // afford any commitment transaction(s).
573         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value - 1, push_msat, 42, None).unwrap();
574         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
575
576         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel_message);
577         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
578         assert_eq!(msg_events.len(), 1);
579         if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
580                 match action {
581                         &ErrorAction::SendErrorMessage { .. } => {
582                                 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Insufficient funding amount for initial commitment".to_string(), 1);
583                         },
584                         _ => panic!("unexpected event!"),
585                 }
586         } else { assert!(false); }
587
588         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, push_msat, InitFeatures::known(), InitFeatures::known());
589         let channel_id = chan.2;
590
591         let feerate = 254;
592         nodes[0].node.update_fee(channel_id, feerate).unwrap();
593         check_added_monitors!(nodes[0], 1);
594         let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
595
596         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
597
598         commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
599
600         //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
601         //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
602         {
603                 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
604
605                 //We made sure neither party's funds are below the dust limit so -3 non-HTLC txns from number of outputs
606                 let num_htlcs = commitment_tx.output.len() - 3;
607                 let total_fee: u64 = feerate * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
608                 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
609                 actual_fee = channel_value - actual_fee;
610                 assert_eq!(total_fee, actual_fee);
611         }
612
613         //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
614         //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
615         nodes[0].node.update_fee(channel_id, feerate+2).unwrap();
616         check_added_monitors!(nodes[0], 1);
617
618         let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
619
620         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap());
621
622         //While producing the commitment_signed response after handling a received update_fee request the
623         //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
624         //Should produce and error.
625         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed);
626         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
627         check_added_monitors!(nodes[1], 1);
628         check_closed_broadcast!(nodes[1], true);
629 }
630
631 #[test]
632 fn test_update_fee_with_fundee_update_add_htlc() {
633         let chanmon_cfgs = create_chanmon_cfgs(2);
634         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
635         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
636         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
637         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
638         let channel_id = chan.2;
639         let logger = test_utils::TestLogger::new();
640
641         // balancing
642         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
643
644         let feerate = get_feerate!(nodes[0], channel_id);
645         nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
646         check_added_monitors!(nodes[0], 1);
647
648         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
649         assert_eq!(events_0.len(), 1);
650         let (update_msg, commitment_signed) = match events_0[0] {
651                         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 } } => {
652                         (update_fee.as_ref(), commitment_signed)
653                 },
654                 _ => panic!("Unexpected event"),
655         };
656         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
657         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
658         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
659         check_added_monitors!(nodes[1], 1);
660
661         let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]);
662         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
663         let route = get_route(&nodes[1].node.get_our_node_id(), net_graph_msg_handler, &nodes[0].node.get_our_node_id(), None, &Vec::new(), 800000, TEST_FINAL_CLTV, &logger).unwrap();
664
665         // nothing happens since node[1] is in AwaitingRemoteRevoke
666         nodes[1].node.send_payment(&route, our_payment_hash, &None).unwrap();
667         {
668                 let mut added_monitors = nodes[0].chan_monitor.added_monitors.lock().unwrap();
669                 assert_eq!(added_monitors.len(), 0);
670                 added_monitors.clear();
671         }
672         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
673         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
674         // node[1] has nothing to do
675
676         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
677         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
678         check_added_monitors!(nodes[0], 1);
679
680         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
681         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
682         // No commitment_signed so get_event_msg's assert(len == 1) passes
683         check_added_monitors!(nodes[0], 1);
684         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
685         check_added_monitors!(nodes[1], 1);
686         // AwaitingRemoteRevoke ends here
687
688         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
689         assert_eq!(commitment_update.update_add_htlcs.len(), 1);
690         assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
691         assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
692         assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
693         assert_eq!(commitment_update.update_fee.is_none(), true);
694
695         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
696         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
697         check_added_monitors!(nodes[0], 1);
698         let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
699
700         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
701         check_added_monitors!(nodes[1], 1);
702         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
703
704         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
705         check_added_monitors!(nodes[1], 1);
706         let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
707         // No commitment_signed so get_event_msg's assert(len == 1) passes
708
709         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
710         check_added_monitors!(nodes[0], 1);
711         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
712
713         expect_pending_htlcs_forwardable!(nodes[0]);
714
715         let events = nodes[0].node.get_and_clear_pending_events();
716         assert_eq!(events.len(), 1);
717         match events[0] {
718                 Event::PaymentReceived { .. } => { },
719                 _ => panic!("Unexpected event"),
720         };
721
722         claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage, 800_000);
723
724         send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000, 800_000);
725         send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000, 800_000);
726         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
727 }
728
729 #[test]
730 fn test_update_fee() {
731         let chanmon_cfgs = create_chanmon_cfgs(2);
732         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
733         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
734         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
735         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
736         let channel_id = chan.2;
737
738         // A                                        B
739         // (1) update_fee/commitment_signed      ->
740         //                                       <- (2) revoke_and_ack
741         //                                       .- send (3) commitment_signed
742         // (4) update_fee/commitment_signed      ->
743         //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
744         //                                       <- (3) commitment_signed delivered
745         // send (6) revoke_and_ack               -.
746         //                                       <- (5) deliver revoke_and_ack
747         // (6) deliver revoke_and_ack            ->
748         //                                       .- send (7) commitment_signed in response to (4)
749         //                                       <- (7) deliver commitment_signed
750         // revoke_and_ack                        ->
751
752         // Create and deliver (1)...
753         let feerate = get_feerate!(nodes[0], channel_id);
754         nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
755         check_added_monitors!(nodes[0], 1);
756
757         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
758         assert_eq!(events_0.len(), 1);
759         let (update_msg, commitment_signed) = match events_0[0] {
760                         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 } } => {
761                         (update_fee.as_ref(), commitment_signed)
762                 },
763                 _ => panic!("Unexpected event"),
764         };
765         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
766
767         // Generate (2) and (3):
768         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
769         let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
770         check_added_monitors!(nodes[1], 1);
771
772         // Deliver (2):
773         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
774         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
775         check_added_monitors!(nodes[0], 1);
776
777         // Create and deliver (4)...
778         nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
779         check_added_monitors!(nodes[0], 1);
780         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
781         assert_eq!(events_0.len(), 1);
782         let (update_msg, commitment_signed) = match events_0[0] {
783                         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 } } => {
784                         (update_fee.as_ref(), commitment_signed)
785                 },
786                 _ => panic!("Unexpected event"),
787         };
788
789         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
790         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
791         check_added_monitors!(nodes[1], 1);
792         // ... creating (5)
793         let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
794         // No commitment_signed so get_event_msg's assert(len == 1) passes
795
796         // Handle (3), creating (6):
797         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
798         check_added_monitors!(nodes[0], 1);
799         let revoke_msg_0 = 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         // Deliver (5):
803         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
804         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
805         check_added_monitors!(nodes[0], 1);
806
807         // Deliver (6), creating (7):
808         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
809         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
810         assert!(commitment_update.update_add_htlcs.is_empty());
811         assert!(commitment_update.update_fulfill_htlcs.is_empty());
812         assert!(commitment_update.update_fail_htlcs.is_empty());
813         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
814         assert!(commitment_update.update_fee.is_none());
815         check_added_monitors!(nodes[1], 1);
816
817         // Deliver (7)
818         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
819         check_added_monitors!(nodes[0], 1);
820         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
821         // No commitment_signed so get_event_msg's assert(len == 1) passes
822
823         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
824         check_added_monitors!(nodes[1], 1);
825         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
826
827         assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
828         assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
829         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
830 }
831
832 #[test]
833 fn pre_funding_lock_shutdown_test() {
834         // Test sending a shutdown prior to funding_locked after funding generation
835         let chanmon_cfgs = create_chanmon_cfgs(2);
836         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
837         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
838         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
839         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 8000000, 0, InitFeatures::known(), InitFeatures::known());
840         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
841         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![tx.clone()]}, 1);
842         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![tx.clone()]}, 1);
843
844         nodes[0].node.close_channel(&OutPoint::new(tx.txid(), 0).to_channel_id()).unwrap();
845         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
846         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
847         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
848         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
849
850         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
851         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
852         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
853         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
854         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
855         assert!(node_0_none.is_none());
856
857         assert!(nodes[0].node.list_channels().is_empty());
858         assert!(nodes[1].node.list_channels().is_empty());
859 }
860
861 #[test]
862 fn updates_shutdown_wait() {
863         // Test sending a shutdown with outstanding updates pending
864         let chanmon_cfgs = create_chanmon_cfgs(3);
865         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
866         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
867         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
868         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
869         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
870         let logger = test_utils::TestLogger::new();
871
872         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
873
874         nodes[0].node.close_channel(&chan_1.2).unwrap();
875         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
876         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
877         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
878         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
879
880         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
881         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
882
883         let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
884
885         let net_graph_msg_handler0 = &nodes[0].net_graph_msg_handler;
886         let net_graph_msg_handler1 = &nodes[1].net_graph_msg_handler;
887         let route_1 = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler0, &nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
888         let route_2 = get_route(&nodes[1].node.get_our_node_id(), net_graph_msg_handler1, &nodes[0].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
889         unwrap_send_err!(nodes[0].node.send_payment(&route_1, payment_hash, &None), true, APIError::ChannelUnavailable {..}, {});
890         unwrap_send_err!(nodes[1].node.send_payment(&route_2, payment_hash, &None), true, APIError::ChannelUnavailable {..}, {});
891
892         assert!(nodes[2].node.claim_funds(our_payment_preimage, &None, 100_000));
893         check_added_monitors!(nodes[2], 1);
894         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
895         assert!(updates.update_add_htlcs.is_empty());
896         assert!(updates.update_fail_htlcs.is_empty());
897         assert!(updates.update_fail_malformed_htlcs.is_empty());
898         assert!(updates.update_fee.is_none());
899         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
900         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
901         check_added_monitors!(nodes[1], 1);
902         let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
903         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
904
905         assert!(updates_2.update_add_htlcs.is_empty());
906         assert!(updates_2.update_fail_htlcs.is_empty());
907         assert!(updates_2.update_fail_malformed_htlcs.is_empty());
908         assert!(updates_2.update_fee.is_none());
909         assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
910         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
911         commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
912
913         let events = nodes[0].node.get_and_clear_pending_events();
914         assert_eq!(events.len(), 1);
915         match events[0] {
916                 Event::PaymentSent { ref payment_preimage } => {
917                         assert_eq!(our_payment_preimage, *payment_preimage);
918                 },
919                 _ => panic!("Unexpected event"),
920         }
921
922         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
923         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
924         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
925         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
926         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
927         assert!(node_0_none.is_none());
928
929         assert!(nodes[0].node.list_channels().is_empty());
930
931         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
932         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
933         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
934         assert!(nodes[1].node.list_channels().is_empty());
935         assert!(nodes[2].node.list_channels().is_empty());
936 }
937
938 #[test]
939 fn htlc_fail_async_shutdown() {
940         // Test HTLCs fail if shutdown starts even if messages are delivered out-of-order
941         let chanmon_cfgs = create_chanmon_cfgs(3);
942         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
943         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
944         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
945         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
946         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
947         let logger = test_utils::TestLogger::new();
948
949         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
950         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
951         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[2].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
952         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
953         check_added_monitors!(nodes[0], 1);
954         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
955         assert_eq!(updates.update_add_htlcs.len(), 1);
956         assert!(updates.update_fulfill_htlcs.is_empty());
957         assert!(updates.update_fail_htlcs.is_empty());
958         assert!(updates.update_fail_malformed_htlcs.is_empty());
959         assert!(updates.update_fee.is_none());
960
961         nodes[1].node.close_channel(&chan_1.2).unwrap();
962         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
963         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
964         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
965
966         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
967         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
968         check_added_monitors!(nodes[1], 1);
969         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
970         commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
971
972         let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
973         assert!(updates_2.update_add_htlcs.is_empty());
974         assert!(updates_2.update_fulfill_htlcs.is_empty());
975         assert_eq!(updates_2.update_fail_htlcs.len(), 1);
976         assert!(updates_2.update_fail_malformed_htlcs.is_empty());
977         assert!(updates_2.update_fee.is_none());
978
979         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]);
980         commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
981
982         expect_payment_failed!(nodes[0], our_payment_hash, false);
983
984         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
985         assert_eq!(msg_events.len(), 2);
986         let node_0_closing_signed = match msg_events[0] {
987                 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
988                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
989                         (*msg).clone()
990                 },
991                 _ => panic!("Unexpected event"),
992         };
993         match msg_events[1] {
994                 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
995                         assert_eq!(msg.contents.short_channel_id, chan_1.0.contents.short_channel_id);
996                 },
997                 _ => panic!("Unexpected event"),
998         }
999
1000         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1001         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
1002         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1003         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
1004         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
1005         assert!(node_0_none.is_none());
1006
1007         assert!(nodes[0].node.list_channels().is_empty());
1008
1009         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
1010         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
1011         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
1012         assert!(nodes[1].node.list_channels().is_empty());
1013         assert!(nodes[2].node.list_channels().is_empty());
1014 }
1015
1016 fn do_test_shutdown_rebroadcast(recv_count: u8) {
1017         // Test that shutdown/closing_signed is re-sent on reconnect with a variable number of
1018         // messages delivered prior to disconnect
1019         let chanmon_cfgs = create_chanmon_cfgs(3);
1020         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1021         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1022         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1023         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1024         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1025
1026         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
1027
1028         nodes[1].node.close_channel(&chan_1.2).unwrap();
1029         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1030         if recv_count > 0 {
1031                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
1032                 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1033                 if recv_count > 1 {
1034                         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
1035                 }
1036         }
1037
1038         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1039         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1040
1041         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1042         let node_0_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1043         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1044         let node_1_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1045
1046         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish);
1047         let node_1_2nd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1048         assert!(node_1_shutdown == node_1_2nd_shutdown);
1049
1050         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish);
1051         let node_0_2nd_shutdown = if recv_count > 0 {
1052                 let node_0_2nd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1053                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown);
1054                 node_0_2nd_shutdown
1055         } else {
1056                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1057                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown);
1058                 get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id())
1059         };
1060         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_2nd_shutdown);
1061
1062         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1063         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1064
1065         assert!(nodes[2].node.claim_funds(our_payment_preimage, &None, 100_000));
1066         check_added_monitors!(nodes[2], 1);
1067         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1068         assert!(updates.update_add_htlcs.is_empty());
1069         assert!(updates.update_fail_htlcs.is_empty());
1070         assert!(updates.update_fail_malformed_htlcs.is_empty());
1071         assert!(updates.update_fee.is_none());
1072         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
1073         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
1074         check_added_monitors!(nodes[1], 1);
1075         let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1076         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
1077
1078         assert!(updates_2.update_add_htlcs.is_empty());
1079         assert!(updates_2.update_fail_htlcs.is_empty());
1080         assert!(updates_2.update_fail_malformed_htlcs.is_empty());
1081         assert!(updates_2.update_fee.is_none());
1082         assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
1083         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
1084         commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
1085
1086         let events = nodes[0].node.get_and_clear_pending_events();
1087         assert_eq!(events.len(), 1);
1088         match events[0] {
1089                 Event::PaymentSent { ref payment_preimage } => {
1090                         assert_eq!(our_payment_preimage, *payment_preimage);
1091                 },
1092                 _ => panic!("Unexpected event"),
1093         }
1094
1095         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1096         if recv_count > 0 {
1097                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
1098                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1099                 assert!(node_1_closing_signed.is_some());
1100         }
1101
1102         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1103         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1104
1105         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1106         let node_0_2nd_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1107         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1108         if recv_count == 0 {
1109                 // If all closing_signeds weren't delivered we can just resume where we left off...
1110                 let node_1_2nd_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1111
1112                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish);
1113                 let node_0_3rd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1114                 assert!(node_0_2nd_shutdown == node_0_3rd_shutdown);
1115
1116                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1117                 let node_1_3rd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1118                 assert!(node_1_3rd_shutdown == node_1_2nd_shutdown);
1119
1120                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_3rd_shutdown);
1121                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1122
1123                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_3rd_shutdown);
1124                 let node_0_2nd_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1125                 assert!(node_0_closing_signed == node_0_2nd_closing_signed);
1126
1127                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed);
1128                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1129                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
1130                 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
1131                 assert!(node_0_none.is_none());
1132         } else {
1133                 // If one node, however, received + responded with an identical closing_signed we end
1134                 // up erroring and node[0] will try to broadcast its own latest commitment transaction.
1135                 // There isn't really anything better we can do simply, but in the future we might
1136                 // explore storing a set of recently-closed channels that got disconnected during
1137                 // closing_signed and avoiding broadcasting local commitment txn for some timeout to
1138                 // give our counterparty enough time to (potentially) broadcast a cooperative closing
1139                 // transaction.
1140                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1141
1142                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1143                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1144                 assert_eq!(msg_events.len(), 1);
1145                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
1146                         match action {
1147                                 &ErrorAction::SendErrorMessage { ref msg } => {
1148                                         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msg);
1149                                         assert_eq!(msg.channel_id, chan_1.2);
1150                                 },
1151                                 _ => panic!("Unexpected event!"),
1152                         }
1153                 } else { panic!("Needed SendErrorMessage close"); }
1154
1155                 // get_closing_signed_broadcast usually eats the BroadcastChannelUpdate for us and
1156                 // checks it, but in this case nodes[0] didn't ever get a chance to receive a
1157                 // closing_signed so we do it ourselves
1158                 check_closed_broadcast!(nodes[0], false);
1159                 check_added_monitors!(nodes[0], 1);
1160         }
1161
1162         assert!(nodes[0].node.list_channels().is_empty());
1163
1164         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
1165         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
1166         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
1167         assert!(nodes[1].node.list_channels().is_empty());
1168         assert!(nodes[2].node.list_channels().is_empty());
1169 }
1170
1171 #[test]
1172 fn test_shutdown_rebroadcast() {
1173         do_test_shutdown_rebroadcast(0);
1174         do_test_shutdown_rebroadcast(1);
1175         do_test_shutdown_rebroadcast(2);
1176 }
1177
1178 #[test]
1179 fn fake_network_test() {
1180         // Simple test which builds a network of ChannelManagers, connects them to each other, and
1181         // tests that payments get routed and transactions broadcast in semi-reasonable ways.
1182         let chanmon_cfgs = create_chanmon_cfgs(4);
1183         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1184         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1185         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1186
1187         // Create some initial channels
1188         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1189         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1190         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1191
1192         // Rebalance the network a bit by relaying one payment through all the channels...
1193         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1194         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1195         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1196         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1197
1198         // Send some more payments
1199         send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000, 1_000_000);
1200         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000, 1_000_000);
1201         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000, 1_000_000);
1202
1203         // Test failure packets
1204         let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1205         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1206
1207         // Add a new channel that skips 3
1208         let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1209
1210         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000, 1_000_000);
1211         send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000, 1_000_000);
1212         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1213         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1214         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1215         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1216         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1217
1218         // Do some rebalance loop payments, simultaneously
1219         let mut hops = Vec::with_capacity(3);
1220         hops.push(RouteHop {
1221                 pubkey: nodes[2].node.get_our_node_id(),
1222                 node_features: NodeFeatures::empty(),
1223                 short_channel_id: chan_2.0.contents.short_channel_id,
1224                 channel_features: ChannelFeatures::empty(),
1225                 fee_msat: 0,
1226                 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1227         });
1228         hops.push(RouteHop {
1229                 pubkey: nodes[3].node.get_our_node_id(),
1230                 node_features: NodeFeatures::empty(),
1231                 short_channel_id: chan_3.0.contents.short_channel_id,
1232                 channel_features: ChannelFeatures::empty(),
1233                 fee_msat: 0,
1234                 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1235         });
1236         hops.push(RouteHop {
1237                 pubkey: nodes[1].node.get_our_node_id(),
1238                 node_features: NodeFeatures::empty(),
1239                 short_channel_id: chan_4.0.contents.short_channel_id,
1240                 channel_features: ChannelFeatures::empty(),
1241                 fee_msat: 1000000,
1242                 cltv_expiry_delta: TEST_FINAL_CLTV,
1243         });
1244         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;
1245         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;
1246         let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1247
1248         let mut hops = Vec::with_capacity(3);
1249         hops.push(RouteHop {
1250                 pubkey: nodes[3].node.get_our_node_id(),
1251                 node_features: NodeFeatures::empty(),
1252                 short_channel_id: chan_4.0.contents.short_channel_id,
1253                 channel_features: ChannelFeatures::empty(),
1254                 fee_msat: 0,
1255                 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1256         });
1257         hops.push(RouteHop {
1258                 pubkey: nodes[2].node.get_our_node_id(),
1259                 node_features: NodeFeatures::empty(),
1260                 short_channel_id: chan_3.0.contents.short_channel_id,
1261                 channel_features: ChannelFeatures::empty(),
1262                 fee_msat: 0,
1263                 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1264         });
1265         hops.push(RouteHop {
1266                 pubkey: nodes[1].node.get_our_node_id(),
1267                 node_features: NodeFeatures::empty(),
1268                 short_channel_id: chan_2.0.contents.short_channel_id,
1269                 channel_features: ChannelFeatures::empty(),
1270                 fee_msat: 1000000,
1271                 cltv_expiry_delta: TEST_FINAL_CLTV,
1272         });
1273         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;
1274         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;
1275         let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1276
1277         // Claim the rebalances...
1278         fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1279         claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1, 1_000_000);
1280
1281         // Add a duplicate new channel from 2 to 4
1282         let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1283
1284         // Send some payments across both channels
1285         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1286         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1287         let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1288
1289
1290         route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1291         let events = nodes[0].node.get_and_clear_pending_msg_events();
1292         assert_eq!(events.len(), 0);
1293         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);
1294
1295         //TODO: Test that routes work again here as we've been notified that the channel is full
1296
1297         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3, 3_000_000);
1298         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4, 3_000_000);
1299         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5, 3_000_000);
1300
1301         // Close down the channels...
1302         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1303         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1304         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1305         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1306         close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1307 }
1308
1309 #[test]
1310 fn holding_cell_htlc_counting() {
1311         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1312         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1313         // commitment dance rounds.
1314         let chanmon_cfgs = create_chanmon_cfgs(3);
1315         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1316         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1317         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1318         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1319         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1320         let logger = test_utils::TestLogger::new();
1321
1322         let mut payments = Vec::new();
1323         for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1324                 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1325                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1326                 let route = get_route(&nodes[1].node.get_our_node_id(), net_graph_msg_handler, &nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
1327                 nodes[1].node.send_payment(&route, payment_hash, &None).unwrap();
1328                 payments.push((payment_preimage, payment_hash));
1329         }
1330         check_added_monitors!(nodes[1], 1);
1331
1332         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1333         assert_eq!(events.len(), 1);
1334         let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1335         assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1336
1337         // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1338         // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1339         // another HTLC.
1340         let (_, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
1341         {
1342                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1343                 let route = get_route(&nodes[1].node.get_our_node_id(), net_graph_msg_handler, &nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
1344                 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &None), true, APIError::ChannelUnavailable { err },
1345                         assert_eq!(err, "Cannot push more than their max accepted HTLCs"));
1346                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1347                 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1348         }
1349
1350         // This should also be true if we try to forward a payment.
1351         let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
1352         {
1353                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1354                 let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
1355                 nodes[0].node.send_payment(&route, payment_hash_2, &None).unwrap();
1356                 check_added_monitors!(nodes[0], 1);
1357         }
1358
1359         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1360         assert_eq!(events.len(), 1);
1361         let payment_event = SendEvent::from_event(events.pop().unwrap());
1362         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1363
1364         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1365         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1366         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1367         // fails), the second will process the resulting failure and fail the HTLC backward.
1368         expect_pending_htlcs_forwardable!(nodes[1]);
1369         expect_pending_htlcs_forwardable!(nodes[1]);
1370         check_added_monitors!(nodes[1], 1);
1371
1372         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1373         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1374         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1375
1376         let events = nodes[0].node.get_and_clear_pending_msg_events();
1377         assert_eq!(events.len(), 1);
1378         match events[0] {
1379                 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
1380                         assert_eq!(msg.contents.short_channel_id, chan_2.0.contents.short_channel_id);
1381                 },
1382                 _ => panic!("Unexpected event"),
1383         }
1384
1385         expect_payment_failed!(nodes[0], payment_hash_2, false);
1386
1387         // Now forward all the pending HTLCs and claim them back
1388         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1389         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1390         check_added_monitors!(nodes[2], 1);
1391
1392         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1393         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1394         check_added_monitors!(nodes[1], 1);
1395         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1396
1397         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1398         check_added_monitors!(nodes[1], 1);
1399         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1400
1401         for ref update in as_updates.update_add_htlcs.iter() {
1402                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1403         }
1404         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1405         check_added_monitors!(nodes[2], 1);
1406         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1407         check_added_monitors!(nodes[2], 1);
1408         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1409
1410         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1411         check_added_monitors!(nodes[1], 1);
1412         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1413         check_added_monitors!(nodes[1], 1);
1414         let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1415
1416         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1417         check_added_monitors!(nodes[2], 1);
1418
1419         expect_pending_htlcs_forwardable!(nodes[2]);
1420
1421         let events = nodes[2].node.get_and_clear_pending_events();
1422         assert_eq!(events.len(), payments.len());
1423         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1424                 match event {
1425                         &Event::PaymentReceived { ref payment_hash, .. } => {
1426                                 assert_eq!(*payment_hash, *hash);
1427                         },
1428                         _ => panic!("Unexpected event"),
1429                 };
1430         }
1431
1432         for (preimage, _) in payments.drain(..) {
1433                 claim_payment(&nodes[1], &[&nodes[2]], preimage, 100_000);
1434         }
1435
1436         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000, 1_000_000);
1437 }
1438
1439 #[test]
1440 fn duplicate_htlc_test() {
1441         // Test that we accept duplicate payment_hash HTLCs across the network and that
1442         // claiming/failing them are all separate and don't affect each other
1443         let chanmon_cfgs = create_chanmon_cfgs(6);
1444         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1445         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1446         let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1447
1448         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1449         create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1450         create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1451         create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1452         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1453         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1454
1455         let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1456
1457         *nodes[0].network_payment_count.borrow_mut() -= 1;
1458         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1459
1460         *nodes[0].network_payment_count.borrow_mut() -= 1;
1461         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1462
1463         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage, 1_000_000);
1464         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1465         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage, 1_000_000);
1466 }
1467
1468 #[test]
1469 fn test_duplicate_htlc_different_direction_onchain() {
1470         // Test that ChannelMonitor doesn't generate 2 preimage txn
1471         // when we have 2 HTLCs with same preimage that go across a node
1472         // in opposite directions.
1473         let chanmon_cfgs = create_chanmon_cfgs(2);
1474         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1475         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1476         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1477
1478         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1479         let logger = test_utils::TestLogger::new();
1480
1481         // balancing
1482         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
1483
1484         let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1485
1486         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1487         let route = get_route(&nodes[1].node.get_our_node_id(), net_graph_msg_handler, &nodes[0].node.get_our_node_id(), None, &Vec::new(), 800_000, TEST_FINAL_CLTV, &logger).unwrap();
1488         send_along_route_with_hash(&nodes[1], route, &vec!(&nodes[0])[..], 800_000, payment_hash);
1489
1490         // Provide preimage to node 0 by claiming payment
1491         nodes[0].node.claim_funds(payment_preimage, &None, 800_000);
1492         check_added_monitors!(nodes[0], 1);
1493
1494         // Broadcast node 1 commitment txn
1495         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1496
1497         assert_eq!(remote_txn[0].output.len(), 5); // 1 local, 1 remote, 1 anchor, 1 htlc inbound, and 1 htlc outbound
1498         let mut has_both_htlcs = 0; // check htlcs match ones committed
1499         for outp in remote_txn[0].output.iter() {
1500                 if outp.value == 800_000 / 1000 {
1501                         has_both_htlcs += 1;
1502                 } else if outp.value == 900_000 / 1000 {
1503                         has_both_htlcs += 1;
1504                 }
1505         }
1506         assert_eq!(has_both_htlcs, 2);
1507
1508         let header = BlockHeader { version: 0x2000_0000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1509         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![remote_txn[0].clone()] }, 1);
1510         check_added_monitors!(nodes[0], 1);
1511
1512         // Check we only broadcast 1 timeout tx
1513         let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1514         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()) };
1515         assert_eq!(claim_txn.len(), 5);
1516         check_spends!(claim_txn[2], chan_1.3);
1517         check_spends!(claim_txn[3], claim_txn[2]);
1518         assert_eq!(htlc_pair.0.input.len(), 1);
1519         assert_eq!(htlc_pair.0.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1520         check_spends!(htlc_pair.0, remote_txn[0]);
1521         assert_eq!(htlc_pair.1.input.len(), 1);
1522         assert_eq!(htlc_pair.1.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1523         check_spends!(htlc_pair.1, remote_txn[0]);
1524
1525         let events = nodes[0].node.get_and_clear_pending_msg_events();
1526         assert_eq!(events.len(), 2);
1527         for e in events {
1528                 match e {
1529                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1530                         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, .. } } => {
1531                                 assert!(update_add_htlcs.is_empty());
1532                                 assert!(update_fail_htlcs.is_empty());
1533                                 assert_eq!(update_fulfill_htlcs.len(), 1);
1534                                 assert!(update_fail_malformed_htlcs.is_empty());
1535                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1536                         },
1537                         _ => panic!("Unexpected event"),
1538                 }
1539         }
1540 }
1541
1542 fn do_channel_reserve_test(test_recv: bool) {
1543
1544         let chanmon_cfgs = create_chanmon_cfgs(3);
1545         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1546         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1547         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1548         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1900, 1001, InitFeatures::known(), InitFeatures::known());
1549         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1900, 1001, InitFeatures::known(), InitFeatures::known());
1550         let logger = test_utils::TestLogger::new();
1551
1552         let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1553         let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1554
1555         let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1556         let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1557
1558         macro_rules! get_route_and_payment_hash {
1559                 ($recv_value: expr) => {{
1560                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1561                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1562                         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes.last().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV, &logger).unwrap();
1563                         (route, payment_hash, payment_preimage)
1564                 }}
1565         };
1566
1567         macro_rules! expect_forward {
1568                 ($node: expr) => {{
1569                         let mut events = $node.node.get_and_clear_pending_msg_events();
1570                         assert_eq!(events.len(), 1);
1571                         check_added_monitors!($node, 1);
1572                         let payment_event = SendEvent::from_event(events.remove(0));
1573                         payment_event
1574                 }}
1575         }
1576
1577         let feemsat = 239; // somehow we know?
1578         let total_fee_msat = (nodes.len() - 2) as u64 * 239;
1579
1580         let recv_value_0 = stat01.their_max_htlc_value_in_flight_msat - total_fee_msat;
1581
1582         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1583         {
1584                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0 + 1);
1585                 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1586                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { err },
1587                         assert_eq!(err, "Cannot send value that would put us over the max HTLC value in flight our peer will accept"));
1588                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1589                 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);
1590         }
1591
1592         let mut htlc_id = 0;
1593         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1594         // nodes[0]'s wealth
1595         loop {
1596                 let amt_msat = recv_value_0 + total_fee_msat;
1597                 if stat01.value_to_self_msat - amt_msat < stat01.channel_reserve_msat {
1598                         break;
1599                 }
1600                 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0, recv_value_0);
1601                 htlc_id += 1;
1602
1603                 let (stat01_, stat11_, stat12_, stat22_) = (
1604                         get_channel_value_stat!(nodes[0], chan_1.2),
1605                         get_channel_value_stat!(nodes[1], chan_1.2),
1606                         get_channel_value_stat!(nodes[1], chan_2.2),
1607                         get_channel_value_stat!(nodes[2], chan_2.2),
1608                 );
1609
1610                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1611                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1612                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1613                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1614                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1615         }
1616
1617         {
1618                 let recv_value = stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat;
1619                 // attempt to get channel_reserve violation
1620                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value + 1);
1621                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { err },
1622                         assert_eq!(err, "Cannot send value that would put us under local channel reserve value"));
1623                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1624                 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send value that would put us under local channel reserve value".to_string(), 1);
1625         }
1626
1627         // adding pending output
1628         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat)/2;
1629         let amt_msat_1 = recv_value_1 + total_fee_msat;
1630
1631         let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
1632         let payment_event_1 = {
1633                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &None).unwrap();
1634                 check_added_monitors!(nodes[0], 1);
1635
1636                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1637                 assert_eq!(events.len(), 1);
1638                 SendEvent::from_event(events.remove(0))
1639         };
1640         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1641
1642         // channel reserve test with htlc pending output > 0
1643         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat;
1644         {
1645                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
1646                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { err },
1647                         assert_eq!(err, "Cannot send value that would put us under local channel reserve value"));
1648                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1649                 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send value that would put us under local channel reserve value".to_string(), 2);
1650         }
1651
1652         {
1653                 // test channel_reserve test on nodes[1] side
1654                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
1655
1656                 // Need to manually create update_add_htlc message to go around the channel reserve check in send_htlc()
1657                 let secp_ctx = Secp256k1::new();
1658                 let session_priv = SecretKey::from_slice(&{
1659                         let mut session_key = [0; 32];
1660                         let mut rng = thread_rng();
1661                         rng.fill_bytes(&mut session_key);
1662                         session_key
1663                 }).expect("RNG is bad!");
1664
1665                 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1666                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1667                 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], recv_value_2 + 1, &None, cur_height).unwrap();
1668                 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
1669                 let msg = msgs::UpdateAddHTLC {
1670                         channel_id: chan_1.2,
1671                         htlc_id,
1672                         amount_msat: htlc_msat,
1673                         payment_hash: our_payment_hash,
1674                         cltv_expiry: htlc_cltv,
1675                         onion_routing_packet: onion_packet,
1676                 };
1677
1678                 if test_recv {
1679                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1680                         // If we send a garbage message, the channel should get closed, making the rest of this test case fail.
1681                         assert_eq!(nodes[1].node.list_channels().len(), 1);
1682                         assert_eq!(nodes[1].node.list_channels().len(), 1);
1683                         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1684                         assert_eq!(err_msg.data, "Remote HTLC add would put them under their reserve value");
1685                         check_added_monitors!(nodes[1], 1);
1686                         return;
1687                 }
1688         }
1689
1690         // split the rest to test holding cell
1691         let recv_value_21 = recv_value_2/2;
1692         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat;
1693         {
1694                 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
1695                 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);
1696         }
1697
1698         // now see if they go through on both sides
1699         let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
1700         // but this will stuck in the holding cell
1701         nodes[0].node.send_payment(&route_21, our_payment_hash_21, &None).unwrap();
1702         check_added_monitors!(nodes[0], 0);
1703         let events = nodes[0].node.get_and_clear_pending_events();
1704         assert_eq!(events.len(), 0);
1705
1706         // test with outbound holding cell amount > 0
1707         {
1708                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+1);
1709                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { err },
1710                         assert_eq!(err, "Cannot send value that would put us under local channel reserve value"));
1711                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1712                 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send value that would put us under local channel reserve value".to_string(), 3);
1713         }
1714
1715         let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
1716         // this will also stuck in the holding cell
1717         nodes[0].node.send_payment(&route_22, our_payment_hash_22, &None).unwrap();
1718         check_added_monitors!(nodes[0], 0);
1719         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1720         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1721
1722         // flush the pending htlc
1723         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1724         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1725         check_added_monitors!(nodes[1], 1);
1726
1727         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1728         check_added_monitors!(nodes[0], 1);
1729         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1730
1731         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1732         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1733         // No commitment_signed so get_event_msg's assert(len == 1) passes
1734         check_added_monitors!(nodes[0], 1);
1735
1736         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1737         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1738         check_added_monitors!(nodes[1], 1);
1739
1740         expect_pending_htlcs_forwardable!(nodes[1]);
1741
1742         let ref payment_event_11 = expect_forward!(nodes[1]);
1743         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1744         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1745
1746         expect_pending_htlcs_forwardable!(nodes[2]);
1747         expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
1748
1749         // flush the htlcs in the holding cell
1750         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1751         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1752         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1753         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1754         expect_pending_htlcs_forwardable!(nodes[1]);
1755
1756         let ref payment_event_3 = expect_forward!(nodes[1]);
1757         assert_eq!(payment_event_3.msgs.len(), 2);
1758         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1759         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1760
1761         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1762         expect_pending_htlcs_forwardable!(nodes[2]);
1763
1764         let events = nodes[2].node.get_and_clear_pending_events();
1765         assert_eq!(events.len(), 2);
1766         match events[0] {
1767                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
1768                         assert_eq!(our_payment_hash_21, *payment_hash);
1769                         assert_eq!(*payment_secret, None);
1770                         assert_eq!(recv_value_21, amt);
1771                 },
1772                 _ => panic!("Unexpected event"),
1773         }
1774         match events[1] {
1775                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
1776                         assert_eq!(our_payment_hash_22, *payment_hash);
1777                         assert_eq!(None, *payment_secret);
1778                         assert_eq!(recv_value_22, amt);
1779                 },
1780                 _ => panic!("Unexpected event"),
1781         }
1782
1783         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1, recv_value_1);
1784         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21, recv_value_21);
1785         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22, recv_value_22);
1786
1787         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);
1788         let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
1789         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
1790         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat);
1791
1792         let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
1793         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22);
1794 }
1795
1796 #[test]
1797 fn channel_reserve_test() {
1798         do_channel_reserve_test(false);
1799         do_channel_reserve_test(true);
1800 }
1801
1802 #[test]
1803 fn channel_reserve_in_flight_removes() {
1804         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
1805         // can send to its counterparty, but due to update ordering, the other side may not yet have
1806         // considered those HTLCs fully removed.
1807         // This tests that we don't count HTLCs which will not be included in the next remote
1808         // commitment transaction towards the reserve value (as it implies no commitment transaction
1809         // will be generated which violates the remote reserve value).
1810         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
1811         // To test this we:
1812         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
1813         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
1814         //    you only consider the value of the first HTLC, it may not),
1815         //  * start routing a third HTLC from A to B,
1816         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
1817         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
1818         //  * deliver the first fulfill from B
1819         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
1820         //    claim,
1821         //  * deliver A's response CS and RAA.
1822         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
1823         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
1824         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
1825         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
1826         let chanmon_cfgs = create_chanmon_cfgs(2);
1827         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1828         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1829         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1830         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1831         let logger = test_utils::TestLogger::new();
1832
1833         let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
1834         // Route the first two HTLCs.
1835         let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000);
1836         let (payment_preimage_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20000);
1837
1838         // Start routing the third HTLC (this is just used to get everyone in the right state).
1839         let (payment_preimage_3, payment_hash_3) = get_payment_preimage_hash!(nodes[0]);
1840         let send_1 = {
1841                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1842                 let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
1843                 nodes[0].node.send_payment(&route, payment_hash_3, &None).unwrap();
1844                 check_added_monitors!(nodes[0], 1);
1845                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1846                 assert_eq!(events.len(), 1);
1847                 SendEvent::from_event(events.remove(0))
1848         };
1849
1850         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
1851         // initial fulfill/CS.
1852         assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000));
1853         check_added_monitors!(nodes[1], 1);
1854         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1855
1856         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
1857         // remove the second HTLC when we send the HTLC back from B to A.
1858         assert!(nodes[1].node.claim_funds(payment_preimage_2, &None, 20000));
1859         check_added_monitors!(nodes[1], 1);
1860         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1861
1862         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
1863         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
1864         check_added_monitors!(nodes[0], 1);
1865         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1866         expect_payment_sent!(nodes[0], payment_preimage_1);
1867
1868         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
1869         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
1870         check_added_monitors!(nodes[1], 1);
1871         // B is already AwaitingRAA, so cant generate a CS here
1872         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1873
1874         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1875         check_added_monitors!(nodes[1], 1);
1876         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1877
1878         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1879         check_added_monitors!(nodes[0], 1);
1880         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1881
1882         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
1883         check_added_monitors!(nodes[1], 1);
1884         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1885
1886         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
1887         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
1888         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
1889         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
1890         // on-chain as necessary).
1891         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
1892         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
1893         check_added_monitors!(nodes[0], 1);
1894         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1895         expect_payment_sent!(nodes[0], payment_preimage_2);
1896
1897         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1898         check_added_monitors!(nodes[1], 1);
1899         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1900
1901         expect_pending_htlcs_forwardable!(nodes[1]);
1902         expect_payment_received!(nodes[1], payment_hash_3, 100000);
1903
1904         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
1905         // resolve the second HTLC from A's point of view.
1906         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1907         check_added_monitors!(nodes[0], 1);
1908         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1909
1910         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
1911         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
1912         let (payment_preimage_4, payment_hash_4) = get_payment_preimage_hash!(nodes[1]);
1913         let send_2 = {
1914                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1915                 let route = get_route(&nodes[1].node.get_our_node_id(), net_graph_msg_handler, &nodes[0].node.get_our_node_id(), None, &[], 10000, TEST_FINAL_CLTV, &logger).unwrap();
1916                 nodes[1].node.send_payment(&route, payment_hash_4, &None).unwrap();
1917                 check_added_monitors!(nodes[1], 1);
1918                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1919                 assert_eq!(events.len(), 1);
1920                 SendEvent::from_event(events.remove(0))
1921         };
1922
1923         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
1924         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
1925         check_added_monitors!(nodes[0], 1);
1926         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1927
1928         // Now just resolve all the outstanding messages/HTLCs for completeness...
1929
1930         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
1931         check_added_monitors!(nodes[1], 1);
1932         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1933
1934         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1935         check_added_monitors!(nodes[1], 1);
1936
1937         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1938         check_added_monitors!(nodes[0], 1);
1939         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1940
1941         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
1942         check_added_monitors!(nodes[1], 1);
1943         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1944
1945         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1946         check_added_monitors!(nodes[0], 1);
1947
1948         expect_pending_htlcs_forwardable!(nodes[0]);
1949         expect_payment_received!(nodes[0], payment_hash_4, 10000);
1950
1951         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4, 10_000);
1952         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3, 100_000);
1953 }
1954
1955 #[test]
1956 fn channel_monitor_network_test() {
1957         // Simple test which builds a network of ChannelManagers, connects them to each other, and
1958         // tests that ChannelMonitor is able to recover from various states.
1959         let chanmon_cfgs = create_chanmon_cfgs(5);
1960         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
1961         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
1962         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
1963
1964         // Create some initial channels
1965         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1966         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1967         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1968         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1969
1970         // Rebalance the network a bit by relaying one payment through all the channels...
1971         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
1972         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
1973         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
1974         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
1975
1976         // Simple case with no pending HTLCs:
1977         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
1978         check_added_monitors!(nodes[1], 1);
1979         {
1980                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
1981                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1982                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
1983                 check_added_monitors!(nodes[0], 1);
1984                 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
1985         }
1986         get_announce_close_broadcast_events(&nodes, 0, 1);
1987         assert_eq!(nodes[0].node.list_channels().len(), 0);
1988         assert_eq!(nodes[1].node.list_channels().len(), 1);
1989
1990         // One pending HTLC is discarded by the force-close:
1991         let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
1992
1993         // Simple case of one pending HTLC to HTLC-Timeout
1994         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
1995         check_added_monitors!(nodes[1], 1);
1996         {
1997                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
1998                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1999                 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
2000                 check_added_monitors!(nodes[2], 1);
2001                 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2002         }
2003         get_announce_close_broadcast_events(&nodes, 1, 2);
2004         assert_eq!(nodes[1].node.list_channels().len(), 0);
2005         assert_eq!(nodes[2].node.list_channels().len(), 1);
2006
2007         macro_rules! claim_funds {
2008                 ($node: expr, $prev_node: expr, $preimage: expr, $amount: expr) => {
2009                         {
2010                                 assert!($node.node.claim_funds($preimage, &None, $amount));
2011                                 check_added_monitors!($node, 1);
2012
2013                                 let events = $node.node.get_and_clear_pending_msg_events();
2014                                 assert_eq!(events.len(), 1);
2015                                 match events[0] {
2016                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2017                                                 assert!(update_add_htlcs.is_empty());
2018                                                 assert!(update_fail_htlcs.is_empty());
2019                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2020                                         },
2021                                         _ => panic!("Unexpected event"),
2022                                 };
2023                         }
2024                 }
2025         }
2026
2027         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2028         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2029         nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
2030         check_added_monitors!(nodes[2], 1);
2031         let node2_commitment_txid;
2032         {
2033                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2034                 node2_commitment_txid = node_txn[0].txid();
2035
2036                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2037                 claim_funds!(nodes[3], nodes[2], payment_preimage_1, 3_000_000);
2038
2039                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2040                 nodes[3].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, 1);
2041                 check_added_monitors!(nodes[3], 1);
2042
2043                 check_preimage_claim(&nodes[3], &node_txn);
2044         }
2045         get_announce_close_broadcast_events(&nodes, 2, 3);
2046         assert_eq!(nodes[2].node.list_channels().len(), 0);
2047         assert_eq!(nodes[3].node.list_channels().len(), 1);
2048
2049         { // Cheat and reset nodes[4]'s height to 1
2050                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2051                 nodes[4].block_notifier.block_connected(&Block { header, txdata: vec![] }, 1);
2052         }
2053
2054         assert_eq!(nodes[3].node.latest_block_height.load(Ordering::Acquire), 1);
2055         assert_eq!(nodes[4].node.latest_block_height.load(Ordering::Acquire), 1);
2056         // One pending HTLC to time out:
2057         let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
2058         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2059         // buffer space).
2060
2061         {
2062                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2063                 nodes[3].block_notifier.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
2064                 for i in 3..TEST_FINAL_CLTV + 2 + LATENCY_GRACE_PERIOD_BLOCKS + 1 {
2065                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2066                         nodes[3].block_notifier.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
2067                 }
2068                 check_added_monitors!(nodes[3], 1);
2069
2070                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2071                 {
2072                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2073                         node_txn.retain(|tx| {
2074                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2075                                         false
2076                                 } else { true }
2077                         });
2078                 }
2079
2080                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2081
2082                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2083                 claim_funds!(nodes[4], nodes[3], payment_preimage_2, 3_000_000);
2084
2085                 header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2086
2087                 nodes[4].block_notifier.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
2088                 for i in 3..TEST_FINAL_CLTV + 2 - CLTV_CLAIM_BUFFER + 1 {
2089                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2090                         nodes[4].block_notifier.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
2091                 }
2092
2093                 check_added_monitors!(nodes[4], 1);
2094                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2095
2096                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2097                 nodes[4].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, TEST_FINAL_CLTV - 5);
2098
2099                 check_preimage_claim(&nodes[4], &node_txn);
2100         }
2101         get_announce_close_broadcast_events(&nodes, 3, 4);
2102         assert_eq!(nodes[3].node.list_channels().len(), 0);
2103         assert_eq!(nodes[4].node.list_channels().len(), 0);
2104 }
2105
2106 #[test]
2107 fn test_justice_tx() {
2108         // Test justice txn built on revoked HTLC-Success tx, against both sides
2109         let mut alice_config = UserConfig::default();
2110         alice_config.channel_options.announced_channel = true;
2111         alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
2112         alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
2113         let mut bob_config = UserConfig::default();
2114         bob_config.channel_options.announced_channel = true;
2115         bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
2116         bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
2117         let user_cfgs = [Some(alice_config), Some(bob_config)];
2118         let chanmon_cfgs = create_chanmon_cfgs(2);
2119         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2120         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2121         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2122         // Create some new channels:
2123         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2124
2125         // A pending HTLC which will be revoked:
2126         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2127         // Get the will-be-revoked local txn from nodes[0]
2128         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2129         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2130         assert_eq!(revoked_local_txn[0].input.len(), 1);
2131         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2132         assert_eq!(revoked_local_txn[0].output.len(), 3); // Only HTLC, anchor, and output back to 0 are present
2133         assert_eq!(revoked_local_txn[1].input.len(), 1);
2134         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2135         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2136         // Revoke the old state
2137         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 3_000_000);
2138
2139         {
2140                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2141                 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2142                 {
2143                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2144                         assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2145                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2146
2147                         check_spends!(node_txn[0], revoked_local_txn[0]);
2148                         node_txn.swap_remove(0);
2149                         node_txn.truncate(1);
2150                 }
2151                 check_added_monitors!(nodes[1], 1);
2152                 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2153
2154                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2155                 // Verify broadcast of revoked HTLC-timeout
2156                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2157                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2158                 check_added_monitors!(nodes[0], 1);
2159                 // Broadcast revoked HTLC-timeout on node 1
2160                 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
2161                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2162         }
2163         get_announce_close_broadcast_events(&nodes, 0, 1);
2164
2165         assert_eq!(nodes[0].node.list_channels().len(), 0);
2166         assert_eq!(nodes[1].node.list_channels().len(), 0);
2167
2168         // We test justice_tx build by A on B's revoked HTLC-Success tx
2169         // Create some new channels:
2170         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2171         {
2172                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2173                 node_txn.clear();
2174         }
2175
2176         // A pending HTLC which will be revoked:
2177         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2178         // Get the will-be-revoked local txn from B
2179         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2180         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2181         assert_eq!(revoked_local_txn[0].input.len(), 1);
2182         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2183         assert_eq!(revoked_local_txn[0].output.len(), 3); // Only HTLC, anchor, and output back to A are present
2184         // Revoke the old state
2185         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4, 3_000_000);
2186         {
2187                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2188                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2189                 {
2190                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2191                         assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2192                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2193
2194                         check_spends!(node_txn[0], revoked_local_txn[0]);
2195                         node_txn.swap_remove(0);
2196                 }
2197                 check_added_monitors!(nodes[0], 1);
2198                 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2199
2200                 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2201                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2202                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2203                 check_added_monitors!(nodes[1], 1);
2204                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
2205                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2206         }
2207         get_announce_close_broadcast_events(&nodes, 0, 1);
2208         assert_eq!(nodes[0].node.list_channels().len(), 0);
2209         assert_eq!(nodes[1].node.list_channels().len(), 0);
2210 }
2211
2212 #[test]
2213 fn revoked_output_claim() {
2214         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2215         // transaction is broadcast by its counterparty
2216         let chanmon_cfgs = create_chanmon_cfgs(2);
2217         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2218         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2219         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2220         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2221         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2222         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2223         assert_eq!(revoked_local_txn.len(), 1);
2224         // Only outputs are the anchor and the full channel value back to nodes[0]:
2225         assert_eq!(revoked_local_txn[0].output.len(), 2);
2226         // Send a payment through, updating everyone's latest commitment txn
2227         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000, 5_000_000);
2228
2229         // Inform nodes[1] that nodes[0] broadcast a stale tx
2230         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2231         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2232         check_added_monitors!(nodes[1], 1);
2233         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2234         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2235
2236         check_spends!(node_txn[0], revoked_local_txn[0]);
2237         check_spends!(node_txn[1], chan_1.3);
2238
2239         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2240         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2241         get_announce_close_broadcast_events(&nodes, 0, 1);
2242         check_added_monitors!(nodes[0], 1)
2243 }
2244
2245 #[test]
2246 fn claim_htlc_outputs_shared_tx() {
2247         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2248         let chanmon_cfgs = create_chanmon_cfgs(2);
2249         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2250         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2251         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2252
2253         // Create some new channel:
2254         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2255
2256         // Rebalance the network to generate htlc in the two directions
2257         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2258         // 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
2259         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2260         let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2261
2262         // Get the will-be-revoked local txn from node[0]
2263         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2264         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2265         assert_eq!(revoked_local_txn[0].input.len(), 1);
2266         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2267         assert_eq!(revoked_local_txn[1].input.len(), 1);
2268         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2269         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2270         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2271
2272         //Revoke the old state
2273         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2274
2275         {
2276                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2277                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2278                 check_added_monitors!(nodes[0], 1);
2279                 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2280                 check_added_monitors!(nodes[1], 1);
2281                 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
2282                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2283
2284                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2285                 assert_eq!(node_txn.len(), 3); // ChannelMonitor: penalty tx, ChannelManager: local commitment + HTLC-timeout
2286
2287                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2288                 check_spends!(node_txn[0], revoked_local_txn[0]);
2289
2290                 let mut witness_lens = BTreeSet::new();
2291                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2292                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2293                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2294                 assert_eq!(witness_lens.len(), 3);
2295                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2296                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2297                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2298
2299                 // Next nodes[1] broadcasts its current local tx state:
2300                 assert_eq!(node_txn[1].input.len(), 1);
2301                 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2302
2303                 assert_eq!(node_txn[2].input.len(), 1);
2304                 let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
2305                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2306                 assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
2307                 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
2308                 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
2309         }
2310         get_announce_close_broadcast_events(&nodes, 0, 1);
2311         assert_eq!(nodes[0].node.list_channels().len(), 0);
2312         assert_eq!(nodes[1].node.list_channels().len(), 0);
2313 }
2314
2315 #[test]
2316 fn claim_htlc_outputs_single_tx() {
2317         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2318         let chanmon_cfgs = create_chanmon_cfgs(2);
2319         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2320         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2321         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2322
2323         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2324
2325         // Rebalance the network to generate htlc in the two directions
2326         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2327         // 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
2328         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2329         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2330         let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2331
2332         // Get the will-be-revoked local txn from node[0]
2333         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2334
2335         //Revoke the old state
2336         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2337
2338         {
2339                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2340                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2341                 check_added_monitors!(nodes[0], 1);
2342                 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2343                 check_added_monitors!(nodes[1], 1);
2344                 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
2345
2346                 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 200, true, header.bitcoin_hash());
2347                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2348
2349                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2350                 assert_eq!(node_txn.len(), 9);
2351                 // ChannelMonitor: justice tx revoked offered htlc, justice tx revoked received htlc, justice tx revoked to_local (3)
2352                 // ChannelManager: local commmitment + local HTLC-timeout (2)
2353                 // ChannelMonitor: bumped justice tx, after one increase, bumps on HTLC aren't generated not being substantial anymore, bump on revoked to_local isn't generated due to more room for expiration (2)
2354                 // ChannelMonitor: local commitment + local HTLC-timeout (2)
2355
2356                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2357                 assert_eq!(node_txn[2].input.len(), 1);
2358                 check_spends!(node_txn[2], chan_1.3);
2359                 assert_eq!(node_txn[3].input.len(), 1);
2360                 let witness_script = node_txn[3].input[0].witness.last().unwrap();
2361                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2362                 check_spends!(node_txn[3], node_txn[2]);
2363
2364                 // Justice transactions are indices 1-2-4
2365                 assert_eq!(node_txn[0].input.len(), 1);
2366                 assert_eq!(node_txn[1].input.len(), 1);
2367                 assert_eq!(node_txn[4].input.len(), 1);
2368
2369                 check_spends!(node_txn[0], revoked_local_txn[0]);
2370                 check_spends!(node_txn[1], revoked_local_txn[0]);
2371                 check_spends!(node_txn[4], revoked_local_txn[0]);
2372
2373                 let mut witness_lens = BTreeSet::new();
2374                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2375                 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
2376                 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2377                 assert_eq!(witness_lens.len(), 3);
2378                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2379                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2380                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2381         }
2382         get_announce_close_broadcast_events(&nodes, 0, 1);
2383         assert_eq!(nodes[0].node.list_channels().len(), 0);
2384         assert_eq!(nodes[1].node.list_channels().len(), 0);
2385 }
2386
2387 #[test]
2388 fn test_htlc_on_chain_success() {
2389         // Test that in case of a unilateral close onchain, we detect the state of output thanks to
2390         // ChainWatchInterface and pass the preimage backward accordingly. So here we test that ChannelManager is
2391         // broadcasting the right event to other nodes in payment path.
2392         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2393         // A --------------------> B ----------------------> C (preimage)
2394         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2395         // commitment transaction was broadcast.
2396         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2397         // towards B.
2398         // B should be able to claim via preimage if A then broadcasts its local tx.
2399         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2400         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2401         // PaymentSent event).
2402
2403         let chanmon_cfgs = create_chanmon_cfgs(3);
2404         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2405         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2406         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2407
2408         // Create some initial channels
2409         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2410         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2411
2412         // Rebalance the network a bit by relaying one payment through all the channels...
2413         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2414         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2415
2416         let (our_payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2417         let (our_payment_preimage_2, _payment_hash_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2418         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2419
2420         // Broadcast legit commitment tx from C on B's chain
2421         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2422         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2423         assert_eq!(commitment_tx.len(), 1);
2424         check_spends!(commitment_tx[0], chan_2.3);
2425         nodes[2].node.claim_funds(our_payment_preimage, &None, 3_000_000);
2426         nodes[2].node.claim_funds(our_payment_preimage_2, &None, 3_000_000);
2427         check_added_monitors!(nodes[2], 2);
2428         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2429         assert!(updates.update_add_htlcs.is_empty());
2430         assert!(updates.update_fail_htlcs.is_empty());
2431         assert!(updates.update_fail_malformed_htlcs.is_empty());
2432         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2433
2434         nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2435         check_closed_broadcast!(nodes[2], false);
2436         check_added_monitors!(nodes[2], 1);
2437         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 3 (commitment tx, 2*htlc-success tx), ChannelMonitor : 2 (2 * HTLC-Success tx)
2438         assert_eq!(node_txn.len(), 5);
2439         assert_eq!(node_txn[0], node_txn[3]);
2440         assert_eq!(node_txn[1], node_txn[4]);
2441         assert_eq!(node_txn[2], commitment_tx[0]);
2442         check_spends!(node_txn[0], commitment_tx[0]);
2443         check_spends!(node_txn[1], commitment_tx[0]);
2444         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2445         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2446         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2447         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2448         assert_eq!(node_txn[0].lock_time, 0);
2449         assert_eq!(node_txn[1].lock_time, 0);
2450
2451         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2452         nodes[1].block_notifier.block_connected(&Block { header, txdata: node_txn}, 1);
2453         {
2454                 let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
2455                 assert_eq!(added_monitors.len(), 1);
2456                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2457                 added_monitors.clear();
2458         }
2459         let events = nodes[1].node.get_and_clear_pending_msg_events();
2460         {
2461                 let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
2462                 assert_eq!(added_monitors.len(), 2);
2463                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2464                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2465                 added_monitors.clear();
2466         }
2467         assert_eq!(events.len(), 2);
2468         match events[0] {
2469                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2470                 _ => panic!("Unexpected event"),
2471         }
2472         match events[1] {
2473                 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, .. } } => {
2474                         assert!(update_add_htlcs.is_empty());
2475                         assert!(update_fail_htlcs.is_empty());
2476                         assert_eq!(update_fulfill_htlcs.len(), 1);
2477                         assert!(update_fail_malformed_htlcs.is_empty());
2478                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2479                 },
2480                 _ => panic!("Unexpected event"),
2481         };
2482         macro_rules! check_tx_local_broadcast {
2483                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2484                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2485                         assert_eq!(node_txn.len(), 5);
2486                         // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2487                         // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2488                         check_spends!(node_txn[0], $commitment_tx);
2489                         check_spends!(node_txn[1], $commitment_tx);
2490                         assert_ne!(node_txn[0].lock_time, 0);
2491                         assert_ne!(node_txn[1].lock_time, 0);
2492                         if $htlc_offered {
2493                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2494                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2495                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2496                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2497                         } else {
2498                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2499                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2500                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2501                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2502                         }
2503                         check_spends!(node_txn[2], $chan_tx);
2504                         check_spends!(node_txn[3], node_txn[2]);
2505                         check_spends!(node_txn[4], node_txn[2]);
2506                         assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), 71);
2507                         assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2508                         assert_eq!(node_txn[4].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2509                         assert!(node_txn[3].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2510                         assert!(node_txn[4].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2511                         assert_ne!(node_txn[3].lock_time, 0);
2512                         assert_ne!(node_txn[4].lock_time, 0);
2513                         node_txn.clear();
2514                 } }
2515         }
2516         // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2517         // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2518         // timeout-claim of the output that nodes[2] just claimed via success.
2519         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2520
2521         // Broadcast legit commitment tx from A on B's chain
2522         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2523         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2524         check_spends!(commitment_tx[0], chan_1.3);
2525         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2526         check_closed_broadcast!(nodes[1], false);
2527         check_added_monitors!(nodes[1], 1);
2528         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 1 (HTLC-Success)
2529         assert_eq!(node_txn.len(), 4);
2530         check_spends!(node_txn[0], commitment_tx[0]);
2531         assert_eq!(node_txn[0].input.len(), 2);
2532         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2533         assert_eq!(node_txn[0].input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2534         assert_eq!(node_txn[0].lock_time, 0);
2535         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2536         check_spends!(node_txn[1], chan_1.3);
2537         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
2538         check_spends!(node_txn[2], node_txn[1]);
2539         check_spends!(node_txn[3], node_txn[1]);
2540         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2541         // we already checked the same situation with A.
2542
2543         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2544         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone()] }, 1);
2545         check_closed_broadcast!(nodes[0], false);
2546         check_added_monitors!(nodes[0], 1);
2547         let events = nodes[0].node.get_and_clear_pending_events();
2548         assert_eq!(events.len(), 2);
2549         let mut first_claimed = false;
2550         for event in events {
2551                 match event {
2552                         Event::PaymentSent { payment_preimage } => {
2553                                 if payment_preimage == our_payment_preimage {
2554                                         assert!(!first_claimed);
2555                                         first_claimed = true;
2556                                 } else {
2557                                         assert_eq!(payment_preimage, our_payment_preimage_2);
2558                                 }
2559                         },
2560                         _ => panic!("Unexpected event"),
2561                 }
2562         }
2563         check_tx_local_broadcast!(nodes[0], true, commitment_tx[0], chan_1.3);
2564 }
2565
2566 #[test]
2567 fn test_htlc_on_chain_timeout() {
2568         // Test that in case of a unilateral close onchain, we detect the state of output thanks to
2569         // ChainWatchInterface and timeout the HTLC backward accordingly. So here we test that ChannelManager is
2570         // broadcasting the right event to other nodes in payment path.
2571         // A ------------------> B ----------------------> C (timeout)
2572         //    B's commitment tx                 C's commitment tx
2573         //            \                                  \
2574         //         B's HTLC timeout tx               B's timeout tx
2575
2576         let chanmon_cfgs = create_chanmon_cfgs(3);
2577         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2578         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2579         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2580
2581         // Create some intial channels
2582         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2583         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2584
2585         // Rebalance the network a bit by relaying one payment thorugh all the channels...
2586         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2587         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2588
2589         let (_payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2590         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2591
2592         // Broadcast legit commitment tx from C on B's chain
2593         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2594         check_spends!(commitment_tx[0], chan_2.3);
2595         nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
2596         check_added_monitors!(nodes[2], 0);
2597         expect_pending_htlcs_forwardable!(nodes[2]);
2598         check_added_monitors!(nodes[2], 1);
2599
2600         let events = nodes[2].node.get_and_clear_pending_msg_events();
2601         assert_eq!(events.len(), 1);
2602         match events[0] {
2603                 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, .. } } => {
2604                         assert!(update_add_htlcs.is_empty());
2605                         assert!(!update_fail_htlcs.is_empty());
2606                         assert!(update_fulfill_htlcs.is_empty());
2607                         assert!(update_fail_malformed_htlcs.is_empty());
2608                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2609                 },
2610                 _ => panic!("Unexpected event"),
2611         };
2612         nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2613         check_closed_broadcast!(nodes[2], false);
2614         check_added_monitors!(nodes[2], 1);
2615         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2616         assert_eq!(node_txn.len(), 1);
2617         check_spends!(node_txn[0], chan_2.3);
2618         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2619
2620         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2621         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2622         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
2623         let timeout_tx;
2624         {
2625                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2626                 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2627                 assert_eq!(node_txn[1], node_txn[3]);
2628                 assert_eq!(node_txn[2], node_txn[4]);
2629
2630                 check_spends!(node_txn[0], commitment_tx[0]);
2631                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2632
2633                 check_spends!(node_txn[1], chan_2.3);
2634                 check_spends!(node_txn[2], node_txn[1]);
2635                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
2636                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2637
2638                 timeout_tx = node_txn[0].clone();
2639                 node_txn.clear();
2640         }
2641
2642         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![timeout_tx]}, 1);
2643         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
2644         check_added_monitors!(nodes[1], 1);
2645         check_closed_broadcast!(nodes[1], false);
2646
2647         expect_pending_htlcs_forwardable!(nodes[1]);
2648         check_added_monitors!(nodes[1], 1);
2649         let events = nodes[1].node.get_and_clear_pending_msg_events();
2650         assert_eq!(events.len(), 1);
2651         match events[0] {
2652                 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, .. } } => {
2653                         assert!(update_add_htlcs.is_empty());
2654                         assert!(!update_fail_htlcs.is_empty());
2655                         assert!(update_fulfill_htlcs.is_empty());
2656                         assert!(update_fail_malformed_htlcs.is_empty());
2657                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2658                 },
2659                 _ => panic!("Unexpected event"),
2660         };
2661         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
2662         assert_eq!(node_txn.len(), 0);
2663
2664         // Broadcast legit commitment tx from B on A's chain
2665         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
2666         check_spends!(commitment_tx[0], chan_1.3);
2667
2668         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
2669         check_closed_broadcast!(nodes[0], false);
2670         check_added_monitors!(nodes[0], 1);
2671         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 1 timeout tx
2672         assert_eq!(node_txn.len(), 3);
2673         check_spends!(node_txn[0], commitment_tx[0]);
2674         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2675         check_spends!(node_txn[1], chan_1.3);
2676         check_spends!(node_txn[2], node_txn[1]);
2677         assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
2678         assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2679 }
2680
2681 #[test]
2682 fn test_simple_commitment_revoked_fail_backward() {
2683         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
2684         // and fail backward accordingly.
2685
2686         let chanmon_cfgs = create_chanmon_cfgs(3);
2687         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2688         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2689         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2690
2691         // Create some initial channels
2692         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2693         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2694
2695         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2696         // Get the will-be-revoked local txn from nodes[2]
2697         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
2698         // Revoke the old state
2699         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, 3_000_000);
2700
2701         let (_, payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2702
2703         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2704         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2705         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
2706         check_added_monitors!(nodes[1], 1);
2707         check_closed_broadcast!(nodes[1], false);
2708
2709         expect_pending_htlcs_forwardable!(nodes[1]);
2710         check_added_monitors!(nodes[1], 1);
2711         let events = nodes[1].node.get_and_clear_pending_msg_events();
2712         assert_eq!(events.len(), 1);
2713         match events[0] {
2714                 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, .. } } => {
2715                         assert!(update_add_htlcs.is_empty());
2716                         assert_eq!(update_fail_htlcs.len(), 1);
2717                         assert!(update_fulfill_htlcs.is_empty());
2718                         assert!(update_fail_malformed_htlcs.is_empty());
2719                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2720
2721                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
2722                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
2723
2724                         let events = nodes[0].node.get_and_clear_pending_msg_events();
2725                         assert_eq!(events.len(), 1);
2726                         match events[0] {
2727                                 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
2728                                 _ => panic!("Unexpected event"),
2729                         }
2730                         expect_payment_failed!(nodes[0], payment_hash, false);
2731                 },
2732                 _ => panic!("Unexpected event"),
2733         }
2734 }
2735
2736 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
2737         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
2738         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
2739         // commitment transaction anymore.
2740         // To do this, we have the peer which will broadcast a revoked commitment transaction send
2741         // a number of update_fail/commitment_signed updates without ever sending the RAA in
2742         // response to our commitment_signed. This is somewhat misbehavior-y, though not
2743         // technically disallowed and we should probably handle it reasonably.
2744         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
2745         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
2746         // transactions:
2747         // * Once we move it out of our holding cell/add it, we will immediately include it in a
2748         //   commitment_signed (implying it will be in the latest remote commitment transaction).
2749         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
2750         //   and once they revoke the previous commitment transaction (allowing us to send a new
2751         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
2752         let chanmon_cfgs = create_chanmon_cfgs(3);
2753         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2754         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2755         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2756
2757         // Create some initial channels
2758         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2759         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2760
2761         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
2762         // Get the will-be-revoked local txn from nodes[2]
2763         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
2764         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 3 });
2765         // Revoke the old state
2766         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, if no_to_remote { 10_000 } else { 3_000_000});
2767
2768         let value = if use_dust {
2769                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
2770                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
2771                 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().our_dust_limit_satoshis * 1000
2772         } else { 3000000 };
2773
2774         let (_, first_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2775         let (_, second_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2776         let (_, third_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2777
2778         assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash, &None));
2779         expect_pending_htlcs_forwardable!(nodes[2]);
2780         check_added_monitors!(nodes[2], 1);
2781         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2782         assert!(updates.update_add_htlcs.is_empty());
2783         assert!(updates.update_fulfill_htlcs.is_empty());
2784         assert!(updates.update_fail_malformed_htlcs.is_empty());
2785         assert_eq!(updates.update_fail_htlcs.len(), 1);
2786         assert!(updates.update_fee.is_none());
2787         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2788         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
2789         // Drop the last RAA from 3 -> 2
2790
2791         assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash, &None));
2792         expect_pending_htlcs_forwardable!(nodes[2]);
2793         check_added_monitors!(nodes[2], 1);
2794         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2795         assert!(updates.update_add_htlcs.is_empty());
2796         assert!(updates.update_fulfill_htlcs.is_empty());
2797         assert!(updates.update_fail_malformed_htlcs.is_empty());
2798         assert_eq!(updates.update_fail_htlcs.len(), 1);
2799         assert!(updates.update_fee.is_none());
2800         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2801         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
2802         check_added_monitors!(nodes[1], 1);
2803         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
2804         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
2805         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
2806         check_added_monitors!(nodes[2], 1);
2807
2808         assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash, &None));
2809         expect_pending_htlcs_forwardable!(nodes[2]);
2810         check_added_monitors!(nodes[2], 1);
2811         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2812         assert!(updates.update_add_htlcs.is_empty());
2813         assert!(updates.update_fulfill_htlcs.is_empty());
2814         assert!(updates.update_fail_malformed_htlcs.is_empty());
2815         assert_eq!(updates.update_fail_htlcs.len(), 1);
2816         assert!(updates.update_fee.is_none());
2817         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2818         // At this point first_payment_hash has dropped out of the latest two commitment
2819         // transactions that nodes[1] is tracking...
2820         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
2821         check_added_monitors!(nodes[1], 1);
2822         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
2823         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
2824         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
2825         check_added_monitors!(nodes[2], 1);
2826
2827         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
2828         // on nodes[2]'s RAA.
2829         let (_, fourth_payment_hash) = get_payment_preimage_hash!(nodes[0]);
2830         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
2831         let logger = test_utils::TestLogger::new();
2832         let route = get_route(&nodes[1].node.get_our_node_id(), net_graph_msg_handler, &nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
2833         nodes[1].node.send_payment(&route, fourth_payment_hash, &None).unwrap();
2834         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2835         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2836         check_added_monitors!(nodes[1], 0);
2837
2838         if deliver_bs_raa {
2839                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
2840                 // One monitor for the new revocation preimage, no second on as we won't generate a new
2841                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
2842                 check_added_monitors!(nodes[1], 1);
2843                 let events = nodes[1].node.get_and_clear_pending_events();
2844                 assert_eq!(events.len(), 1);
2845                 match events[0] {
2846                         Event::PendingHTLCsForwardable { .. } => { },
2847                         _ => panic!("Unexpected event"),
2848                 };
2849                 // Deliberately don't process the pending fail-back so they all fail back at once after
2850                 // block connection just like the !deliver_bs_raa case
2851         }
2852
2853         let mut failed_htlcs = HashSet::new();
2854         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2855
2856         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2857         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2858         check_added_monitors!(nodes[1], 1);
2859         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
2860
2861         let events = nodes[1].node.get_and_clear_pending_events();
2862         assert_eq!(events.len(), if deliver_bs_raa { 1 } else { 2 });
2863         match events[0] {
2864                 Event::PaymentFailed { ref payment_hash, .. } => {
2865                         assert_eq!(*payment_hash, fourth_payment_hash);
2866                 },
2867                 _ => panic!("Unexpected event"),
2868         }
2869         if !deliver_bs_raa {
2870                 match events[1] {
2871                         Event::PendingHTLCsForwardable { .. } => { },
2872                         _ => panic!("Unexpected event"),
2873                 };
2874         }
2875         nodes[1].node.process_pending_htlc_forwards();
2876         check_added_monitors!(nodes[1], 1);
2877
2878         let events = nodes[1].node.get_and_clear_pending_msg_events();
2879         assert_eq!(events.len(), if deliver_bs_raa { 3 } else { 2 });
2880         match events[if deliver_bs_raa { 1 } else { 0 }] {
2881                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
2882                 _ => panic!("Unexpected event"),
2883         }
2884         if deliver_bs_raa {
2885                 match events[0] {
2886                         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, .. } } => {
2887                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
2888                                 assert_eq!(update_add_htlcs.len(), 1);
2889                                 assert!(update_fulfill_htlcs.is_empty());
2890                                 assert!(update_fail_htlcs.is_empty());
2891                                 assert!(update_fail_malformed_htlcs.is_empty());
2892                         },
2893                         _ => panic!("Unexpected event"),
2894                 }
2895         }
2896         match events[if deliver_bs_raa { 2 } else { 1 }] {
2897                 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, .. } } => {
2898                         assert!(update_add_htlcs.is_empty());
2899                         assert_eq!(update_fail_htlcs.len(), 3);
2900                         assert!(update_fulfill_htlcs.is_empty());
2901                         assert!(update_fail_malformed_htlcs.is_empty());
2902                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2903
2904                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
2905                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
2906                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
2907
2908                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
2909
2910                         let events = nodes[0].node.get_and_clear_pending_msg_events();
2911                         // If we delivered B's RAA we got an unknown preimage error, not something
2912                         // that we should update our routing table for.
2913                         assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 3 });
2914                         for event in events {
2915                                 match event {
2916                                         MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
2917                                         _ => panic!("Unexpected event"),
2918                                 }
2919                         }
2920                         let events = nodes[0].node.get_and_clear_pending_events();
2921                         assert_eq!(events.len(), 3);
2922                         match events[0] {
2923                                 Event::PaymentFailed { ref payment_hash, .. } => {
2924                                         assert!(failed_htlcs.insert(payment_hash.0));
2925                                 },
2926                                 _ => panic!("Unexpected event"),
2927                         }
2928                         match events[1] {
2929                                 Event::PaymentFailed { ref payment_hash, .. } => {
2930                                         assert!(failed_htlcs.insert(payment_hash.0));
2931                                 },
2932                                 _ => panic!("Unexpected event"),
2933                         }
2934                         match events[2] {
2935                                 Event::PaymentFailed { ref payment_hash, .. } => {
2936                                         assert!(failed_htlcs.insert(payment_hash.0));
2937                                 },
2938                                 _ => panic!("Unexpected event"),
2939                         }
2940                 },
2941                 _ => panic!("Unexpected event"),
2942         }
2943
2944         assert!(failed_htlcs.contains(&first_payment_hash.0));
2945         assert!(failed_htlcs.contains(&second_payment_hash.0));
2946         assert!(failed_htlcs.contains(&third_payment_hash.0));
2947 }
2948
2949 #[test]
2950 fn test_commitment_revoked_fail_backward_exhaustive_a() {
2951         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
2952         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
2953         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
2954         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
2955 }
2956
2957 #[test]
2958 fn test_commitment_revoked_fail_backward_exhaustive_b() {
2959         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
2960         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
2961         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
2962         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
2963 }
2964
2965 #[test]
2966 fn fail_backward_pending_htlc_upon_channel_failure() {
2967         let chanmon_cfgs = create_chanmon_cfgs(2);
2968         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2969         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2970         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2971         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
2972         let logger = test_utils::TestLogger::new();
2973
2974         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
2975         {
2976                 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
2977                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
2978                 let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &Vec::new(), 50_000, TEST_FINAL_CLTV, &logger).unwrap();
2979                 nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
2980                 check_added_monitors!(nodes[0], 1);
2981
2982                 let payment_event = {
2983                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2984                         assert_eq!(events.len(), 1);
2985                         SendEvent::from_event(events.remove(0))
2986                 };
2987                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
2988                 assert_eq!(payment_event.msgs.len(), 1);
2989         }
2990
2991         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
2992         let (_, failed_payment_hash) = get_payment_preimage_hash!(nodes[0]);
2993         {
2994                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
2995                 let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &Vec::new(), 50_000, TEST_FINAL_CLTV, &logger).unwrap();
2996                 nodes[0].node.send_payment(&route, failed_payment_hash, &None).unwrap();
2997                 check_added_monitors!(nodes[0], 0);
2998
2999                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3000         }
3001
3002         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3003         {
3004                 let (_, payment_hash) = get_payment_preimage_hash!(nodes[1]);
3005
3006                 let secp_ctx = Secp256k1::new();
3007                 let session_priv = {
3008                         let mut session_key = [0; 32];
3009                         let mut rng = thread_rng();
3010                         rng.fill_bytes(&mut session_key);
3011                         SecretKey::from_slice(&session_key).expect("RNG is bad!")
3012                 };
3013
3014                 let current_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
3015                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3016                 let route = get_route(&nodes[1].node.get_our_node_id(), net_graph_msg_handler, &nodes[0].node.get_our_node_id(), None, &Vec::new(), 50_000, TEST_FINAL_CLTV, &logger).unwrap();
3017                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &None, current_height).unwrap();
3018                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3019                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3020
3021                 // Send a 0-msat update_add_htlc to fail the channel.
3022                 let update_add_htlc = msgs::UpdateAddHTLC {
3023                         channel_id: chan.2,
3024                         htlc_id: 0,
3025                         amount_msat: 0,
3026                         payment_hash,
3027                         cltv_expiry,
3028                         onion_routing_packet,
3029                 };
3030                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3031         }
3032
3033         // Check that Alice fails backward the pending HTLC from the second payment.
3034         expect_payment_failed!(nodes[0], failed_payment_hash, true);
3035         check_closed_broadcast!(nodes[0], true);
3036         check_added_monitors!(nodes[0], 1);
3037 }
3038
3039 #[test]
3040 fn test_htlc_ignore_latest_remote_commitment() {
3041         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3042         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3043         let chanmon_cfgs = create_chanmon_cfgs(2);
3044         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3045         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3046         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3047         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3048
3049         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3050         nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id);
3051         check_closed_broadcast!(nodes[0], false);
3052         check_added_monitors!(nodes[0], 1);
3053
3054         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3055         assert_eq!(node_txn.len(), 2);
3056
3057         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3058         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]}, 1);
3059         check_closed_broadcast!(nodes[1], false);
3060         check_added_monitors!(nodes[1], 1);
3061
3062         // Duplicate the block_connected call since this may happen due to other listeners
3063         // registering new transactions
3064         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]}, 1);
3065 }
3066
3067 #[test]
3068 fn test_force_close_fail_back() {
3069         // Check which HTLCs are failed-backwards on channel force-closure
3070         let chanmon_cfgs = create_chanmon_cfgs(3);
3071         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3072         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3073         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3074         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3075         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3076         let logger = test_utils::TestLogger::new();
3077
3078         let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3079
3080         let mut payment_event = {
3081                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3082                 let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, 42, &logger).unwrap();
3083                 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
3084                 check_added_monitors!(nodes[0], 1);
3085
3086                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3087                 assert_eq!(events.len(), 1);
3088                 SendEvent::from_event(events.remove(0))
3089         };
3090
3091         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3092         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3093
3094         expect_pending_htlcs_forwardable!(nodes[1]);
3095
3096         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3097         assert_eq!(events_2.len(), 1);
3098         payment_event = SendEvent::from_event(events_2.remove(0));
3099         assert_eq!(payment_event.msgs.len(), 1);
3100
3101         check_added_monitors!(nodes[1], 1);
3102         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3103         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3104         check_added_monitors!(nodes[2], 1);
3105         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3106
3107         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3108         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3109         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3110
3111         nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id);
3112         check_closed_broadcast!(nodes[2], false);
3113         check_added_monitors!(nodes[2], 1);
3114         let tx = {
3115                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3116                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3117                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3118                 // back to nodes[1] upon timeout otherwise.
3119                 assert_eq!(node_txn.len(), 1);
3120                 node_txn.remove(0)
3121         };
3122
3123         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3124         nodes[1].block_notifier.block_connected_checked(&header, 1, &[&tx], &[1]);
3125
3126         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3127         check_closed_broadcast!(nodes[1], false);
3128         check_added_monitors!(nodes[1], 1);
3129
3130         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3131         {
3132                 let mut monitors = nodes[2].chan_monitor.simple_monitor.monitors.lock().unwrap();
3133                 monitors.get_mut(&OutPoint::new(Txid::from_slice(&payment_event.commitment_msg.channel_id[..]).unwrap(), 0)).unwrap()
3134                         .provide_payment_preimage(&our_payment_hash, &our_payment_preimage);
3135         }
3136         nodes[2].block_notifier.block_connected_checked(&header, 1, &[&tx], &[1]);
3137         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3138         assert_eq!(node_txn.len(), 1);
3139         assert_eq!(node_txn[0].input.len(), 1);
3140         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3141         assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3142         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3143
3144         check_spends!(node_txn[0], tx);
3145 }
3146
3147 #[test]
3148 fn test_unconf_chan() {
3149         // After creating a chan between nodes, we disconnect all blocks previously seen to force a channel close on nodes[0] side
3150         let chanmon_cfgs = create_chanmon_cfgs(2);
3151         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3152         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3153         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3154         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3155
3156         let channel_state = nodes[0].node.channel_state.lock().unwrap();
3157         assert_eq!(channel_state.by_id.len(), 1);
3158         assert_eq!(channel_state.short_to_id.len(), 1);
3159         mem::drop(channel_state);
3160
3161         let mut headers = Vec::new();
3162         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3163         headers.push(header.clone());
3164         for _i in 2..100 {
3165                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3166                 headers.push(header.clone());
3167         }
3168         let mut height = 99;
3169         while !headers.is_empty() {
3170                 nodes[0].node.block_disconnected(&headers.pop().unwrap(), height);
3171                 height -= 1;
3172         }
3173         check_closed_broadcast!(nodes[0], false);
3174         check_added_monitors!(nodes[0], 1);
3175         let channel_state = nodes[0].node.channel_state.lock().unwrap();
3176         assert_eq!(channel_state.by_id.len(), 0);
3177         assert_eq!(channel_state.short_to_id.len(), 0);
3178 }
3179
3180 #[test]
3181 fn test_simple_peer_disconnect() {
3182         // Test that we can reconnect when there are no lost messages
3183         let chanmon_cfgs = create_chanmon_cfgs(3);
3184         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3185         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3186         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3187         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3188         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3189
3190         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3191         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3192         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3193
3194         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3195         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3196         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3197         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1, 1_000_000);
3198
3199         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3200         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3201         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3202
3203         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3204         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3205         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3206         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3207
3208         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3209         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3210
3211         claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3, 1_000_000);
3212         fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
3213
3214         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3215         {
3216                 let events = nodes[0].node.get_and_clear_pending_events();
3217                 assert_eq!(events.len(), 2);
3218                 match events[0] {
3219                         Event::PaymentSent { payment_preimage } => {
3220                                 assert_eq!(payment_preimage, payment_preimage_3);
3221                         },
3222                         _ => panic!("Unexpected event"),
3223                 }
3224                 match events[1] {
3225                         Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
3226                                 assert_eq!(payment_hash, payment_hash_5);
3227                                 assert!(rejected_by_dest);
3228                         },
3229                         _ => panic!("Unexpected event"),
3230                 }
3231         }
3232
3233         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4, 1_000_000);
3234         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3235 }
3236
3237 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
3238         // Test that we can reconnect when in-flight HTLC updates get dropped
3239         let chanmon_cfgs = create_chanmon_cfgs(2);
3240         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3241         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3242         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3243         if messages_delivered == 0 {
3244                 create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3245                 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3246         } else {
3247                 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3248         }
3249
3250         let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
3251
3252         let logger = test_utils::TestLogger::new();
3253         let payment_event = {
3254                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3255                 let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), Some(&nodes[0].node.list_usable_channels()), &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3256                 nodes[0].node.send_payment(&route, payment_hash_1, &None).unwrap();
3257                 check_added_monitors!(nodes[0], 1);
3258
3259                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3260                 assert_eq!(events.len(), 1);
3261                 SendEvent::from_event(events.remove(0))
3262         };
3263         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3264
3265         if messages_delivered < 2 {
3266                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3267         } else {
3268                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3269                 if messages_delivered >= 3 {
3270                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3271                         check_added_monitors!(nodes[1], 1);
3272                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3273
3274                         if messages_delivered >= 4 {
3275                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3276                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3277                                 check_added_monitors!(nodes[0], 1);
3278
3279                                 if messages_delivered >= 5 {
3280                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3281                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3282                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3283                                         check_added_monitors!(nodes[0], 1);
3284
3285                                         if messages_delivered >= 6 {
3286                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3287                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3288                                                 check_added_monitors!(nodes[1], 1);
3289                                         }
3290                                 }
3291                         }
3292                 }
3293         }
3294
3295         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3296         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3297         if messages_delivered < 3 {
3298                 // Even if the funding_locked messages get exchanged, as long as nothing further was
3299                 // received on either side, both sides will need to resend them.
3300                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
3301         } else if messages_delivered == 3 {
3302                 // nodes[0] still wants its RAA + commitment_signed
3303                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
3304         } else if messages_delivered == 4 {
3305                 // nodes[0] still wants its commitment_signed
3306                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3307         } else if messages_delivered == 5 {
3308                 // nodes[1] still wants its final RAA
3309                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3310         } else if messages_delivered == 6 {
3311                 // Everything was delivered...
3312                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3313         }
3314
3315         let events_1 = nodes[1].node.get_and_clear_pending_events();
3316         assert_eq!(events_1.len(), 1);
3317         match events_1[0] {
3318                 Event::PendingHTLCsForwardable { .. } => { },
3319                 _ => panic!("Unexpected event"),
3320         };
3321
3322         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3323         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3324         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3325
3326         nodes[1].node.process_pending_htlc_forwards();
3327
3328         let events_2 = nodes[1].node.get_and_clear_pending_events();
3329         assert_eq!(events_2.len(), 1);
3330         match events_2[0] {
3331                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
3332                         assert_eq!(payment_hash_1, *payment_hash);
3333                         assert_eq!(*payment_secret, None);
3334                         assert_eq!(amt, 1000000);
3335                 },
3336                 _ => panic!("Unexpected event"),
3337         }
3338
3339         nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000);
3340         check_added_monitors!(nodes[1], 1);
3341
3342         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3343         assert_eq!(events_3.len(), 1);
3344         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3345                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3346                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3347                         assert!(updates.update_add_htlcs.is_empty());
3348                         assert!(updates.update_fail_htlcs.is_empty());
3349                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3350                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3351                         assert!(updates.update_fee.is_none());
3352                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3353                 },
3354                 _ => panic!("Unexpected event"),
3355         };
3356
3357         if messages_delivered >= 1 {
3358                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3359
3360                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3361                 assert_eq!(events_4.len(), 1);
3362                 match events_4[0] {
3363                         Event::PaymentSent { ref payment_preimage } => {
3364                                 assert_eq!(payment_preimage_1, *payment_preimage);
3365                         },
3366                         _ => panic!("Unexpected event"),
3367                 }
3368
3369                 if messages_delivered >= 2 {
3370                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3371                         check_added_monitors!(nodes[0], 1);
3372                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3373
3374                         if messages_delivered >= 3 {
3375                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3376                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3377                                 check_added_monitors!(nodes[1], 1);
3378
3379                                 if messages_delivered >= 4 {
3380                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3381                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3382                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3383                                         check_added_monitors!(nodes[1], 1);
3384
3385                                         if messages_delivered >= 5 {
3386                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3387                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3388                                                 check_added_monitors!(nodes[0], 1);
3389                                         }
3390                                 }
3391                         }
3392                 }
3393         }
3394
3395         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3396         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3397         if messages_delivered < 2 {
3398                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
3399                 //TODO: Deduplicate PaymentSent events, then enable this if:
3400                 //if messages_delivered < 1 {
3401                         let events_4 = nodes[0].node.get_and_clear_pending_events();
3402                         assert_eq!(events_4.len(), 1);
3403                         match events_4[0] {
3404                                 Event::PaymentSent { ref payment_preimage } => {
3405                                         assert_eq!(payment_preimage_1, *payment_preimage);
3406                                 },
3407                                 _ => panic!("Unexpected event"),
3408                         }
3409                 //}
3410         } else if messages_delivered == 2 {
3411                 // nodes[0] still wants its RAA + commitment_signed
3412                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
3413         } else if messages_delivered == 3 {
3414                 // nodes[0] still wants its commitment_signed
3415                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
3416         } else if messages_delivered == 4 {
3417                 // nodes[1] still wants its final RAA
3418                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3419         } else if messages_delivered == 5 {
3420                 // Everything was delivered...
3421                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3422         }
3423
3424         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3425         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3426         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3427
3428         // Channel should still work fine...
3429         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3430         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), Some(&nodes[0].node.list_usable_channels()), &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3431         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3432         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
3433 }
3434
3435 #[test]
3436 fn test_drop_messages_peer_disconnect_a() {
3437         do_test_drop_messages_peer_disconnect(0);
3438         do_test_drop_messages_peer_disconnect(1);
3439         do_test_drop_messages_peer_disconnect(2);
3440         do_test_drop_messages_peer_disconnect(3);
3441 }
3442
3443 #[test]
3444 fn test_drop_messages_peer_disconnect_b() {
3445         do_test_drop_messages_peer_disconnect(4);
3446         do_test_drop_messages_peer_disconnect(5);
3447         do_test_drop_messages_peer_disconnect(6);
3448 }
3449
3450 #[test]
3451 fn test_funding_peer_disconnect() {
3452         // Test that we can lock in our funding tx while disconnected
3453         let chanmon_cfgs = create_chanmon_cfgs(2);
3454         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3455         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3456         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3457         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3458
3459         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3460         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3461
3462         confirm_transaction(&nodes[0].block_notifier, &nodes[0].chain_monitor, &tx, tx.version);
3463         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3464         assert_eq!(events_1.len(), 1);
3465         match events_1[0] {
3466                 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
3467                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3468                 },
3469                 _ => panic!("Unexpected event"),
3470         }
3471
3472         reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3473
3474         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3475         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3476
3477         confirm_transaction(&nodes[1].block_notifier, &nodes[1].chain_monitor, &tx, tx.version);
3478         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3479         assert_eq!(events_2.len(), 2);
3480         let funding_locked = match events_2[0] {
3481                 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3482                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3483                         msg.clone()
3484                 },
3485                 _ => panic!("Unexpected event"),
3486         };
3487         let bs_announcement_sigs = match events_2[1] {
3488                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3489                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3490                         msg.clone()
3491                 },
3492                 _ => panic!("Unexpected event"),
3493         };
3494
3495         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3496
3497         nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &funding_locked);
3498         nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3499         let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3500         assert_eq!(events_3.len(), 2);
3501         let as_announcement_sigs = match events_3[0] {
3502                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3503                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3504                         msg.clone()
3505                 },
3506                 _ => panic!("Unexpected event"),
3507         };
3508         let (as_announcement, as_update) = match events_3[1] {
3509                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3510                         (msg.clone(), update_msg.clone())
3511                 },
3512                 _ => panic!("Unexpected event"),
3513         };
3514
3515         nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3516         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3517         assert_eq!(events_4.len(), 1);
3518         let (_, bs_update) = match events_4[0] {
3519                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3520                         (msg.clone(), update_msg.clone())
3521                 },
3522                 _ => panic!("Unexpected event"),
3523         };
3524
3525         nodes[0].net_graph_msg_handler.handle_channel_announcement(&as_announcement).unwrap();
3526         nodes[0].net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3527         nodes[0].net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3528
3529         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3530         let logger = test_utils::TestLogger::new();
3531         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3532         let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
3533         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage, 1_000_000);
3534 }
3535
3536 #[test]
3537 fn test_drop_messages_peer_disconnect_dual_htlc() {
3538         // Test that we can handle reconnecting when both sides of a channel have pending
3539         // commitment_updates when we disconnect.
3540         let chanmon_cfgs = create_chanmon_cfgs(2);
3541         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3542         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3543         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3544         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3545         let logger = test_utils::TestLogger::new();
3546
3547         let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3548
3549         // Now try to send a second payment which will fail to send
3550         let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
3551         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3552         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3553         nodes[0].node.send_payment(&route, payment_hash_2, &None).unwrap();
3554         check_added_monitors!(nodes[0], 1);
3555
3556         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3557         assert_eq!(events_1.len(), 1);
3558         match events_1[0] {
3559                 MessageSendEvent::UpdateHTLCs { .. } => {},
3560                 _ => panic!("Unexpected event"),
3561         }
3562
3563         assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000));
3564         check_added_monitors!(nodes[1], 1);
3565
3566         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3567         assert_eq!(events_2.len(), 1);
3568         match events_2[0] {
3569                 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 } } => {
3570                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3571                         assert!(update_add_htlcs.is_empty());
3572                         assert_eq!(update_fulfill_htlcs.len(), 1);
3573                         assert!(update_fail_htlcs.is_empty());
3574                         assert!(update_fail_malformed_htlcs.is_empty());
3575                         assert!(update_fee.is_none());
3576
3577                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3578                         let events_3 = nodes[0].node.get_and_clear_pending_events();
3579                         assert_eq!(events_3.len(), 1);
3580                         match events_3[0] {
3581                                 Event::PaymentSent { ref payment_preimage } => {
3582                                         assert_eq!(*payment_preimage, payment_preimage_1);
3583                                 },
3584                                 _ => panic!("Unexpected event"),
3585                         }
3586
3587                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3588                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3589                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3590                         check_added_monitors!(nodes[0], 1);
3591                 },
3592                 _ => panic!("Unexpected event"),
3593         }
3594
3595         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3596         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3597
3598         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3599         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3600         assert_eq!(reestablish_1.len(), 1);
3601         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3602         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3603         assert_eq!(reestablish_2.len(), 1);
3604
3605         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3606         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3607         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3608         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
3609
3610         assert!(as_resp.0.is_none());
3611         assert!(bs_resp.0.is_none());
3612
3613         assert!(bs_resp.1.is_none());
3614         assert!(bs_resp.2.is_none());
3615
3616         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
3617
3618         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
3619         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
3620         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
3621         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
3622         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
3623         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
3624         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
3625         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3626         // No commitment_signed so get_event_msg's assert(len == 1) passes
3627         check_added_monitors!(nodes[1], 1);
3628
3629         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
3630         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3631         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
3632         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
3633         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
3634         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
3635         assert!(bs_second_commitment_signed.update_fee.is_none());
3636         check_added_monitors!(nodes[1], 1);
3637
3638         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3639         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3640         assert!(as_commitment_signed.update_add_htlcs.is_empty());
3641         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
3642         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
3643         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
3644         assert!(as_commitment_signed.update_fee.is_none());
3645         check_added_monitors!(nodes[0], 1);
3646
3647         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
3648         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3649         // No commitment_signed so get_event_msg's assert(len == 1) passes
3650         check_added_monitors!(nodes[0], 1);
3651
3652         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
3653         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3654         // No commitment_signed so get_event_msg's assert(len == 1) passes
3655         check_added_monitors!(nodes[1], 1);
3656
3657         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3658         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3659         check_added_monitors!(nodes[1], 1);
3660
3661         expect_pending_htlcs_forwardable!(nodes[1]);
3662
3663         let events_5 = nodes[1].node.get_and_clear_pending_events();
3664         assert_eq!(events_5.len(), 1);
3665         match events_5[0] {
3666                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt: _ } => {
3667                         assert_eq!(payment_hash_2, *payment_hash);
3668                         assert_eq!(*payment_secret, None);
3669                 },
3670                 _ => panic!("Unexpected event"),
3671         }
3672
3673         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
3674         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3675         check_added_monitors!(nodes[0], 1);
3676
3677         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
3678 }
3679
3680 fn do_test_htlc_timeout(send_partial_mpp: bool) {
3681         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
3682         // to avoid our counterparty failing the channel.
3683         let chanmon_cfgs = create_chanmon_cfgs(2);
3684         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3685         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3686         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3687
3688         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3689         let logger = test_utils::TestLogger::new();
3690
3691         let our_payment_hash = if send_partial_mpp {
3692                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3693                 let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
3694                 let (_, our_payment_hash) = get_payment_preimage_hash!(&nodes[0]);
3695                 let payment_secret = PaymentSecret([0xdb; 32]);
3696                 // Use the utility function send_payment_along_path to send the payment with MPP data which
3697                 // indicates there are more HTLCs coming.
3698                 nodes[0].node.send_payment_along_path(&route.paths[0], &our_payment_hash, &Some(payment_secret), 200000, CHAN_CONFIRM_DEPTH).unwrap();
3699                 check_added_monitors!(nodes[0], 1);
3700                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3701                 assert_eq!(events.len(), 1);
3702                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
3703                 // hop should *not* yet generate any PaymentReceived event(s).
3704                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false);
3705                 our_payment_hash
3706         } else {
3707                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
3708         };
3709
3710         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3711         nodes[0].block_notifier.block_connected_checked(&header, 101, &[], &[]);
3712         nodes[1].block_notifier.block_connected_checked(&header, 101, &[], &[]);
3713         for i in 102..TEST_FINAL_CLTV + 100 + 1 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
3714                 header.prev_blockhash = header.bitcoin_hash();
3715                 nodes[0].block_notifier.block_connected_checked(&header, i, &[], &[]);
3716                 nodes[1].block_notifier.block_connected_checked(&header, i, &[], &[]);
3717         }
3718
3719         expect_pending_htlcs_forwardable!(nodes[1]);
3720
3721         check_added_monitors!(nodes[1], 1);
3722         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3723         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
3724         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
3725         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
3726         assert!(htlc_timeout_updates.update_fee.is_none());
3727
3728         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
3729         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
3730         // 100_000 msat as u64, followed by a height of 123 as u32
3731         let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
3732         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(123));
3733         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
3734 }
3735
3736 #[test]
3737 fn test_htlc_timeout() {
3738         do_test_htlc_timeout(true);
3739         do_test_htlc_timeout(false);
3740 }
3741
3742 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
3743         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
3744         let chanmon_cfgs = create_chanmon_cfgs(3);
3745         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3746         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3747         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3748         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3749         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3750         let logger = test_utils::TestLogger::new();
3751
3752         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
3753         let (_, first_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3754         {
3755                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3756                 let route = get_route(&nodes[1].node.get_our_node_id(), net_graph_msg_handler, &nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
3757                 nodes[1].node.send_payment(&route, first_payment_hash, &None).unwrap();
3758         }
3759         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
3760         check_added_monitors!(nodes[1], 1);
3761
3762         // Now attempt to route a second payment, which should be placed in the holding cell
3763         let (_, second_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3764         if forwarded_htlc {
3765                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3766                 let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
3767                 nodes[0].node.send_payment(&route, second_payment_hash, &None).unwrap();
3768                 check_added_monitors!(nodes[0], 1);
3769                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
3770                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3771                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3772                 expect_pending_htlcs_forwardable!(nodes[1]);
3773                 check_added_monitors!(nodes[1], 0);
3774         } else {
3775                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3776                 let route = get_route(&nodes[1].node.get_our_node_id(), net_graph_msg_handler, &nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
3777                 nodes[1].node.send_payment(&route, second_payment_hash, &None).unwrap();
3778                 check_added_monitors!(nodes[1], 0);
3779         }
3780
3781         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3782         nodes[1].block_notifier.block_connected_checked(&header, 101, &[], &[]);
3783         for i in 102..TEST_FINAL_CLTV + 100 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
3784                 header.prev_blockhash = header.bitcoin_hash();
3785                 nodes[1].block_notifier.block_connected_checked(&header, i, &[], &[]);
3786         }
3787
3788         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3789         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3790
3791         header.prev_blockhash = header.bitcoin_hash();
3792         nodes[1].block_notifier.block_connected_checked(&header, TEST_FINAL_CLTV + 100 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS, &[], &[]);
3793
3794         if forwarded_htlc {
3795                 expect_pending_htlcs_forwardable!(nodes[1]);
3796                 check_added_monitors!(nodes[1], 1);
3797                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
3798                 assert_eq!(fail_commit.len(), 1);
3799                 match fail_commit[0] {
3800                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
3801                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3802                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
3803                         },
3804                         _ => unreachable!(),
3805                 }
3806                 expect_payment_failed!(nodes[0], second_payment_hash, false);
3807                 if let &MessageSendEvent::PaymentFailureNetworkUpdate { ref update } = &nodes[0].node.get_and_clear_pending_msg_events()[0] {
3808                         match update {
3809                                 &HTLCFailChannelUpdate::ChannelUpdateMessage { .. } => {},
3810                                 _ => panic!("Unexpected event"),
3811                         }
3812                 } else {
3813                         panic!("Unexpected event");
3814                 }
3815         } else {
3816                 expect_payment_failed!(nodes[1], second_payment_hash, true);
3817         }
3818 }
3819
3820 #[test]
3821 fn test_holding_cell_htlc_add_timeouts() {
3822         do_test_holding_cell_htlc_add_timeouts(false);
3823         do_test_holding_cell_htlc_add_timeouts(true);
3824 }
3825
3826 #[test]
3827 fn test_invalid_channel_announcement() {
3828         //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
3829         let secp_ctx = Secp256k1::new();
3830         let chanmon_cfgs = create_chanmon_cfgs(2);
3831         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3832         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3833         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3834
3835         let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
3836
3837         let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
3838         let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
3839         let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
3840         let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
3841
3842         nodes[0].net_graph_msg_handler.handle_htlc_fail_channel_update(&msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id : as_chan.get_short_channel_id().unwrap(), is_permanent: false } );
3843
3844         let as_bitcoin_key = as_chan.get_local_keys().inner.local_channel_pubkeys.funding_pubkey;
3845         let bs_bitcoin_key = bs_chan.get_local_keys().inner.local_channel_pubkeys.funding_pubkey;
3846
3847         let as_network_key = nodes[0].node.get_our_node_id();
3848         let bs_network_key = nodes[1].node.get_our_node_id();
3849
3850         let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
3851
3852         let mut chan_announcement;
3853
3854         macro_rules! dummy_unsigned_msg {
3855                 () => {
3856                         msgs::UnsignedChannelAnnouncement {
3857                                 features: ChannelFeatures::known(),
3858                                 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
3859                                 short_channel_id: as_chan.get_short_channel_id().unwrap(),
3860                                 node_id_1: if were_node_one { as_network_key } else { bs_network_key },
3861                                 node_id_2: if were_node_one { bs_network_key } else { as_network_key },
3862                                 bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
3863                                 bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
3864                                 excess_data: Vec::new(),
3865                         };
3866                 }
3867         }
3868
3869         macro_rules! sign_msg {
3870                 ($unsigned_msg: expr) => {
3871                         let msghash = Message::from_slice(&Sha256dHash::hash(&$unsigned_msg.encode()[..])[..]).unwrap();
3872                         let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_local_keys().inner.funding_key());
3873                         let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_local_keys().inner.funding_key());
3874                         let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].keys_manager.get_node_secret());
3875                         let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].keys_manager.get_node_secret());
3876                         chan_announcement = msgs::ChannelAnnouncement {
3877                                 node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
3878                                 node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
3879                                 bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
3880                                 bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
3881                                 contents: $unsigned_msg
3882                         }
3883                 }
3884         }
3885
3886         let unsigned_msg = dummy_unsigned_msg!();
3887         sign_msg!(unsigned_msg);
3888         assert_eq!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).unwrap(), true);
3889         let _ = nodes[0].net_graph_msg_handler.handle_htlc_fail_channel_update(&msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id : as_chan.get_short_channel_id().unwrap(), is_permanent: false } );
3890
3891         // Configured with Network::Testnet
3892         let mut unsigned_msg = dummy_unsigned_msg!();
3893         unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.bitcoin_hash();
3894         sign_msg!(unsigned_msg);
3895         assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
3896
3897         let mut unsigned_msg = dummy_unsigned_msg!();
3898         unsigned_msg.chain_hash = BlockHash::hash(&[1,2,3,4,5,6,7,8,9]);
3899         sign_msg!(unsigned_msg);
3900         assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
3901 }
3902
3903 #[test]
3904 fn test_no_txn_manager_serialize_deserialize() {
3905         let chanmon_cfgs = create_chanmon_cfgs(2);
3906         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3907         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3908         let logger: test_utils::TestLogger;
3909         let fee_estimator: test_utils::TestFeeEstimator;
3910         let new_chan_monitor: test_utils::TestChannelMonitor;
3911         let keys_manager: test_utils::TestKeysInterface;
3912         let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
3913         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3914
3915         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3916
3917         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3918
3919         let nodes_0_serialized = nodes[0].node.encode();
3920         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3921         nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
3922
3923         logger = test_utils::TestLogger::new();
3924         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
3925         new_chan_monitor = test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator);
3926         nodes[0].chan_monitor = &new_chan_monitor;
3927         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
3928         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut chan_0_monitor_read).unwrap();
3929         assert!(chan_0_monitor_read.is_empty());
3930
3931         let mut nodes_0_read = &nodes_0_serialized[..];
3932         let config = UserConfig::default();
3933         keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
3934         let (_, nodes_0_deserialized_tmp) = {
3935                 let mut channel_monitors = HashMap::new();
3936                 channel_monitors.insert(chan_0_monitor.get_funding_txo(), &mut chan_0_monitor);
3937                 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3938                         default_config: config,
3939                         keys_manager: &keys_manager,
3940                         fee_estimator: &fee_estimator,
3941                         monitor: nodes[0].chan_monitor,
3942                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3943                         logger: &logger,
3944                         channel_monitors: &mut channel_monitors,
3945                 }).unwrap()
3946         };
3947         nodes_0_deserialized = nodes_0_deserialized_tmp;
3948         assert!(nodes_0_read.is_empty());
3949
3950         assert!(nodes[0].chan_monitor.add_monitor(chan_0_monitor.get_funding_txo(), chan_0_monitor).is_ok());
3951         nodes[0].node = &nodes_0_deserialized;
3952         nodes[0].block_notifier.register_listener(nodes[0].node);
3953         assert_eq!(nodes[0].node.list_channels().len(), 1);
3954         check_added_monitors!(nodes[0], 1);
3955
3956         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3957         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3958         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3959         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3960
3961         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3962         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3963         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3964         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3965
3966         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
3967         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
3968         for node in nodes.iter() {
3969                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
3970                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3971                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3972         }
3973
3974         send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
3975 }
3976
3977 #[test]
3978 fn test_manager_serialize_deserialize_events() {
3979         // This test makes sure the events field in ChannelManager survives de/serialization
3980         let chanmon_cfgs = create_chanmon_cfgs(2);
3981         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3982         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3983         let fee_estimator: test_utils::TestFeeEstimator;
3984         let logger: test_utils::TestLogger;
3985         let new_chan_monitor: test_utils::TestChannelMonitor;
3986         let keys_manager: test_utils::TestKeysInterface;
3987         let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
3988         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3989
3990         // Start creating a channel, but stop right before broadcasting the event message FundingBroadcastSafe
3991         let channel_value = 100000;
3992         let push_msat = 10001;
3993         let a_flags = InitFeatures::known();
3994         let b_flags = InitFeatures::known();
3995         let node_a = nodes.pop().unwrap();
3996         let node_b = nodes.pop().unwrap();
3997         node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
3998         node_b.node.handle_open_channel(&node_a.node.get_our_node_id(), a_flags, &get_event_msg!(node_a, MessageSendEvent::SendOpenChannel, node_b.node.get_our_node_id()));
3999         node_a.node.handle_accept_channel(&node_b.node.get_our_node_id(), b_flags, &get_event_msg!(node_b, MessageSendEvent::SendAcceptChannel, node_a.node.get_our_node_id()));
4000
4001         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, channel_value, 42);
4002
4003         node_a.node.funding_transaction_generated(&temporary_channel_id, funding_output);
4004         check_added_monitors!(node_a, 0);
4005
4006         node_b.node.handle_funding_created(&node_a.node.get_our_node_id(), &get_event_msg!(node_a, MessageSendEvent::SendFundingCreated, node_b.node.get_our_node_id()));
4007         {
4008                 let mut added_monitors = node_b.chan_monitor.added_monitors.lock().unwrap();
4009                 assert_eq!(added_monitors.len(), 1);
4010                 assert_eq!(added_monitors[0].0, funding_output);
4011                 added_monitors.clear();
4012         }
4013
4014         node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &get_event_msg!(node_b, MessageSendEvent::SendFundingSigned, node_a.node.get_our_node_id()));
4015         {
4016                 let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
4017                 assert_eq!(added_monitors.len(), 1);
4018                 assert_eq!(added_monitors[0].0, funding_output);
4019                 added_monitors.clear();
4020         }
4021         // Normally, this is where node_a would check for a FundingBroadcastSafe event, but the test de/serializes first instead
4022
4023         nodes.push(node_a);
4024         nodes.push(node_b);
4025
4026         // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4027         let nodes_0_serialized = nodes[0].node.encode();
4028         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4029         nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
4030
4031         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4032         logger = test_utils::TestLogger::new();
4033         new_chan_monitor = test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator);
4034         nodes[0].chan_monitor = &new_chan_monitor;
4035         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4036         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut chan_0_monitor_read).unwrap();
4037         assert!(chan_0_monitor_read.is_empty());
4038
4039         let mut nodes_0_read = &nodes_0_serialized[..];
4040         let config = UserConfig::default();
4041         keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
4042         let (_, nodes_0_deserialized_tmp) = {
4043                 let mut channel_monitors = HashMap::new();
4044                 channel_monitors.insert(chan_0_monitor.get_funding_txo(), &mut chan_0_monitor);
4045                 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4046                         default_config: config,
4047                         keys_manager: &keys_manager,
4048                         fee_estimator: &fee_estimator,
4049                         monitor: nodes[0].chan_monitor,
4050                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4051                         logger: &logger,
4052                         channel_monitors: &mut channel_monitors,
4053                 }).unwrap()
4054         };
4055         nodes_0_deserialized = nodes_0_deserialized_tmp;
4056         assert!(nodes_0_read.is_empty());
4057
4058         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4059
4060         assert!(nodes[0].chan_monitor.add_monitor(chan_0_monitor.get_funding_txo(), chan_0_monitor).is_ok());
4061         nodes[0].node = &nodes_0_deserialized;
4062
4063         // After deserializing, make sure the FundingBroadcastSafe event is still held by the channel manager
4064         let events_4 = nodes[0].node.get_and_clear_pending_events();
4065         assert_eq!(events_4.len(), 1);
4066         match events_4[0] {
4067                 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
4068                         assert_eq!(user_channel_id, 42);
4069                         assert_eq!(*funding_txo, funding_output);
4070                 },
4071                 _ => panic!("Unexpected event"),
4072         };
4073
4074         // Make sure the channel is functioning as though the de/serialization never happened
4075         nodes[0].block_notifier.register_listener(nodes[0].node);
4076         assert_eq!(nodes[0].node.list_channels().len(), 1);
4077         check_added_monitors!(nodes[0], 1);
4078
4079         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4080         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4081         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4082         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4083
4084         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4085         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4086         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4087         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4088
4089         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4090         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4091         for node in nodes.iter() {
4092                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4093                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4094                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4095         }
4096
4097         send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
4098 }
4099
4100 #[test]
4101 fn test_simple_manager_serialize_deserialize() {
4102         let chanmon_cfgs = create_chanmon_cfgs(2);
4103         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4104         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4105         let logger: test_utils::TestLogger;
4106         let fee_estimator: test_utils::TestFeeEstimator;
4107         let new_chan_monitor: test_utils::TestChannelMonitor;
4108         let keys_manager: test_utils::TestKeysInterface;
4109         let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4110         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4111         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4112
4113         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4114         let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4115
4116         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4117
4118         let nodes_0_serialized = nodes[0].node.encode();
4119         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4120         nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
4121
4122         logger = test_utils::TestLogger::new();
4123         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4124         new_chan_monitor = test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator);
4125         nodes[0].chan_monitor = &new_chan_monitor;
4126         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4127         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut chan_0_monitor_read).unwrap();
4128         assert!(chan_0_monitor_read.is_empty());
4129
4130         let mut nodes_0_read = &nodes_0_serialized[..];
4131         keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
4132         let (_, nodes_0_deserialized_tmp) = {
4133                 let mut channel_monitors = HashMap::new();
4134                 channel_monitors.insert(chan_0_monitor.get_funding_txo(), &mut chan_0_monitor);
4135                 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4136                         default_config: UserConfig::default(),
4137                         keys_manager: &keys_manager,
4138                         fee_estimator: &fee_estimator,
4139                         monitor: nodes[0].chan_monitor,
4140                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4141                         logger: &logger,
4142                         channel_monitors: &mut channel_monitors,
4143                 }).unwrap()
4144         };
4145         nodes_0_deserialized = nodes_0_deserialized_tmp;
4146         assert!(nodes_0_read.is_empty());
4147
4148         assert!(nodes[0].chan_monitor.add_monitor(chan_0_monitor.get_funding_txo(), chan_0_monitor).is_ok());
4149         nodes[0].node = &nodes_0_deserialized;
4150         check_added_monitors!(nodes[0], 1);
4151
4152         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4153
4154         fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4155         claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage, 1_000_000);
4156 }
4157
4158 #[test]
4159 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4160         // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4161         let chanmon_cfgs = create_chanmon_cfgs(4);
4162         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4163         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4164         let logger: test_utils::TestLogger;
4165         let fee_estimator: test_utils::TestFeeEstimator;
4166         let new_chan_monitor: test_utils::TestChannelMonitor;
4167         let keys_manager: test_utils::TestKeysInterface;
4168         let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4169         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4170         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4171         create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known());
4172         let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4173
4174         let mut node_0_stale_monitors_serialized = Vec::new();
4175         for monitor in nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter() {
4176                 let mut writer = test_utils::TestVecWriter(Vec::new());
4177                 monitor.1.write_for_disk(&mut writer).unwrap();
4178                 node_0_stale_monitors_serialized.push(writer.0);
4179         }
4180
4181         let (our_payment_preimage, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4182
4183         // Serialize the ChannelManager here, but the monitor we keep up-to-date
4184         let nodes_0_serialized = nodes[0].node.encode();
4185
4186         route_payment(&nodes[0], &[&nodes[3]], 1000000);
4187         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4188         nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4189         nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4190
4191         // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4192         // nodes[3])
4193         let mut node_0_monitors_serialized = Vec::new();
4194         for monitor in nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter() {
4195                 let mut writer = test_utils::TestVecWriter(Vec::new());
4196                 monitor.1.write_for_disk(&mut writer).unwrap();
4197                 node_0_monitors_serialized.push(writer.0);
4198         }
4199
4200         logger = test_utils::TestLogger::new();
4201         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4202         new_chan_monitor = test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator);
4203         nodes[0].chan_monitor = &new_chan_monitor;
4204
4205         let mut node_0_stale_monitors = Vec::new();
4206         for serialized in node_0_stale_monitors_serialized.iter() {
4207                 let mut read = &serialized[..];
4208                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut read).unwrap();
4209                 assert!(read.is_empty());
4210                 node_0_stale_monitors.push(monitor);
4211         }
4212
4213         let mut node_0_monitors = Vec::new();
4214         for serialized in node_0_monitors_serialized.iter() {
4215                 let mut read = &serialized[..];
4216                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut read).unwrap();
4217                 assert!(read.is_empty());
4218                 node_0_monitors.push(monitor);
4219         }
4220
4221         keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
4222
4223         let mut nodes_0_read = &nodes_0_serialized[..];
4224         if let Err(msgs::DecodeError::InvalidValue) =
4225                 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4226                 default_config: UserConfig::default(),
4227                 keys_manager: &keys_manager,
4228                 fee_estimator: &fee_estimator,
4229                 monitor: nodes[0].chan_monitor,
4230                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4231                 logger: &logger,
4232                 channel_monitors: &mut node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo(), monitor) }).collect(),
4233         }) { } else {
4234                 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4235         };
4236
4237         let mut nodes_0_read = &nodes_0_serialized[..];
4238         let (_, nodes_0_deserialized_tmp) =
4239                 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4240                 default_config: UserConfig::default(),
4241                 keys_manager: &keys_manager,
4242                 fee_estimator: &fee_estimator,
4243                 monitor: nodes[0].chan_monitor,
4244                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4245                 logger: &logger,
4246                 channel_monitors: &mut node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo(), monitor) }).collect(),
4247         }).unwrap();
4248         nodes_0_deserialized = nodes_0_deserialized_tmp;
4249         assert!(nodes_0_read.is_empty());
4250
4251         { // Channel close should result in a commitment tx and an HTLC tx
4252                 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4253                 assert_eq!(txn.len(), 2);
4254                 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4255                 assert_eq!(txn[1].input[0].previous_output.txid, txn[0].txid());
4256         }
4257
4258         for monitor in node_0_monitors.drain(..) {
4259                 assert!(nodes[0].chan_monitor.add_monitor(monitor.get_funding_txo(), monitor).is_ok());
4260                 check_added_monitors!(nodes[0], 1);
4261         }
4262         nodes[0].node = &nodes_0_deserialized;
4263
4264         // nodes[1] and nodes[2] have no lost state with nodes[0]...
4265         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4266         reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4267         //... and we can even still claim the payment!
4268         claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage, 1_000_000);
4269
4270         nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4271         let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4272         nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4273         nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4274         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4275         assert_eq!(msg_events.len(), 1);
4276         if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4277                 match action {
4278                         &ErrorAction::SendErrorMessage { ref msg } => {
4279                                 assert_eq!(msg.channel_id, channel_id);
4280                         },
4281                         _ => panic!("Unexpected event!"),
4282                 }
4283         }
4284 }
4285
4286 macro_rules! check_spendable_outputs {
4287         ($node: expr, $der_idx: expr) => {
4288                 {
4289                         let events = $node.chan_monitor.simple_monitor.get_and_clear_pending_events();
4290                         let mut txn = Vec::new();
4291                         for event in events {
4292                                 match event {
4293                                         Event::SpendableOutputs { ref outputs } => {
4294                                                 for outp in outputs {
4295                                                         match *outp {
4296                                                                 SpendableOutputDescriptor::DynamicOutputP2WPKH { ref outpoint, ref key, ref output } => {
4297                                                                         let input = TxIn {
4298                                                                                 previous_output: outpoint.clone(),
4299                                                                                 script_sig: Script::new(),
4300                                                                                 sequence: 0,
4301                                                                                 witness: Vec::new(),
4302                                                                         };
4303                                                                         let outp = TxOut {
4304                                                                                 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
4305                                                                                 value: output.value,
4306                                                                         };
4307                                                                         let mut spend_tx = Transaction {
4308                                                                                 version: 2,
4309                                                                                 lock_time: 0,
4310                                                                                 input: vec![input],
4311                                                                                 output: vec![outp],
4312                                                                         };
4313                                                                         let secp_ctx = Secp256k1::new();
4314                                                                         let remotepubkey = PublicKey::from_secret_key(&secp_ctx, &key);
4315                                                                         let witness_script = Address::p2pkh(&::bitcoin::PublicKey{compressed: true, key: remotepubkey}, Network::Testnet).script_pubkey();
4316                                                                         let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
4317                                                                         let remotesig = secp_ctx.sign(&sighash, key);
4318                                                                         spend_tx.input[0].witness.push(remotesig.serialize_der().to_vec());
4319                                                                         spend_tx.input[0].witness[0].push(SigHashType::All as u8);
4320                                                                         spend_tx.input[0].witness.push(remotepubkey.serialize().to_vec());
4321                                                                         txn.push(spend_tx);
4322                                                                 },
4323                                                                 SpendableOutputDescriptor::DynamicOutputP2WSH { ref outpoint, ref key, ref witness_script, ref to_self_delay, ref output } => {
4324                                                                         let input = TxIn {
4325                                                                                 previous_output: outpoint.clone(),
4326                                                                                 script_sig: Script::new(),
4327                                                                                 sequence: *to_self_delay as u32,
4328                                                                                 witness: Vec::new(),
4329                                                                         };
4330                                                                         let outp = TxOut {
4331                                                                                 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
4332                                                                                 value: output.value,
4333                                                                         };
4334                                                                         let mut spend_tx = Transaction {
4335                                                                                 version: 2,
4336                                                                                 lock_time: 0,
4337                                                                                 input: vec![input],
4338                                                                                 output: vec![outp],
4339                                                                         };
4340                                                                         let secp_ctx = Secp256k1::new();
4341                                                                         let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], witness_script, output.value)[..]).unwrap();
4342                                                                         let local_delaysig = secp_ctx.sign(&sighash, key);
4343                                                                         spend_tx.input[0].witness.push(local_delaysig.serialize_der().to_vec());
4344                                                                         spend_tx.input[0].witness[0].push(SigHashType::All as u8);
4345                                                                         spend_tx.input[0].witness.push(vec!());
4346                                                                         spend_tx.input[0].witness.push(witness_script.clone().into_bytes());
4347                                                                         txn.push(spend_tx);
4348                                                                 },
4349                                                                 SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
4350                                                                         let secp_ctx = Secp256k1::new();
4351                                                                         let input = TxIn {
4352                                                                                 previous_output: outpoint.clone(),
4353                                                                                 script_sig: Script::new(),
4354                                                                                 sequence: 0,
4355                                                                                 witness: Vec::new(),
4356                                                                         };
4357                                                                         let outp = TxOut {
4358                                                                                 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
4359                                                                                 value: output.value,
4360                                                                         };
4361                                                                         let mut spend_tx = Transaction {
4362                                                                                 version: 2,
4363                                                                                 lock_time: 0,
4364                                                                                 input: vec![input],
4365                                                                                 output: vec![outp.clone()],
4366                                                                         };
4367                                                                         let secret = {
4368                                                                                 match ExtendedPrivKey::new_master(Network::Testnet, &$node.node_seed) {
4369                                                                                         Ok(master_key) => {
4370                                                                                                 match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx($der_idx).expect("key space exhausted")) {
4371                                                                                                         Ok(key) => key,
4372                                                                                                         Err(_) => panic!("Your RNG is busted"),
4373                                                                                                 }
4374                                                                                         }
4375                                                                                         Err(_) => panic!("Your rng is busted"),
4376                                                                                 }
4377                                                                         };
4378                                                                         let pubkey = ExtendedPubKey::from_private(&secp_ctx, &secret).public_key;
4379                                                                         let witness_script = Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
4380                                                                         let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
4381                                                                         let sig = secp_ctx.sign(&sighash, &secret.private_key.key);
4382                                                                         spend_tx.input[0].witness.push(sig.serialize_der().to_vec());
4383                                                                         spend_tx.input[0].witness[0].push(SigHashType::All as u8);
4384                                                                         spend_tx.input[0].witness.push(pubkey.key.serialize().to_vec());
4385                                                                         txn.push(spend_tx);
4386                                                                 },
4387                                                         }
4388                                                 }
4389                                         },
4390                                         _ => panic!("Unexpected event"),
4391                                 };
4392                         }
4393                         txn
4394                 }
4395         }
4396 }
4397
4398 #[test]
4399 fn test_claim_sizeable_push_msat() {
4400         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4401         let chanmon_cfgs = create_chanmon_cfgs(2);
4402         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4403         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4404         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4405
4406         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, InitFeatures::known(), InitFeatures::known());
4407         nodes[1].node.force_close_channel(&chan.2);
4408         check_closed_broadcast!(nodes[1], false);
4409         check_added_monitors!(nodes[1], 1);
4410         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4411         assert_eq!(node_txn.len(), 1);
4412         check_spends!(node_txn[0], chan.3);
4413         assert_eq!(node_txn[0].output.len(), 3); // We can't force trimming of to_remote/anchor outputs as channel_reserve_satoshis block us to do so at channel opening
4414
4415         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4416         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
4417         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4418
4419         let spend_txn = check_spendable_outputs!(nodes[1], 1);
4420         assert_eq!(spend_txn.len(), 1);
4421         check_spends!(spend_txn[0], node_txn[0]);
4422 }
4423
4424 #[test]
4425 fn test_claim_on_remote_sizeable_push_msat() {
4426         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4427         // to_remote output is encumbered by a P2WPKH
4428         let chanmon_cfgs = create_chanmon_cfgs(2);
4429         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4430         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4431         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4432
4433         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, InitFeatures::known(), InitFeatures::known());
4434         nodes[0].node.force_close_channel(&chan.2);
4435         check_closed_broadcast!(nodes[0], false);
4436         check_added_monitors!(nodes[0], 1);
4437
4438         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4439         assert_eq!(node_txn.len(), 1);
4440         check_spends!(node_txn[0], chan.3);
4441         assert_eq!(node_txn[0].output.len(), 3); // We can't force trimming of to_remote/anchor outputs as channel_reserve_satoshis block us to do so at channel opening
4442
4443         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4444         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
4445         check_closed_broadcast!(nodes[1], false);
4446         check_added_monitors!(nodes[1], 1);
4447         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4448
4449         let spend_txn = check_spendable_outputs!(nodes[1], 1);
4450         assert_eq!(spend_txn.len(), 2);
4451         assert_eq!(spend_txn[0], spend_txn[1]);
4452         check_spends!(spend_txn[0], node_txn[0]);
4453 }
4454
4455 #[test]
4456 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4457         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4458         // to_remote output is encumbered by a P2WPKH
4459
4460         let chanmon_cfgs = create_chanmon_cfgs(2);
4461         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4462         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4463         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4464
4465         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4466         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4467         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4468         assert_eq!(revoked_local_txn[0].input.len(), 1);
4469         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4470
4471         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4472         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4473         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 0);
4474         check_closed_broadcast!(nodes[1], false);
4475         check_added_monitors!(nodes[1], 1);
4476
4477         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4478         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4479         nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4480         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4481
4482         let spend_txn = check_spendable_outputs!(nodes[1], 1);
4483         assert_eq!(spend_txn.len(), 3);
4484         assert_eq!(spend_txn[0], spend_txn[1]); // to_remote output on revoked remote commitment_tx
4485         check_spends!(spend_txn[0], revoked_local_txn[0]);
4486         check_spends!(spend_txn[2], node_txn[0]);
4487 }
4488
4489 #[test]
4490 fn test_static_spendable_outputs_preimage_tx() {
4491         let chanmon_cfgs = create_chanmon_cfgs(2);
4492         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4493         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4494         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4495
4496         // Create some initial channels
4497         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4498
4499         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4500
4501         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4502         assert_eq!(commitment_tx[0].input.len(), 1);
4503         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4504
4505         // Settle A's commitment tx on B's chain
4506         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4507         assert!(nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000));
4508         check_added_monitors!(nodes[1], 1);
4509         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()] }, 1);
4510         check_added_monitors!(nodes[1], 1);
4511         let events = nodes[1].node.get_and_clear_pending_msg_events();
4512         match events[0] {
4513                 MessageSendEvent::UpdateHTLCs { .. } => {},
4514                 _ => panic!("Unexpected event"),
4515         }
4516         match events[1] {
4517                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4518                 _ => panic!("Unexepected event"),
4519         }
4520
4521         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4522         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4523         assert_eq!(node_txn.len(), 3);
4524         check_spends!(node_txn[0], commitment_tx[0]);
4525         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4526         check_spends!(node_txn[1], chan_1.3);
4527         check_spends!(node_txn[2], node_txn[1]);
4528
4529         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4530         nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4531         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4532
4533         let spend_txn = check_spendable_outputs!(nodes[1], 1);
4534         assert_eq!(spend_txn.len(), 1);
4535         check_spends!(spend_txn[0], node_txn[0]);
4536 }
4537
4538 #[test]
4539 fn test_static_spendable_outputs_timeout_tx() {
4540         let chanmon_cfgs = create_chanmon_cfgs(2);
4541         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4542         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4543         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4544
4545         // Create some initial channels
4546         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4547
4548         // Rebalance the network a bit by relaying one payment through all the channels ...
4549         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
4550
4551         let (_, our_payment_hash) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4552
4553         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4554         assert_eq!(commitment_tx[0].input.len(), 1);
4555         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4556
4557         // Settle A's commitment tx on B' chain
4558         let header = BlockHeader { version: 0x2000_0000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
4559         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()] }, 0);
4560         check_added_monitors!(nodes[1], 1);
4561         let events = nodes[1].node.get_and_clear_pending_msg_events();
4562         match events[0] {
4563                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4564                 _ => panic!("Unexpected event"),
4565         }
4566
4567         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4568         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4569         assert_eq!(node_txn.len(), 3); // ChannelManager : 2 (local commitent tx + HTLC-timeout), ChannelMonitor: timeout tx
4570         check_spends!(node_txn[0],  commitment_tx[0].clone());
4571         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4572         check_spends!(node_txn[1], chan_1.3.clone());
4573         check_spends!(node_txn[2], node_txn[1]);
4574
4575         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4576         nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4577         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4578         expect_payment_failed!(nodes[1], our_payment_hash, true);
4579
4580         let spend_txn = check_spendable_outputs!(nodes[1], 1);
4581         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote (*2), timeout_tx.output (*1)
4582         check_spends!(spend_txn[2], node_txn[0].clone());
4583 }
4584
4585 #[test]
4586 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4587         let chanmon_cfgs = create_chanmon_cfgs(2);
4588         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4589         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4590         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4591
4592         // Create some initial channels
4593         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4594
4595         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4596         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4597         assert_eq!(revoked_local_txn[0].input.len(), 1);
4598         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4599
4600         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4601
4602         let  header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4603         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 0);
4604         check_closed_broadcast!(nodes[1], false);
4605         check_added_monitors!(nodes[1], 1);
4606
4607         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4608         assert_eq!(node_txn.len(), 2);
4609         assert_eq!(node_txn[0].input.len(), 2);
4610         check_spends!(node_txn[0], revoked_local_txn[0]);
4611
4612         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4613         nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4614         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4615
4616         let spend_txn = check_spendable_outputs!(nodes[1], 1);
4617         assert_eq!(spend_txn.len(), 1);
4618         check_spends!(spend_txn[0], node_txn[0]);
4619 }
4620
4621 #[test]
4622 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4623         let chanmon_cfgs = create_chanmon_cfgs(2);
4624         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4625         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4626         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4627
4628         // Create some initial channels
4629         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4630
4631         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4632         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4633         assert_eq!(revoked_local_txn[0].input.len(), 1);
4634         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4635
4636         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4637
4638         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4639         // A will generate HTLC-Timeout from revoked commitment tx
4640         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
4641         check_closed_broadcast!(nodes[0], false);
4642         check_added_monitors!(nodes[0], 1);
4643
4644         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4645         assert_eq!(revoked_htlc_txn.len(), 2);
4646         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4647         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4648         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4649         check_spends!(revoked_htlc_txn[1], chan_1.3);
4650
4651         // B will generate justice tx from A's revoked commitment/HTLC tx
4652         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 0);
4653         check_closed_broadcast!(nodes[1], false);
4654         check_added_monitors!(nodes[1], 1);
4655
4656         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4657         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
4658         assert_eq!(node_txn[0].input.len(), 2);
4659         check_spends!(node_txn[0], revoked_local_txn[0]);
4660         check_spends!(node_txn[1], chan_1.3);
4661         assert_eq!(node_txn[2].input.len(), 1);
4662         check_spends!(node_txn[2], revoked_htlc_txn[0]);
4663         assert_eq!(node_txn[3].input.len(), 1);
4664         check_spends!(node_txn[3], revoked_local_txn[0]);
4665
4666         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4667         nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone(), node_txn[2].clone()] }, 1);
4668         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4669
4670         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4671         let spend_txn = check_spendable_outputs!(nodes[1], 1);
4672         assert_eq!(spend_txn.len(), 2);
4673         check_spends!(spend_txn[0], node_txn[0]);
4674         check_spends!(spend_txn[1], node_txn[2]);
4675 }
4676
4677 #[test]
4678 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4679         let chanmon_cfgs = create_chanmon_cfgs(2);
4680         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4681         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4682         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4683
4684         // Create some initial channels
4685         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4686
4687         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4688         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4689         assert_eq!(revoked_local_txn[0].input.len(), 1);
4690         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4691
4692         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4693
4694         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4695         // B will generate HTLC-Success from revoked commitment tx
4696         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
4697         check_closed_broadcast!(nodes[1], false);
4698         check_added_monitors!(nodes[1], 1);
4699         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4700
4701         assert_eq!(revoked_htlc_txn.len(), 2);
4702         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4703         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4704         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4705
4706         // A will generate justice tx from B's revoked commitment/HTLC tx
4707         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
4708         check_closed_broadcast!(nodes[0], false);
4709         check_added_monitors!(nodes[0], 1);
4710
4711         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4712         assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
4713         assert_eq!(node_txn[2].input.len(), 1);
4714         check_spends!(node_txn[2], revoked_htlc_txn[0]);
4715
4716         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4717         nodes[0].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone(), node_txn[2].clone()] }, 1);
4718         connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4719
4720         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4721         let spend_txn = check_spendable_outputs!(nodes[0], 1);
4722         assert_eq!(spend_txn.len(), 5); // Duplicated SpendableOutput due to block rescan after revoked htlc output tracking
4723         assert_eq!(spend_txn[0], spend_txn[1]);
4724         assert_eq!(spend_txn[0], spend_txn[2]);
4725         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4726         check_spends!(spend_txn[3], node_txn[0]); // spending justice tx output from revoked local tx htlc received output
4727         check_spends!(spend_txn[4], node_txn[2]); // spending justice tx output on htlc success tx
4728 }
4729
4730 #[test]
4731 fn test_onchain_to_onchain_claim() {
4732         // Test that in case of channel closure, we detect the state of output thanks to
4733         // ChainWatchInterface and claim HTLC on downstream peer's remote commitment tx.
4734         // First, have C claim an HTLC against its own latest commitment transaction.
4735         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4736         // channel.
4737         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4738         // gets broadcast.
4739
4740         let chanmon_cfgs = create_chanmon_cfgs(3);
4741         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4742         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4743         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4744
4745         // Create some initial channels
4746         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4747         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4748
4749         // Rebalance the network a bit by relaying one payment through all the channels ...
4750         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
4751         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
4752
4753         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
4754         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
4755         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4756         check_spends!(commitment_tx[0], chan_2.3);
4757         nodes[2].node.claim_funds(payment_preimage, &None, 3_000_000);
4758         check_added_monitors!(nodes[2], 1);
4759         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4760         assert!(updates.update_add_htlcs.is_empty());
4761         assert!(updates.update_fail_htlcs.is_empty());
4762         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4763         assert!(updates.update_fail_malformed_htlcs.is_empty());
4764
4765         nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
4766         check_closed_broadcast!(nodes[2], false);
4767         check_added_monitors!(nodes[2], 1);
4768
4769         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
4770         assert_eq!(c_txn.len(), 3);
4771         assert_eq!(c_txn[0], c_txn[2]);
4772         assert_eq!(commitment_tx[0], c_txn[1]);
4773         check_spends!(c_txn[1], chan_2.3);
4774         check_spends!(c_txn[2], c_txn[1]);
4775         assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
4776         assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4777         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4778         assert_eq!(c_txn[0].lock_time, 0); // Success tx
4779
4780         // 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
4781         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]}, 1);
4782         {
4783                 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4784                 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-timeout tx
4785                 assert_eq!(b_txn.len(), 3);
4786                 check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager
4787                 check_spends!(b_txn[2], b_txn[1]); // HTLC-Timeout on B local commitment tx, issued by ChannelManager
4788                 assert_eq!(b_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4789                 assert!(b_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4790                 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
4791                 check_spends!(b_txn[0], c_txn[1]); // timeout tx on C remote commitment tx, issued by ChannelMonitor, * 2 due to block rescan
4792                 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4793                 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4794                 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
4795                 b_txn.clear();
4796         }
4797         check_added_monitors!(nodes[1], 1);
4798         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4799         check_added_monitors!(nodes[1], 1);
4800         match msg_events[0] {
4801                 MessageSendEvent::BroadcastChannelUpdate {  .. } => {},
4802                 _ => panic!("Unexpected event"),
4803         }
4804         match msg_events[1] {
4805                 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, .. } } => {
4806                         assert!(update_add_htlcs.is_empty());
4807                         assert!(update_fail_htlcs.is_empty());
4808                         assert_eq!(update_fulfill_htlcs.len(), 1);
4809                         assert!(update_fail_malformed_htlcs.is_empty());
4810                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4811                 },
4812                 _ => panic!("Unexpected event"),
4813         };
4814         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4815         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4816         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
4817         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4818         // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
4819         assert_eq!(b_txn.len(), 3);
4820         check_spends!(b_txn[1], chan_1.3);
4821         check_spends!(b_txn[2], b_txn[1]);
4822         check_spends!(b_txn[0], commitment_tx[0]);
4823         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4824         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4825         assert_eq!(b_txn[0].lock_time, 0); // Success tx
4826
4827         check_closed_broadcast!(nodes[1], false);
4828         check_added_monitors!(nodes[1], 1);
4829 }
4830
4831 #[test]
4832 fn test_duplicate_payment_hash_one_failure_one_success() {
4833         // Topology : A --> B --> C
4834         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4835         let chanmon_cfgs = create_chanmon_cfgs(3);
4836         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4837         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4838         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4839
4840         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4841         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4842
4843         let (our_payment_preimage, duplicate_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
4844         *nodes[0].network_payment_count.borrow_mut() -= 1;
4845         assert_eq!(route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, duplicate_payment_hash);
4846
4847         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
4848         assert_eq!(commitment_txn[0].input.len(), 1);
4849         check_spends!(commitment_txn[0], chan_2.3);
4850
4851         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4852         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
4853         check_closed_broadcast!(nodes[1], false);
4854         check_added_monitors!(nodes[1], 1);
4855
4856         let htlc_timeout_tx;
4857         { // Extract one of the two HTLC-Timeout transaction
4858                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4859                 // ChannelMonitor: timeout tx * 2, ChannelManager: local commitment tx + HTLC-timeout * 2
4860                 assert_eq!(node_txn.len(), 5);
4861                 check_spends!(node_txn[0], commitment_txn[0]);
4862                 assert_eq!(node_txn[0].input.len(), 1);
4863                 check_spends!(node_txn[1], commitment_txn[0]);
4864                 assert_eq!(node_txn[1].input.len(), 1);
4865                 assert_ne!(node_txn[0].input[0], node_txn[1].input[0]);
4866                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4867                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4868                 check_spends!(node_txn[2], chan_2.3);
4869                 check_spends!(node_txn[3], node_txn[2]);
4870                 check_spends!(node_txn[4], node_txn[2]);
4871                 htlc_timeout_tx = node_txn[1].clone();
4872         }
4873
4874         nodes[2].node.claim_funds(our_payment_preimage, &None, 900_000);
4875         nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
4876         check_added_monitors!(nodes[2], 3);
4877         let events = nodes[2].node.get_and_clear_pending_msg_events();
4878         match events[0] {
4879                 MessageSendEvent::UpdateHTLCs { .. } => {},
4880                 _ => panic!("Unexpected event"),
4881         }
4882         match events[1] {
4883                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4884                 _ => panic!("Unexepected event"),
4885         }
4886         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4887         assert_eq!(htlc_success_txn.len(), 5); // ChannelMonitor: HTLC-Success txn (*2 due to 2-HTLC outputs), ChannelManager: local commitment tx + HTLC-Success txn (*2 due to 2-HTLC outputs)
4888         check_spends!(htlc_success_txn[2], chan_2.3);
4889         check_spends!(htlc_success_txn[3], htlc_success_txn[2]);
4890         check_spends!(htlc_success_txn[4], htlc_success_txn[2]);
4891         assert_eq!(htlc_success_txn[0], htlc_success_txn[3]);
4892         assert_eq!(htlc_success_txn[0].input.len(), 1);
4893         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4894         assert_eq!(htlc_success_txn[1], htlc_success_txn[4]);
4895         assert_eq!(htlc_success_txn[1].input.len(), 1);
4896         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4897         assert_ne!(htlc_success_txn[0].input[0], htlc_success_txn[1].input[0]);
4898         check_spends!(htlc_success_txn[0], commitment_txn[0]);
4899         check_spends!(htlc_success_txn[1], commitment_txn[0]);
4900
4901         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![htlc_timeout_tx] }, 200);
4902         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 200, true, header.bitcoin_hash());
4903         expect_pending_htlcs_forwardable!(nodes[1]);
4904         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4905         assert!(htlc_updates.update_add_htlcs.is_empty());
4906         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
4907         assert_eq!(htlc_updates.update_fail_htlcs[0].htlc_id, 1);
4908         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
4909         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
4910         check_added_monitors!(nodes[1], 1);
4911
4912         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
4913         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4914         {
4915                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
4916                 let events = nodes[0].node.get_and_clear_pending_msg_events();
4917                 assert_eq!(events.len(), 1);
4918                 match events[0] {
4919                         MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. }  } => {
4920                         },
4921                         _ => { panic!("Unexpected event"); }
4922                 }
4923         }
4924         expect_payment_failed!(nodes[0], duplicate_payment_hash, false);
4925
4926         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
4927         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![htlc_success_txn[0].clone()] }, 200);
4928         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4929         assert!(updates.update_add_htlcs.is_empty());
4930         assert!(updates.update_fail_htlcs.is_empty());
4931         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4932         assert_eq!(updates.update_fulfill_htlcs[0].htlc_id, 0);
4933         assert!(updates.update_fail_malformed_htlcs.is_empty());
4934         check_added_monitors!(nodes[1], 1);
4935
4936         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
4937         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
4938
4939         let events = nodes[0].node.get_and_clear_pending_events();
4940         match events[0] {
4941                 Event::PaymentSent { ref payment_preimage } => {
4942                         assert_eq!(*payment_preimage, our_payment_preimage);
4943                 }
4944                 _ => panic!("Unexpected event"),
4945         }
4946 }
4947
4948 #[test]
4949 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
4950         let chanmon_cfgs = create_chanmon_cfgs(2);
4951         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4952         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4953         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4954
4955         // Create some initial channels
4956         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4957
4958         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
4959         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4960         assert_eq!(local_txn[0].input.len(), 1);
4961         check_spends!(local_txn[0], chan_1.3);
4962
4963         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
4964         nodes[1].node.claim_funds(payment_preimage, &None, 9_000_000);
4965         check_added_monitors!(nodes[1], 1);
4966         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4967         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![local_txn[0].clone()] }, 1);
4968         check_added_monitors!(nodes[1], 1);
4969         let events = nodes[1].node.get_and_clear_pending_msg_events();
4970         match events[0] {
4971                 MessageSendEvent::UpdateHTLCs { .. } => {},
4972                 _ => panic!("Unexpected event"),
4973         }
4974         match events[1] {
4975                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4976                 _ => panic!("Unexepected event"),
4977         }
4978         let node_txn = {
4979                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4980                 assert_eq!(node_txn[0].input.len(), 1);
4981                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4982                 check_spends!(node_txn[0], local_txn[0]);
4983                 vec![node_txn[0].clone(), node_txn[2].clone()]
4984         };
4985
4986         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4987         nodes[1].block_notifier.block_connected(&Block { header: header_201, txdata: node_txn.clone() }, 201);
4988         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 201, true, header_201.bitcoin_hash());
4989
4990         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
4991         let spend_txn = check_spendable_outputs!(nodes[1], 1);
4992         assert_eq!(spend_txn.len(), 2);
4993         check_spends!(spend_txn[0], node_txn[0]);
4994         check_spends!(spend_txn[1], node_txn[1]);
4995 }
4996
4997 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
4998         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
4999         // unrevoked commitment transaction.
5000         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5001         // a remote RAA before they could be failed backwards (and combinations thereof).
5002         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5003         // use the same payment hashes.
5004         // Thus, we use a six-node network:
5005         //
5006         // A \         / E
5007         //    - C - D -
5008         // B /         \ F
5009         // And test where C fails back to A/B when D announces its latest commitment transaction
5010         let chanmon_cfgs = create_chanmon_cfgs(6);
5011         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5012         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
5013         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5014         let logger = test_utils::TestLogger::new();
5015
5016         create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5017         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5018         let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5019         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5020         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5021
5022         // Rebalance and check output sanity...
5023         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000, 500_000);
5024         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000, 500_000);
5025         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 3); // to_local, to_remote, and anchor output
5026
5027         let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
5028         // 0th HTLC:
5029         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
5030         // 1st HTLC:
5031         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
5032         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
5033         let our_node_id = &nodes[1].node.get_our_node_id();
5034         let route = get_route(our_node_id, net_graph_msg_handler, &nodes[5].node.get_our_node_id(), None, &Vec::new(), ds_dust_limit*1000, TEST_FINAL_CLTV, &logger).unwrap();
5035         // 2nd HTLC:
5036         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
5037         // 3rd HTLC:
5038         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
5039         // 4th HTLC:
5040         let (_, payment_hash_3) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5041         // 5th HTLC:
5042         let (_, payment_hash_4) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5043         let route = get_route(our_node_id, net_graph_msg_handler, &nodes[5].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
5044         // 6th HTLC:
5045         send_along_route_with_hash(&nodes[1], route.clone(), &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_3);
5046         // 7th HTLC:
5047         send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_4);
5048
5049         // 8th HTLC:
5050         let (_, payment_hash_5) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5051         // 9th HTLC:
5052         let route = get_route(our_node_id, net_graph_msg_handler, &nodes[5].node.get_our_node_id(), None, &Vec::new(), ds_dust_limit*1000, TEST_FINAL_CLTV, &logger).unwrap();
5053         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
5054
5055         // 10th HTLC:
5056         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
5057         // 11th HTLC:
5058         let route = get_route(our_node_id, net_graph_msg_handler, &nodes[5].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
5059         send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_6);
5060
5061         // Double-check that six of the new HTLC were added
5062         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5063         // with to_local, to_remote, and anchor outputs, 9 outputs and 6 HTLCs not included).
5064         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5065         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 9);
5066
5067         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5068         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5069         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1, &None));
5070         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3, &None));
5071         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5, &None));
5072         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6, &None));
5073         check_added_monitors!(nodes[4], 0);
5074         expect_pending_htlcs_forwardable!(nodes[4]);
5075         check_added_monitors!(nodes[4], 1);
5076
5077         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5078         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5079         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5080         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5081         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5082         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5083
5084         // Fail 3rd below-dust and 7th above-dust HTLCs
5085         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2, &None));
5086         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4, &None));
5087         check_added_monitors!(nodes[5], 0);
5088         expect_pending_htlcs_forwardable!(nodes[5]);
5089         check_added_monitors!(nodes[5], 1);
5090
5091         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5092         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5093         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5094         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5095
5096         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5097
5098         expect_pending_htlcs_forwardable!(nodes[3]);
5099         check_added_monitors!(nodes[3], 1);
5100         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5101         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5102         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5103         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5104         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5105         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5106         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5107         if deliver_last_raa {
5108                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5109         } else {
5110                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5111         }
5112
5113         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5114         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5115         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5116         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5117         //
5118         // We now broadcast the latest commitment transaction, which *should* result in failures for
5119         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5120         // the non-broadcast above-dust HTLCs.
5121         //
5122         // Alternatively, we may broadcast the previous commitment transaction, which should only
5123         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5124         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5125
5126         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5127         if announce_latest {
5128                 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![ds_last_commitment_tx[0].clone()]}, 1);
5129         } else {
5130                 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![ds_prev_commitment_tx[0].clone()]}, 1);
5131         }
5132         connect_blocks(&nodes[2].block_notifier, ANTI_REORG_DELAY - 1, 1, true,  header.bitcoin_hash());
5133         check_closed_broadcast!(nodes[2], false);
5134         expect_pending_htlcs_forwardable!(nodes[2]);
5135         check_added_monitors!(nodes[2], 3);
5136
5137         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5138         assert_eq!(cs_msgs.len(), 2);
5139         let mut a_done = false;
5140         for msg in cs_msgs {
5141                 match msg {
5142                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5143                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5144                                 // should be failed-backwards here.
5145                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5146                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5147                                         for htlc in &updates.update_fail_htlcs {
5148                                                 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 });
5149                                         }
5150                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5151                                         assert!(!a_done);
5152                                         a_done = true;
5153                                         &nodes[0]
5154                                 } else {
5155                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5156                                         for htlc in &updates.update_fail_htlcs {
5157                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5158                                         }
5159                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5160                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5161                                         &nodes[1]
5162                                 };
5163                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5164                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5165                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5166                                 if announce_latest {
5167                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5168                                         if *node_id == nodes[0].node.get_our_node_id() {
5169                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5170                                         }
5171                                 }
5172                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5173                         },
5174                         _ => panic!("Unexpected event"),
5175                 }
5176         }
5177
5178         let as_events = nodes[0].node.get_and_clear_pending_events();
5179         assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5180         let mut as_failds = HashSet::new();
5181         for event in as_events.iter() {
5182                 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5183                         assert!(as_failds.insert(*payment_hash));
5184                         if *payment_hash != payment_hash_2 {
5185                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5186                         } else {
5187                                 assert!(!rejected_by_dest);
5188                         }
5189                 } else { panic!("Unexpected event"); }
5190         }
5191         assert!(as_failds.contains(&payment_hash_1));
5192         assert!(as_failds.contains(&payment_hash_2));
5193         if announce_latest {
5194                 assert!(as_failds.contains(&payment_hash_3));
5195                 assert!(as_failds.contains(&payment_hash_5));
5196         }
5197         assert!(as_failds.contains(&payment_hash_6));
5198
5199         let bs_events = nodes[1].node.get_and_clear_pending_events();
5200         assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5201         let mut bs_failds = HashSet::new();
5202         for event in bs_events.iter() {
5203                 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5204                         assert!(bs_failds.insert(*payment_hash));
5205                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5206                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5207                         } else {
5208                                 assert!(!rejected_by_dest);
5209                         }
5210                 } else { panic!("Unexpected event"); }
5211         }
5212         assert!(bs_failds.contains(&payment_hash_1));
5213         assert!(bs_failds.contains(&payment_hash_2));
5214         if announce_latest {
5215                 assert!(bs_failds.contains(&payment_hash_4));
5216         }
5217         assert!(bs_failds.contains(&payment_hash_5));
5218
5219         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5220         // get a PaymentFailureNetworkUpdate. A should have gotten 4 HTLCs which were failed-back due
5221         // to unknown-preimage-etc, B should have gotten 2. Thus, in the
5222         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2
5223         // PaymentFailureNetworkUpdates.
5224         let as_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
5225         assert_eq!(as_msg_events.len(), if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5226         let bs_msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5227         assert_eq!(bs_msg_events.len(), if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5228         for event in as_msg_events.iter().chain(bs_msg_events.iter()) {
5229                 match event {
5230                         &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
5231                         _ => panic!("Unexpected event"),
5232                 }
5233         }
5234 }
5235
5236 #[test]
5237 fn test_fail_backwards_latest_remote_announce_a() {
5238         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5239 }
5240
5241 #[test]
5242 fn test_fail_backwards_latest_remote_announce_b() {
5243         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5244 }
5245
5246 #[test]
5247 fn test_fail_backwards_previous_remote_announce() {
5248         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5249         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5250         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5251 }
5252
5253 #[test]
5254 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5255         let chanmon_cfgs = create_chanmon_cfgs(2);
5256         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5257         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5258         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5259
5260         // Create some initial channels
5261         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5262
5263         let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5264         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5265         assert_eq!(local_txn[0].input.len(), 1);
5266         check_spends!(local_txn[0], chan_1.3);
5267
5268         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5269         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5270         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![local_txn[0].clone()] }, 200);
5271         check_closed_broadcast!(nodes[0], false);
5272         check_added_monitors!(nodes[0], 1);
5273
5274         let htlc_timeout = {
5275                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5276                 assert_eq!(node_txn[0].input.len(), 1);
5277                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5278                 check_spends!(node_txn[0], local_txn[0]);
5279                 node_txn[0].clone()
5280         };
5281
5282         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5283         nodes[0].block_notifier.block_connected(&Block { header: header_201, txdata: vec![htlc_timeout.clone()] }, 201);
5284         connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 201, true, header_201.bitcoin_hash());
5285         expect_payment_failed!(nodes[0], our_payment_hash, true);
5286
5287         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5288         let spend_txn = check_spendable_outputs!(nodes[0], 1);
5289         assert_eq!(spend_txn.len(), 3);
5290         assert_eq!(spend_txn[0], spend_txn[1]);
5291         check_spends!(spend_txn[0], local_txn[0]);
5292         check_spends!(spend_txn[2], htlc_timeout);
5293 }
5294
5295 #[test]
5296 fn test_static_output_closing_tx() {
5297         let chanmon_cfgs = create_chanmon_cfgs(2);
5298         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5299         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5300         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5301
5302         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5303
5304         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
5305         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5306
5307         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5308         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![closing_tx.clone()] }, 0);
5309         connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 0, true, header.bitcoin_hash());
5310
5311         let spend_txn = check_spendable_outputs!(nodes[0], 2);
5312         assert_eq!(spend_txn.len(), 1);
5313         check_spends!(spend_txn[0], closing_tx);
5314
5315         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![closing_tx.clone()] }, 0);
5316         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 0, true, header.bitcoin_hash());
5317
5318         let spend_txn = check_spendable_outputs!(nodes[1], 2);
5319         assert_eq!(spend_txn.len(), 1);
5320         check_spends!(spend_txn[0], closing_tx);
5321 }
5322
5323 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5324         let chanmon_cfgs = create_chanmon_cfgs(2);
5325         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5326         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5327         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5328         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5329
5330         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
5331
5332         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5333         // present in B's local commitment transaction, but none of A's commitment transactions.
5334         assert!(nodes[1].node.claim_funds(our_payment_preimage, &None, if use_dust { 50_000 } else { 3_000_000 }));
5335         check_added_monitors!(nodes[1], 1);
5336
5337         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5338         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5339         let events = nodes[0].node.get_and_clear_pending_events();
5340         assert_eq!(events.len(), 1);
5341         match events[0] {
5342                 Event::PaymentSent { payment_preimage } => {
5343                         assert_eq!(payment_preimage, our_payment_preimage);
5344                 },
5345                 _ => panic!("Unexpected event"),
5346         }
5347
5348         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5349         check_added_monitors!(nodes[0], 1);
5350         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5351         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5352         check_added_monitors!(nodes[1], 1);
5353
5354         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5355         for i in 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + CHAN_CONFIRM_DEPTH + 1 {
5356                 nodes[1].block_notifier.block_connected_checked(&header, i, &Vec::new(), &Vec::new());
5357                 header.prev_blockhash = header.bitcoin_hash();
5358         }
5359         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5360         check_closed_broadcast!(nodes[1], false);
5361         check_added_monitors!(nodes[1], 1);
5362 }
5363
5364 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5365         let chanmon_cfgs = create_chanmon_cfgs(2);
5366         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5367         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5368         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5369         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5370         let logger = test_utils::TestLogger::new();
5371
5372         let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5373         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5374         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &Vec::new(), if use_dust { 50000 } else { 3000000 }, TEST_FINAL_CLTV, &logger).unwrap();
5375         nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
5376         check_added_monitors!(nodes[0], 1);
5377
5378         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5379
5380         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5381         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5382         // to "time out" the HTLC.
5383
5384         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5385
5386         for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
5387                 nodes[0].block_notifier.block_connected(&Block { header, txdata: Vec::new()}, i);
5388                 header.prev_blockhash = header.bitcoin_hash();
5389         }
5390         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5391         check_closed_broadcast!(nodes[0], false);
5392         check_added_monitors!(nodes[0], 1);
5393 }
5394
5395 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5396         let chanmon_cfgs = create_chanmon_cfgs(3);
5397         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5398         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5399         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5400         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5401
5402         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5403         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5404         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5405         // actually revoked.
5406         let htlc_value = if use_dust { 50000 } else { 3000000 };
5407         let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5408         assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash, &None));
5409         expect_pending_htlcs_forwardable!(nodes[1]);
5410         check_added_monitors!(nodes[1], 1);
5411
5412         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5413         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5414         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5415         check_added_monitors!(nodes[0], 1);
5416         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5417         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5418         check_added_monitors!(nodes[1], 1);
5419         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5420         check_added_monitors!(nodes[1], 1);
5421         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5422
5423         if check_revoke_no_close {
5424                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5425                 check_added_monitors!(nodes[0], 1);
5426         }
5427
5428         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5429         for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
5430                 nodes[0].block_notifier.block_connected_checked(&header, i, &Vec::new(), &Vec::new());
5431                 header.prev_blockhash = header.bitcoin_hash();
5432         }
5433         if !check_revoke_no_close {
5434                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5435                 check_closed_broadcast!(nodes[0], false);
5436                 check_added_monitors!(nodes[0], 1);
5437         } else {
5438                 expect_payment_failed!(nodes[0], our_payment_hash, true);
5439         }
5440 }
5441
5442 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5443 // There are only a few cases to test here:
5444 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
5445 //    broadcastable commitment transactions result in channel closure,
5446 //  * its included in an unrevoked-but-previous remote commitment transaction,
5447 //  * its included in the latest remote or local commitment transactions.
5448 // We test each of the three possible commitment transactions individually and use both dust and
5449 // non-dust HTLCs.
5450 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5451 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5452 // tested for at least one of the cases in other tests.
5453 #[test]
5454 fn htlc_claim_single_commitment_only_a() {
5455         do_htlc_claim_local_commitment_only(true);
5456         do_htlc_claim_local_commitment_only(false);
5457
5458         do_htlc_claim_current_remote_commitment_only(true);
5459         do_htlc_claim_current_remote_commitment_only(false);
5460 }
5461
5462 #[test]
5463 fn htlc_claim_single_commitment_only_b() {
5464         do_htlc_claim_previous_remote_commitment_only(true, false);
5465         do_htlc_claim_previous_remote_commitment_only(false, false);
5466         do_htlc_claim_previous_remote_commitment_only(true, true);
5467         do_htlc_claim_previous_remote_commitment_only(false, true);
5468 }
5469
5470 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>)
5471         where F1: for <'a> FnMut(&'a mut msgs::UpdateAddHTLC),
5472                                 F2: FnMut(),
5473 {
5474         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);
5475 }
5476
5477 // test_case
5478 // 0: node1 fails backward
5479 // 1: final node fails backward
5480 // 2: payment completed but the user rejects the payment
5481 // 3: final node fails backward (but tamper onion payloads from node0)
5482 // 100: trigger error in the intermediate node and tamper returning fail_htlc
5483 // 200: trigger error in the final node and tamper returning fail_htlc
5484 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>)
5485         where F1: for <'a> FnMut(&'a mut msgs::UpdateAddHTLC),
5486                                 F2: for <'a> FnMut(&'a mut msgs::UpdateFailHTLC),
5487                                 F3: FnMut(),
5488 {
5489
5490         // reset block height
5491         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5492         for ix in 0..nodes.len() {
5493                 nodes[ix].block_notifier.block_connected_checked(&header, 1, &[], &[]);
5494         }
5495
5496         macro_rules! expect_event {
5497                 ($node: expr, $event_type: path) => {{
5498                         let events = $node.node.get_and_clear_pending_events();
5499                         assert_eq!(events.len(), 1);
5500                         match events[0] {
5501                                 $event_type { .. } => {},
5502                                 _ => panic!("Unexpected event"),
5503                         }
5504                 }}
5505         }
5506
5507         macro_rules! expect_htlc_forward {
5508                 ($node: expr) => {{
5509                         expect_event!($node, Event::PendingHTLCsForwardable);
5510                         $node.node.process_pending_htlc_forwards();
5511                 }}
5512         }
5513
5514         // 0 ~~> 2 send payment
5515         nodes[0].node.send_payment(&route, payment_hash.clone(), &None).unwrap();
5516         check_added_monitors!(nodes[0], 1);
5517         let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5518         // temper update_add (0 => 1)
5519         let mut update_add_0 = update_0.update_add_htlcs[0].clone();
5520         if test_case == 0 || test_case == 3 || test_case == 100 {
5521                 callback_msg(&mut update_add_0);
5522                 callback_node();
5523         }
5524         // 0 => 1 update_add & CS
5525         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add_0);
5526         commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
5527
5528         let update_1_0 = match test_case {
5529                 0|100 => { // intermediate node failure; fail backward to 0
5530                         let update_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5531                         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));
5532                         update_1_0
5533                 },
5534                 1|2|3|200 => { // final node failure; forwarding to 2
5535                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5536                         // forwarding on 1
5537                         if test_case != 200 {
5538                                 callback_node();
5539                         }
5540                         expect_htlc_forward!(&nodes[1]);
5541
5542                         let update_1 = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
5543                         check_added_monitors!(&nodes[1], 1);
5544                         assert_eq!(update_1.update_add_htlcs.len(), 1);
5545                         // tamper update_add (1 => 2)
5546                         let mut update_add_1 = update_1.update_add_htlcs[0].clone();
5547                         if test_case != 3 && test_case != 200 {
5548                                 callback_msg(&mut update_add_1);
5549                         }
5550
5551                         // 1 => 2
5552                         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_1);
5553                         commitment_signed_dance!(nodes[2], nodes[1], update_1.commitment_signed, false, true);
5554
5555                         if test_case == 2 || test_case == 200 {
5556                                 expect_htlc_forward!(&nodes[2]);
5557                                 expect_event!(&nodes[2], Event::PaymentReceived);
5558                                 callback_node();
5559                                 expect_pending_htlcs_forwardable!(nodes[2]);
5560                         }
5561
5562                         let update_2_1 = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5563                         if test_case == 2 || test_case == 200 {
5564                                 check_added_monitors!(&nodes[2], 1);
5565                         }
5566                         assert!(update_2_1.update_fail_htlcs.len() == 1);
5567
5568                         let mut fail_msg = update_2_1.update_fail_htlcs[0].clone();
5569                         if test_case == 200 {
5570                                 callback_fail(&mut fail_msg);
5571                         }
5572
5573                         // 2 => 1
5574                         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_msg);
5575                         commitment_signed_dance!(nodes[1], nodes[2], update_2_1.commitment_signed, true);
5576
5577                         // backward fail on 1
5578                         let update_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5579                         assert!(update_1_0.update_fail_htlcs.len() == 1);
5580                         update_1_0
5581                 },
5582                 _ => unreachable!(),
5583         };
5584
5585         // 1 => 0 commitment_signed_dance
5586         if update_1_0.update_fail_htlcs.len() > 0 {
5587                 let mut fail_msg = update_1_0.update_fail_htlcs[0].clone();
5588                 if test_case == 100 {
5589                         callback_fail(&mut fail_msg);
5590                 }
5591                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
5592         } else {
5593                 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_1_0.update_fail_malformed_htlcs[0]);
5594         };
5595
5596         commitment_signed_dance!(nodes[0], nodes[1], update_1_0.commitment_signed, false, true);
5597
5598         let events = nodes[0].node.get_and_clear_pending_events();
5599         assert_eq!(events.len(), 1);
5600         if let &Event::PaymentFailed { payment_hash:_, ref rejected_by_dest, ref error_code, error_data: _ } = &events[0] {
5601                 assert_eq!(*rejected_by_dest, !expected_retryable);
5602                 assert_eq!(*error_code, expected_error_code);
5603         } else {
5604                 panic!("Uexpected event");
5605         }
5606
5607         let events = nodes[0].node.get_and_clear_pending_msg_events();
5608         if expected_channel_update.is_some() {
5609                 assert_eq!(events.len(), 1);
5610                 match events[0] {
5611                         MessageSendEvent::PaymentFailureNetworkUpdate { ref update } => {
5612                                 match update {
5613                                         &HTLCFailChannelUpdate::ChannelUpdateMessage { .. } => {
5614                                                 if let HTLCFailChannelUpdate::ChannelUpdateMessage { .. } = expected_channel_update.unwrap() {} else {
5615                                                         panic!("channel_update not found!");
5616                                                 }
5617                                         },
5618                                         &HTLCFailChannelUpdate::ChannelClosed { ref short_channel_id, ref is_permanent } => {
5619                                                 if let HTLCFailChannelUpdate::ChannelClosed { short_channel_id: ref expected_short_channel_id, is_permanent: ref expected_is_permanent } = expected_channel_update.unwrap() {
5620                                                         assert!(*short_channel_id == *expected_short_channel_id);
5621                                                         assert!(*is_permanent == *expected_is_permanent);
5622                                                 } else {
5623                                                         panic!("Unexpected message event");
5624                                                 }
5625                                         },
5626                                         &HTLCFailChannelUpdate::NodeFailure { ref node_id, ref is_permanent } => {
5627                                                 if let HTLCFailChannelUpdate::NodeFailure { node_id: ref expected_node_id, is_permanent: ref expected_is_permanent } = expected_channel_update.unwrap() {
5628                                                         assert!(*node_id == *expected_node_id);
5629                                                         assert!(*is_permanent == *expected_is_permanent);
5630                                                 } else {
5631                                                         panic!("Unexpected message event");
5632                                                 }
5633                                         },
5634                                 }
5635                         },
5636                         _ => panic!("Unexpected message event"),
5637                 }
5638         } else {
5639                 assert_eq!(events.len(), 0);
5640         }
5641 }
5642
5643 impl msgs::ChannelUpdate {
5644         fn dummy() -> msgs::ChannelUpdate {
5645                 use bitcoin::secp256k1::ffi::Signature as FFISignature;
5646                 use bitcoin::secp256k1::Signature;
5647                 msgs::ChannelUpdate {
5648                         signature: Signature::from(FFISignature::new()),
5649                         contents: msgs::UnsignedChannelUpdate {
5650                                 chain_hash: BlockHash::hash(&vec![0u8][..]),
5651                                 short_channel_id: 0,
5652                                 timestamp: 0,
5653                                 flags: 0,
5654                                 cltv_expiry_delta: 0,
5655                                 htlc_minimum_msat: 0,
5656                                 fee_base_msat: 0,
5657                                 fee_proportional_millionths: 0,
5658                                 excess_data: vec![],
5659                         }
5660                 }
5661         }
5662 }
5663
5664 struct BogusOnionHopData {
5665         data: Vec<u8>
5666 }
5667 impl BogusOnionHopData {
5668         fn new(orig: msgs::OnionHopData) -> Self {
5669                 Self { data: orig.encode() }
5670         }
5671 }
5672 impl Writeable for BogusOnionHopData {
5673         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
5674                 writer.write_all(&self.data[..])
5675         }
5676 }
5677
5678 #[test]
5679 fn test_onion_failure() {
5680         use ln::msgs::ChannelUpdate;
5681         use ln::channelmanager::CLTV_FAR_FAR_AWAY;
5682         use bitcoin::secp256k1;
5683
5684         const BADONION: u16 = 0x8000;
5685         const PERM: u16 = 0x4000;
5686         const NODE: u16 = 0x2000;
5687         const UPDATE: u16 = 0x1000;
5688
5689         let chanmon_cfgs = create_chanmon_cfgs(3);
5690         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5691         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5692         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5693         for node in nodes.iter() {
5694                 *node.keys_manager.override_session_priv.lock().unwrap() = Some(SecretKey::from_slice(&[3; 32]).unwrap());
5695         }
5696         let channels = [create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()), create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known())];
5697         let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5698         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5699         let logger = test_utils::TestLogger::new();
5700         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[2].node.get_our_node_id(), None, &Vec::new(), 40000, TEST_FINAL_CLTV, &logger).unwrap();
5701         // positve case
5702         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 40000, 40_000);
5703
5704         // intermediate node failure
5705         run_onion_failure_test("invalid_realm", 0, &nodes, &route, &payment_hash, |msg| {
5706                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5707                 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
5708                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5709                 let (mut onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 40000, &None, cur_height).unwrap();
5710                 let mut new_payloads = Vec::new();
5711                 for payload in onion_payloads.drain(..) {
5712                         new_payloads.push(BogusOnionHopData::new(payload));
5713                 }
5714                 // break the first (non-final) hop payload by swapping the realm (0) byte for a byte
5715                 // describing a length-1 TLV payload, which is obviously bogus.
5716                 new_payloads[0].data[0] = 1;
5717                 msg.onion_routing_packet = onion_utils::construct_onion_packet_bogus_hopdata(new_payloads, onion_keys, [0; 32], &payment_hash);
5718         }, ||{}, 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
5719
5720         // final node failure
5721         run_onion_failure_test("invalid_realm", 3, &nodes, &route, &payment_hash, |msg| {
5722                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5723                 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
5724                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5725                 let (mut onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 40000, &None, cur_height).unwrap();
5726                 let mut new_payloads = Vec::new();
5727                 for payload in onion_payloads.drain(..) {
5728                         new_payloads.push(BogusOnionHopData::new(payload));
5729                 }
5730                 // break the last-hop payload by swapping the realm (0) byte for a byte describing a
5731                 // length-1 TLV payload, which is obviously bogus.
5732                 new_payloads[1].data[0] = 1;
5733                 msg.onion_routing_packet = onion_utils::construct_onion_packet_bogus_hopdata(new_payloads, onion_keys, [0; 32], &payment_hash);
5734         }, ||{}, false, Some(PERM|22), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
5735
5736         // the following three with run_onion_failure_test_with_fail_intercept() test only the origin node
5737         // receiving simulated fail messages
5738         // intermediate node failure
5739         run_onion_failure_test_with_fail_intercept("temporary_node_failure", 100, &nodes, &route, &payment_hash, |msg| {
5740                 // trigger error
5741                 msg.amount_msat -= 1;
5742         }, |msg| {
5743                 // and tamper returning error message
5744                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5745                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5746                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], NODE|2, &[0;0]);
5747         }, ||{}, true, Some(NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][0].pubkey, is_permanent: false}));
5748
5749         // final node failure
5750         run_onion_failure_test_with_fail_intercept("temporary_node_failure", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
5751                 // and tamper returning error message
5752                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5753                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5754                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], NODE|2, &[0;0]);
5755         }, ||{
5756                 nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
5757         }, true, Some(NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][1].pubkey, is_permanent: false}));
5758
5759         // intermediate node failure
5760         run_onion_failure_test_with_fail_intercept("permanent_node_failure", 100, &nodes, &route, &payment_hash, |msg| {
5761                 msg.amount_msat -= 1;
5762         }, |msg| {
5763                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5764                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5765                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|NODE|2, &[0;0]);
5766         }, ||{}, true, Some(PERM|NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][0].pubkey, is_permanent: true}));
5767
5768         // final node failure
5769         run_onion_failure_test_with_fail_intercept("permanent_node_failure", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
5770                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5771                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5772                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], PERM|NODE|2, &[0;0]);
5773         }, ||{
5774                 nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
5775         }, false, Some(PERM|NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][1].pubkey, is_permanent: true}));
5776
5777         // intermediate node failure
5778         run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 100, &nodes, &route, &payment_hash, |msg| {
5779                 msg.amount_msat -= 1;
5780         }, |msg| {
5781                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5782                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5783                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|NODE|3, &[0;0]);
5784         }, ||{
5785                 nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
5786         }, true, Some(PERM|NODE|3), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][0].pubkey, is_permanent: true}));
5787
5788         // final node failure
5789         run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
5790                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5791                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5792                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], PERM|NODE|3, &[0;0]);
5793         }, ||{
5794                 nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
5795         }, false, Some(PERM|NODE|3), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][1].pubkey, is_permanent: true}));
5796
5797         run_onion_failure_test("invalid_onion_version", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.version = 1; }, ||{}, true,
5798                 Some(BADONION|PERM|4), None);
5799
5800         run_onion_failure_test("invalid_onion_hmac", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.hmac = [3; 32]; }, ||{}, true,
5801                 Some(BADONION|PERM|5), None);
5802
5803         run_onion_failure_test("invalid_onion_key", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.public_key = Err(secp256k1::Error::InvalidPublicKey);}, ||{}, true,
5804                 Some(BADONION|PERM|6), None);
5805
5806         run_onion_failure_test_with_fail_intercept("temporary_channel_failure", 100, &nodes, &route, &payment_hash, |msg| {
5807                 msg.amount_msat -= 1;
5808         }, |msg| {
5809                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5810                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5811                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], UPDATE|7, &ChannelUpdate::dummy().encode_with_len()[..]);
5812         }, ||{}, true, Some(UPDATE|7), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
5813
5814         run_onion_failure_test_with_fail_intercept("permanent_channel_failure", 100, &nodes, &route, &payment_hash, |msg| {
5815                 msg.amount_msat -= 1;
5816         }, |msg| {
5817                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5818                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5819                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|8, &[0;0]);
5820                 // short_channel_id from the processing node
5821         }, ||{}, true, Some(PERM|8), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
5822
5823         run_onion_failure_test_with_fail_intercept("required_channel_feature_missing", 100, &nodes, &route, &payment_hash, |msg| {
5824                 msg.amount_msat -= 1;
5825         }, |msg| {
5826                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5827                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5828                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|9, &[0;0]);
5829                 // short_channel_id from the processing node
5830         }, ||{}, true, Some(PERM|9), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
5831
5832         let mut bogus_route = route.clone();
5833         bogus_route.paths[0][1].short_channel_id -= 1;
5834         run_onion_failure_test("unknown_next_peer", 0, &nodes, &bogus_route, &payment_hash, |_| {}, ||{}, true, Some(PERM|10),
5835           Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: bogus_route.paths[0][1].short_channel_id, is_permanent:true}));
5836
5837         let amt_to_forward = nodes[1].node.channel_state.lock().unwrap().by_id.get(&channels[1].2).unwrap().get_their_htlc_minimum_msat() - 1;
5838         let mut bogus_route = route.clone();
5839         let route_len = bogus_route.paths[0].len();
5840         bogus_route.paths[0][route_len-1].fee_msat = amt_to_forward;
5841         run_onion_failure_test("amount_below_minimum", 0, &nodes, &bogus_route, &payment_hash, |_| {}, ||{}, true, Some(UPDATE|11), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
5842
5843         //TODO: with new config API, we will be able to generate both valid and
5844         //invalid channel_update cases.
5845         run_onion_failure_test("fee_insufficient", 0, &nodes, &route, &payment_hash, |msg| {
5846                 msg.amount_msat -= 1;
5847         }, || {}, true, Some(UPDATE|12), Some(msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id: channels[0].0.contents.short_channel_id, is_permanent: true}));
5848
5849         run_onion_failure_test("incorrect_cltv_expiry", 0, &nodes, &route, &payment_hash, |msg| {
5850                 // need to violate: cltv_expiry - cltv_expiry_delta >= outgoing_cltv_value
5851                 msg.cltv_expiry -= 1;
5852         }, || {}, true, Some(UPDATE|13), Some(msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id: channels[0].0.contents.short_channel_id, is_permanent: true}));
5853
5854         run_onion_failure_test("expiry_too_soon", 0, &nodes, &route, &payment_hash, |msg| {
5855                 let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS + 1;
5856                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5857
5858                 nodes[1].block_notifier.block_connected_checked(&header, height, &[], &[]);
5859         }, ||{}, true, Some(UPDATE|14), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
5860
5861         run_onion_failure_test("unknown_payment_hash", 2, &nodes, &route, &payment_hash, |_| {}, || {
5862                 nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
5863         }, false, Some(PERM|15), None);
5864
5865         run_onion_failure_test("final_expiry_too_soon", 1, &nodes, &route, &payment_hash, |msg| {
5866                 let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS + 1;
5867                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5868
5869                 nodes[2].block_notifier.block_connected_checked(&header, height, &[], &[]);
5870         }, || {}, true, Some(17), None);
5871
5872         run_onion_failure_test("final_incorrect_cltv_expiry", 1, &nodes, &route, &payment_hash, |_| {}, || {
5873                 for (_, pending_forwards) in nodes[1].node.channel_state.lock().unwrap().forward_htlcs.iter_mut() {
5874                         for f in pending_forwards.iter_mut() {
5875                                 match f {
5876                                         &mut HTLCForwardInfo::AddHTLC { ref mut forward_info, .. } =>
5877                                                 forward_info.outgoing_cltv_value += 1,
5878                                         _ => {},
5879                                 }
5880                         }
5881                 }
5882         }, true, Some(18), None);
5883
5884         run_onion_failure_test("final_incorrect_htlc_amount", 1, &nodes, &route, &payment_hash, |_| {}, || {
5885                 // violate amt_to_forward > msg.amount_msat
5886                 for (_, pending_forwards) in nodes[1].node.channel_state.lock().unwrap().forward_htlcs.iter_mut() {
5887                         for f in pending_forwards.iter_mut() {
5888                                 match f {
5889                                         &mut HTLCForwardInfo::AddHTLC { ref mut forward_info, .. } =>
5890                                                 forward_info.amt_to_forward -= 1,
5891                                         _ => {},
5892                                 }
5893                         }
5894                 }
5895         }, true, Some(19), None);
5896
5897         run_onion_failure_test("channel_disabled", 0, &nodes, &route, &payment_hash, |_| {}, || {
5898                 // disconnect event to the channel between nodes[1] ~ nodes[2]
5899                 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
5900                 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5901         }, true, Some(UPDATE|20), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
5902         reconnect_nodes(&nodes[1], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
5903
5904         run_onion_failure_test("expiry_too_far", 0, &nodes, &route, &payment_hash, |msg| {
5905                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5906                 let mut route = route.clone();
5907                 let height = 1;
5908                 route.paths[0][1].cltv_expiry_delta += CLTV_FAR_FAR_AWAY + route.paths[0][0].cltv_expiry_delta + 1;
5909                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5910                 let (onion_payloads, _, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 40000, &None, height).unwrap();
5911                 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
5912                 msg.cltv_expiry = htlc_cltv;
5913                 msg.onion_routing_packet = onion_packet;
5914         }, ||{}, true, Some(21), None);
5915 }
5916
5917 #[test]
5918 #[should_panic]
5919 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5920         let chanmon_cfgs = create_chanmon_cfgs(2);
5921         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5922         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5923         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5924         //Force duplicate channel ids
5925         for node in nodes.iter() {
5926                 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
5927         }
5928
5929         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5930         let channel_value_satoshis=10000;
5931         let push_msat=10001;
5932         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5933         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5934         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5935
5936         //Create a second channel with a channel_id collision
5937         assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5938 }
5939
5940 #[test]
5941 fn bolt2_open_channel_sending_node_checks_part2() {
5942         let chanmon_cfgs = create_chanmon_cfgs(2);
5943         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5944         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5945         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5946
5947         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5948         let channel_value_satoshis=2^24;
5949         let push_msat=10001;
5950         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5951
5952         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5953         let channel_value_satoshis=10000;
5954         // Test when push_msat is equal to 1000 * funding_satoshis.
5955         let push_msat=1000*channel_value_satoshis+1;
5956         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5957
5958         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5959         let channel_value_satoshis=10000;
5960         let push_msat=10001;
5961         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
5962         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5963         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5964
5965         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5966         // 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
5967         assert!(node0_to_1_send_open_channel.channel_flags<=1);
5968
5969         // 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.
5970         assert!(BREAKDOWN_TIMEOUT>0);
5971         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5972
5973         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5974         let chain_hash=genesis_block(Network::Testnet).header.bitcoin_hash();
5975         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5976
5977         // 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.
5978         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5979         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5980         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5981         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5982         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5983 }
5984
5985 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
5986 // 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.
5987 //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.
5988
5989 #[test]
5990 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
5991         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
5992         let chanmon_cfgs = create_chanmon_cfgs(2);
5993         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5994         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5995         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5996         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
5997
5998         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5999         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6000         let logger = test_utils::TestLogger::new();
6001         let mut route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6002         route.paths[0][0].fee_msat = 100;
6003
6004         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { err },
6005                 assert_eq!(err, "Cannot send less than their minimum HTLC value"));
6006         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6007         nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6008 }
6009
6010 #[test]
6011 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6012         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6013         let chanmon_cfgs = create_chanmon_cfgs(2);
6014         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6015         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6016         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6017         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6018         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6019
6020         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6021         let logger = test_utils::TestLogger::new();
6022         let mut route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6023         route.paths[0][0].fee_msat = 0;
6024         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { err },
6025                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6026
6027         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6028         nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6029 }
6030
6031 #[test]
6032 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6033         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6034         let chanmon_cfgs = create_chanmon_cfgs(2);
6035         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6036         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6037         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6038         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6039
6040         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6041         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6042         let logger = test_utils::TestLogger::new();
6043         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6044         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6045         check_added_monitors!(nodes[0], 1);
6046         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6047         updates.update_add_htlcs[0].amount_msat = 0;
6048
6049         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6050         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6051         check_closed_broadcast!(nodes[1], true).unwrap();
6052         check_added_monitors!(nodes[1], 1);
6053 }
6054
6055 #[test]
6056 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6057         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6058         //It is enforced when constructing a route.
6059         let chanmon_cfgs = create_chanmon_cfgs(2);
6060         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6061         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6062         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6063         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 0, InitFeatures::known(), InitFeatures::known());
6064         let logger = test_utils::TestLogger::new();
6065
6066         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6067
6068         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6069         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], 100000000, 500000001, &logger).unwrap();
6070         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::RouteError { err },
6071                 assert_eq!(err, "Channel CLTV overflowed?!"));
6072 }
6073
6074 #[test]
6075 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6076         //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.
6077         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6078         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6079         let chanmon_cfgs = create_chanmon_cfgs(2);
6080         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6081         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6082         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6083         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6084         let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().their_max_accepted_htlcs as u64;
6085
6086         let logger = test_utils::TestLogger::new();
6087         for i in 0..max_accepted_htlcs {
6088                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6089                 let payment_event = {
6090                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6091                         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6092                         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6093                         check_added_monitors!(nodes[0], 1);
6094
6095                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6096                         assert_eq!(events.len(), 1);
6097                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6098                                 assert_eq!(htlcs[0].htlc_id, i);
6099                         } else {
6100                                 assert!(false);
6101                         }
6102                         SendEvent::from_event(events.remove(0))
6103                 };
6104                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6105                 check_added_monitors!(nodes[1], 0);
6106                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6107
6108                 expect_pending_htlcs_forwardable!(nodes[1]);
6109                 expect_payment_received!(nodes[1], our_payment_hash, 100000);
6110         }
6111         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6112         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6113         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6114         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { err },
6115                 assert_eq!(err, "Cannot push more than their max accepted HTLCs"));
6116
6117         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6118         nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6119 }
6120
6121 #[test]
6122 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6123         //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.
6124         let chanmon_cfgs = create_chanmon_cfgs(2);
6125         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6126         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6127         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6128         let channel_value = 100000;
6129         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6130         let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).their_max_htlc_value_in_flight_msat;
6131
6132         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight, max_in_flight);
6133
6134         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6135         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6136         let logger = test_utils::TestLogger::new();
6137         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], max_in_flight+1, TEST_FINAL_CLTV, &logger).unwrap();
6138         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { err },
6139                 assert_eq!(err, "Cannot send value that would put us over the max HTLC value in flight our peer will accept"));
6140
6141         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6142         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);
6143
6144         send_payment(&nodes[0], &[&nodes[1]], max_in_flight, max_in_flight);
6145 }
6146
6147 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6148 #[test]
6149 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6150         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6151         let chanmon_cfgs = create_chanmon_cfgs(2);
6152         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6153         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6154         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6155         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6156         let htlc_minimum_msat: u64;
6157         {
6158                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6159                 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6160                 htlc_minimum_msat = channel.get_our_htlc_minimum_msat();
6161         }
6162
6163         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6164         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6165         let logger = test_utils::TestLogger::new();
6166         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], htlc_minimum_msat, TEST_FINAL_CLTV, &logger).unwrap();
6167         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6168         check_added_monitors!(nodes[0], 1);
6169         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6170         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6171         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6172         assert!(nodes[1].node.list_channels().is_empty());
6173         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6174         assert_eq!(err_msg.data, "Remote side tried to send less than our minimum HTLC value");
6175         check_added_monitors!(nodes[1], 1);
6176 }
6177
6178 #[test]
6179 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6180         //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
6181         let chanmon_cfgs = create_chanmon_cfgs(2);
6182         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6183         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6184         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6185         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6186
6187         let their_channel_reserve = get_channel_value_stat!(nodes[0], chan.2).channel_reserve_msat;
6188
6189         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6190         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6191         let logger = test_utils::TestLogger::new();
6192         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], 5000000-their_channel_reserve, TEST_FINAL_CLTV, &logger).unwrap();
6193         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6194         check_added_monitors!(nodes[0], 1);
6195         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6196
6197         updates.update_add_htlcs[0].amount_msat = 5000000-their_channel_reserve+1;
6198         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6199
6200         assert!(nodes[1].node.list_channels().is_empty());
6201         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6202         assert_eq!(err_msg.data, "Remote HTLC add would put them under their reserve value");
6203         check_added_monitors!(nodes[1], 1);
6204 }
6205
6206 #[test]
6207 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6208         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6209         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
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 mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6214         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6215         let logger = test_utils::TestLogger::new();
6216
6217         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6218
6219         let session_priv = SecretKey::from_slice(&{
6220                 let mut session_key = [0; 32];
6221                 let mut rng = thread_rng();
6222                 rng.fill_bytes(&mut session_key);
6223                 session_key
6224         }).expect("RNG is bad!");
6225
6226         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6227         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], 3999999, TEST_FINAL_CLTV, &logger).unwrap();
6228
6229         let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
6230         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6231         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &None, cur_height).unwrap();
6232         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6233
6234         let mut msg = msgs::UpdateAddHTLC {
6235                 channel_id: chan.2,
6236                 htlc_id: 0,
6237                 amount_msat: 1000,
6238                 payment_hash: our_payment_hash,
6239                 cltv_expiry: htlc_cltv,
6240                 onion_routing_packet: onion_packet.clone(),
6241         };
6242
6243         for i in 0..super::channel::OUR_MAX_HTLCS {
6244                 msg.htlc_id = i as u64;
6245                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6246         }
6247         msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6248         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6249
6250         assert!(nodes[1].node.list_channels().is_empty());
6251         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6252         assert_eq!(err_msg.data, "Remote tried to push more than our max accepted HTLCs");
6253         check_added_monitors!(nodes[1], 1);
6254 }
6255
6256 #[test]
6257 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6258         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6259         let chanmon_cfgs = create_chanmon_cfgs(2);
6260         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6261         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6262         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6263         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6264         let logger = test_utils::TestLogger::new();
6265
6266         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6267         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6268         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6269         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6270         check_added_monitors!(nodes[0], 1);
6271         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6272         updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).their_max_htlc_value_in_flight_msat + 1;
6273         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6274
6275         assert!(nodes[1].node.list_channels().is_empty());
6276         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6277         assert_eq!(err_msg.data,"Remote HTLC add would put them over our max HTLC value");
6278         check_added_monitors!(nodes[1], 1);
6279 }
6280
6281 #[test]
6282 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6283         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6284         let chanmon_cfgs = create_chanmon_cfgs(2);
6285         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6286         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6287         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6288         let logger = test_utils::TestLogger::new();
6289
6290         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6291         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6292         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6293         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6294         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6295         check_added_monitors!(nodes[0], 1);
6296         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6297         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6298         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6299
6300         assert!(nodes[1].node.list_channels().is_empty());
6301         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6302         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6303         check_added_monitors!(nodes[1], 1);
6304 }
6305
6306 #[test]
6307 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6308         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6309         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6310         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6311         let chanmon_cfgs = create_chanmon_cfgs(2);
6312         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6313         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6314         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6315         let logger = test_utils::TestLogger::new();
6316
6317         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6318         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6319         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6320         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6321         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6322         check_added_monitors!(nodes[0], 1);
6323         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6324         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6325
6326         //Disconnect and Reconnect
6327         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6328         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6329         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6330         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6331         assert_eq!(reestablish_1.len(), 1);
6332         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6333         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6334         assert_eq!(reestablish_2.len(), 1);
6335         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6336         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6337         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6338         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6339
6340         //Resend HTLC
6341         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6342         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6343         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6344         check_added_monitors!(nodes[1], 1);
6345         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6346
6347         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6348
6349         assert!(nodes[1].node.list_channels().is_empty());
6350         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6351         assert_eq!(err_msg.data, "Remote skipped HTLC ID");
6352         check_added_monitors!(nodes[1], 1);
6353 }
6354
6355 #[test]
6356 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6357         //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.
6358
6359         let chanmon_cfgs = create_chanmon_cfgs(2);
6360         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6361         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6362         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6363         let logger = test_utils::TestLogger::new();
6364         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6365         let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6366         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6367         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6368         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6369
6370         check_added_monitors!(nodes[0], 1);
6371         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6372         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6373
6374         let update_msg = msgs::UpdateFulfillHTLC{
6375                 channel_id: chan.2,
6376                 htlc_id: 0,
6377                 payment_preimage: our_payment_preimage,
6378         };
6379
6380         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6381
6382         assert!(nodes[0].node.list_channels().is_empty());
6383         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6384         assert_eq!(err_msg.data, "Remote tried to fulfill/fail HTLC before it had been committed");
6385         check_added_monitors!(nodes[0], 1);
6386 }
6387
6388 #[test]
6389 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6390         //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.
6391
6392         let chanmon_cfgs = create_chanmon_cfgs(2);
6393         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6394         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6395         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6396         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6397         let logger = test_utils::TestLogger::new();
6398
6399         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6400         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6401         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6402         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6403         check_added_monitors!(nodes[0], 1);
6404         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6405         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6406
6407         let update_msg = msgs::UpdateFailHTLC{
6408                 channel_id: chan.2,
6409                 htlc_id: 0,
6410                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6411         };
6412
6413         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6414
6415         assert!(nodes[0].node.list_channels().is_empty());
6416         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6417         assert_eq!(err_msg.data, "Remote tried to fulfill/fail HTLC before it had been committed");
6418         check_added_monitors!(nodes[0], 1);
6419 }
6420
6421 #[test]
6422 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6423         //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.
6424
6425         let chanmon_cfgs = create_chanmon_cfgs(2);
6426         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6427         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6428         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6429         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6430         let logger = test_utils::TestLogger::new();
6431
6432         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6433         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6434         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6435         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6436         check_added_monitors!(nodes[0], 1);
6437         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6438         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6439
6440         let update_msg = msgs::UpdateFailMalformedHTLC{
6441                 channel_id: chan.2,
6442                 htlc_id: 0,
6443                 sha256_of_onion: [1; 32],
6444                 failure_code: 0x8000,
6445         };
6446
6447         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6448
6449         assert!(nodes[0].node.list_channels().is_empty());
6450         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6451         assert_eq!(err_msg.data, "Remote tried to fulfill/fail HTLC before it had been committed");
6452         check_added_monitors!(nodes[0], 1);
6453 }
6454
6455 #[test]
6456 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6457         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6458
6459         let chanmon_cfgs = create_chanmon_cfgs(2);
6460         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6461         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6462         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6463         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6464
6465         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6466
6467         nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6468         check_added_monitors!(nodes[1], 1);
6469
6470         let events = nodes[1].node.get_and_clear_pending_msg_events();
6471         assert_eq!(events.len(), 1);
6472         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6473                 match events[0] {
6474                         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, .. } } => {
6475                                 assert!(update_add_htlcs.is_empty());
6476                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6477                                 assert!(update_fail_htlcs.is_empty());
6478                                 assert!(update_fail_malformed_htlcs.is_empty());
6479                                 assert!(update_fee.is_none());
6480                                 update_fulfill_htlcs[0].clone()
6481                         },
6482                         _ => panic!("Unexpected event"),
6483                 }
6484         };
6485
6486         update_fulfill_msg.htlc_id = 1;
6487
6488         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6489
6490         assert!(nodes[0].node.list_channels().is_empty());
6491         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6492         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6493         check_added_monitors!(nodes[0], 1);
6494 }
6495
6496 #[test]
6497 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6498         //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.
6499
6500         let chanmon_cfgs = create_chanmon_cfgs(2);
6501         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6502         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6503         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6504         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6505
6506         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6507
6508         nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6509         check_added_monitors!(nodes[1], 1);
6510
6511         let events = nodes[1].node.get_and_clear_pending_msg_events();
6512         assert_eq!(events.len(), 1);
6513         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6514                 match events[0] {
6515                         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, .. } } => {
6516                                 assert!(update_add_htlcs.is_empty());
6517                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6518                                 assert!(update_fail_htlcs.is_empty());
6519                                 assert!(update_fail_malformed_htlcs.is_empty());
6520                                 assert!(update_fee.is_none());
6521                                 update_fulfill_htlcs[0].clone()
6522                         },
6523                         _ => panic!("Unexpected event"),
6524                 }
6525         };
6526
6527         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6528
6529         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6530
6531         assert!(nodes[0].node.list_channels().is_empty());
6532         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6533         assert_eq!(err_msg.data, "Remote tried to fulfill HTLC with an incorrect preimage");
6534         check_added_monitors!(nodes[0], 1);
6535 }
6536
6537 #[test]
6538 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6539         //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.
6540
6541         let chanmon_cfgs = create_chanmon_cfgs(2);
6542         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6543         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6544         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6545         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6546         let logger = test_utils::TestLogger::new();
6547
6548         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6549         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6550         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6551         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6552         check_added_monitors!(nodes[0], 1);
6553
6554         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6555         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6556
6557         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6558         check_added_monitors!(nodes[1], 0);
6559         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6560
6561         let events = nodes[1].node.get_and_clear_pending_msg_events();
6562
6563         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6564                 match events[0] {
6565                         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, .. } } => {
6566                                 assert!(update_add_htlcs.is_empty());
6567                                 assert!(update_fulfill_htlcs.is_empty());
6568                                 assert!(update_fail_htlcs.is_empty());
6569                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6570                                 assert!(update_fee.is_none());
6571                                 update_fail_malformed_htlcs[0].clone()
6572                         },
6573                         _ => panic!("Unexpected event"),
6574                 }
6575         };
6576         update_msg.failure_code &= !0x8000;
6577         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6578
6579         assert!(nodes[0].node.list_channels().is_empty());
6580         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6581         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6582         check_added_monitors!(nodes[0], 1);
6583 }
6584
6585 #[test]
6586 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6587         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6588         //    * 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.
6589
6590         let chanmon_cfgs = create_chanmon_cfgs(3);
6591         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6592         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6593         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6594         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6595         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6596         let logger = test_utils::TestLogger::new();
6597
6598         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6599
6600         //First hop
6601         let mut payment_event = {
6602                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6603                 let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
6604                 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6605                 check_added_monitors!(nodes[0], 1);
6606                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6607                 assert_eq!(events.len(), 1);
6608                 SendEvent::from_event(events.remove(0))
6609         };
6610         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6611         check_added_monitors!(nodes[1], 0);
6612         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6613         expect_pending_htlcs_forwardable!(nodes[1]);
6614         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6615         assert_eq!(events_2.len(), 1);
6616         check_added_monitors!(nodes[1], 1);
6617         payment_event = SendEvent::from_event(events_2.remove(0));
6618         assert_eq!(payment_event.msgs.len(), 1);
6619
6620         //Second Hop
6621         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6622         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6623         check_added_monitors!(nodes[2], 0);
6624         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6625
6626         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6627         assert_eq!(events_3.len(), 1);
6628         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6629                 match events_3[0] {
6630                         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 } } => {
6631                                 assert!(update_add_htlcs.is_empty());
6632                                 assert!(update_fulfill_htlcs.is_empty());
6633                                 assert!(update_fail_htlcs.is_empty());
6634                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6635                                 assert!(update_fee.is_none());
6636                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6637                         },
6638                         _ => panic!("Unexpected event"),
6639                 }
6640         };
6641
6642         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6643
6644         check_added_monitors!(nodes[1], 0);
6645         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6646         expect_pending_htlcs_forwardable!(nodes[1]);
6647         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6648         assert_eq!(events_4.len(), 1);
6649
6650         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6651         match events_4[0] {
6652                 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, .. } } => {
6653                         assert!(update_add_htlcs.is_empty());
6654                         assert!(update_fulfill_htlcs.is_empty());
6655                         assert_eq!(update_fail_htlcs.len(), 1);
6656                         assert!(update_fail_malformed_htlcs.is_empty());
6657                         assert!(update_fee.is_none());
6658                 },
6659                 _ => panic!("Unexpected event"),
6660         };
6661
6662         check_added_monitors!(nodes[1], 1);
6663 }
6664
6665 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6666         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6667         // 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
6668         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6669
6670         let chanmon_cfgs = create_chanmon_cfgs(2);
6671         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6672         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6673         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6674         let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6675
6676         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
6677
6678         // We route 2 dust-HTLCs between A and B
6679         let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6680         let (_, payment_hash_2) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6681         route_payment(&nodes[0], &[&nodes[1]], 1000000);
6682
6683         // Cache one local commitment tx as previous
6684         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6685
6686         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6687         assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2, &None));
6688         check_added_monitors!(nodes[1], 0);
6689         expect_pending_htlcs_forwardable!(nodes[1]);
6690         check_added_monitors!(nodes[1], 1);
6691
6692         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6693         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6694         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6695         check_added_monitors!(nodes[0], 1);
6696
6697         // Cache one local commitment tx as lastest
6698         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6699
6700         let events = nodes[0].node.get_and_clear_pending_msg_events();
6701         match events[0] {
6702                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6703                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6704                 },
6705                 _ => panic!("Unexpected event"),
6706         }
6707         match events[1] {
6708                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6709                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6710                 },
6711                 _ => panic!("Unexpected event"),
6712         }
6713
6714         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
6715         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
6716         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6717
6718         if announce_latest {
6719                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![as_last_commitment_tx[0].clone()]}, 1);
6720         } else {
6721                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![as_prev_commitment_tx[0].clone()]}, 1);
6722         }
6723
6724         check_closed_broadcast!(nodes[0], false);
6725         check_added_monitors!(nodes[0], 1);
6726
6727         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6728         connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 1, true,  header.bitcoin_hash());
6729         let events = nodes[0].node.get_and_clear_pending_events();
6730         // Only 2 PaymentFailed events should show up, over-dust HTLC has to be failed by timeout tx
6731         assert_eq!(events.len(), 2);
6732         let mut first_failed = false;
6733         for event in events {
6734                 match event {
6735                         Event::PaymentFailed { payment_hash, .. } => {
6736                                 if payment_hash == payment_hash_1 {
6737                                         assert!(!first_failed);
6738                                         first_failed = true;
6739                                 } else {
6740                                         assert_eq!(payment_hash, payment_hash_2);
6741                                 }
6742                         }
6743                         _ => panic!("Unexpected event"),
6744                 }
6745         }
6746 }
6747
6748 #[test]
6749 fn test_failure_delay_dust_htlc_local_commitment() {
6750         do_test_failure_delay_dust_htlc_local_commitment(true);
6751         do_test_failure_delay_dust_htlc_local_commitment(false);
6752 }
6753
6754 #[test]
6755 fn test_no_failure_dust_htlc_local_commitment() {
6756         // Transaction filters for failing back dust htlc based on local commitment txn infos has been
6757         // prone to error, we test here that a dummy transaction don't fail them.
6758
6759         let chanmon_cfgs = create_chanmon_cfgs(2);
6760         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6761         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6762         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6763         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6764
6765         // Rebalance a bit
6766         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
6767
6768         let as_dust_limit = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
6769         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
6770
6771         // We route 2 dust-HTLCs between A and B
6772         let (preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6773         let (preimage_2, _) = route_payment(&nodes[1], &[&nodes[0]], as_dust_limit*1000);
6774
6775         // Build a dummy invalid transaction trying to spend a commitment tx
6776         let input = TxIn {
6777                 previous_output: BitcoinOutPoint { txid: chan.3.txid(), vout: 0 },
6778                 script_sig: Script::new(),
6779                 sequence: 0,
6780                 witness: Vec::new(),
6781         };
6782
6783         let outp = TxOut {
6784                 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
6785                 value: 10000,
6786         };
6787
6788         let dummy_tx = Transaction {
6789                 version: 2,
6790                 lock_time: 0,
6791                 input: vec![input],
6792                 output: vec![outp]
6793         };
6794
6795         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6796         nodes[0].chan_monitor.simple_monitor.block_connected(&header, 1, &[&dummy_tx], &[1;1]);
6797         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6798         assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 0);
6799         // We broadcast a few more block to check everything is all right
6800         connect_blocks(&nodes[0].block_notifier, 20, 1, true,  header.bitcoin_hash());
6801         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6802         assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 0);
6803
6804         claim_payment(&nodes[0], &vec!(&nodes[1])[..], preimage_1, bs_dust_limit*1000);
6805         claim_payment(&nodes[1], &vec!(&nodes[0])[..], preimage_2, as_dust_limit*1000);
6806 }
6807
6808 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
6809         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
6810         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
6811         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
6812         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
6813         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
6814         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
6815
6816         let chanmon_cfgs = create_chanmon_cfgs(3);
6817         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6818         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6819         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6820         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6821
6822         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
6823
6824         let (_payment_preimage_1, dust_hash) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6825         let (_payment_preimage_2, non_dust_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6826
6827         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6828         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
6829
6830         // We revoked bs_commitment_tx
6831         if revoked {
6832                 let (payment_preimage_3, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6833                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 1_000_000);
6834         }
6835
6836         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6837         let mut timeout_tx = Vec::new();
6838         if local {
6839                 // We fail dust-HTLC 1 by broadcast of local commitment tx
6840                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![as_commitment_tx[0].clone()]}, 1);
6841                 check_closed_broadcast!(nodes[0], false);
6842                 check_added_monitors!(nodes[0], 1);
6843                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6844                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
6845                 let parent_hash  = connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 2, true, header.bitcoin_hash());
6846                 expect_payment_failed!(nodes[0], dust_hash, true);
6847                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6848                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
6849                 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6850                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6851                 nodes[0].block_notifier.block_connected(&Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
6852                 let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6853                 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 8, true, header_3.bitcoin_hash());
6854                 expect_payment_failed!(nodes[0], non_dust_hash, true);
6855         } else {
6856                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
6857                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![bs_commitment_tx[0].clone()]}, 1);
6858                 check_closed_broadcast!(nodes[0], false);
6859                 check_added_monitors!(nodes[0], 1);
6860                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6861                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
6862                 let parent_hash  = connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 2, true, header.bitcoin_hash());
6863                 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6864                 if !revoked {
6865                         expect_payment_failed!(nodes[0], dust_hash, true);
6866                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6867                         // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
6868                         nodes[0].block_notifier.block_connected(&Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
6869                         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6870                         let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6871                         connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 8, true, header_3.bitcoin_hash());
6872                         expect_payment_failed!(nodes[0], non_dust_hash, true);
6873                 } else {
6874                         // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
6875                         // commitment tx
6876                         let events = nodes[0].node.get_and_clear_pending_events();
6877                         assert_eq!(events.len(), 2);
6878                         let first;
6879                         match events[0] {
6880                                 Event::PaymentFailed { payment_hash, .. } => {
6881                                         if payment_hash == dust_hash { first = true; }
6882                                         else { first = false; }
6883                                 },
6884                                 _ => panic!("Unexpected event"),
6885                         }
6886                         match events[1] {
6887                                 Event::PaymentFailed { payment_hash, .. } => {
6888                                         if first { assert_eq!(payment_hash, non_dust_hash); }
6889                                         else { assert_eq!(payment_hash, dust_hash); }
6890                                 },
6891                                 _ => panic!("Unexpected event"),
6892                         }
6893                 }
6894         }
6895 }
6896
6897 #[test]
6898 fn test_sweep_outbound_htlc_failure_update() {
6899         do_test_sweep_outbound_htlc_failure_update(false, true);
6900         do_test_sweep_outbound_htlc_failure_update(false, false);
6901         do_test_sweep_outbound_htlc_failure_update(true, false);
6902 }
6903
6904 #[test]
6905 fn test_upfront_shutdown_script() {
6906         // BOLT 2 : Option upfront shutdown script, if peer commit its closing_script at channel opening
6907         // enforce it at shutdown message
6908
6909         let mut config = UserConfig::default();
6910         config.channel_options.announced_channel = true;
6911         config.peer_channel_config_limits.force_announced_channel_preference = false;
6912         config.channel_options.commit_upfront_shutdown_pubkey = false;
6913         let user_cfgs = [None, Some(config), None];
6914         let chanmon_cfgs = create_chanmon_cfgs(3);
6915         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6916         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
6917         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6918
6919         // We test that in case of peer committing upfront to a script, if it changes at closing, we refuse to sign
6920         let flags = InitFeatures::known();
6921         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
6922         nodes[0].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
6923         let mut node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
6924         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
6925         // Test we enforce upfront_scriptpbukey if by providing a diffrent one at closing that  we disconnect peer
6926         nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
6927         assert_eq!(check_closed_broadcast!(nodes[2], true).unwrap().data, "Got shutdown request with a scriptpubkey which did not match their previous scriptpubkey");
6928         check_added_monitors!(nodes[2], 1);
6929
6930         // We test that in case of peer committing upfront to a script, if it doesn't change at closing, we sign
6931         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
6932         nodes[0].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
6933         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
6934         // We test that in case of peer committing upfront to a script, if it oesn't change at closing, we sign
6935         nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
6936         let events = nodes[2].node.get_and_clear_pending_msg_events();
6937         assert_eq!(events.len(), 1);
6938         match events[0] {
6939                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
6940                 _ => panic!("Unexpected event"),
6941         }
6942
6943         // We test that if case of peer non-signaling we don't enforce committed script at channel opening
6944         let flags_no = InitFeatures::known().clear_upfront_shutdown_script();
6945         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags_no, flags.clone());
6946         nodes[0].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
6947         let mut node_1_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
6948         node_1_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
6949         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_1_shutdown);
6950         let events = nodes[1].node.get_and_clear_pending_msg_events();
6951         assert_eq!(events.len(), 1);
6952         match events[0] {
6953                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
6954                 _ => panic!("Unexpected event"),
6955         }
6956
6957         // We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
6958         // channel smoothly, opt-out is from channel initiator here
6959         let chan = create_announced_chan_between_nodes_with_value(&nodes, 1, 0, 1000000, 1000000, flags.clone(), flags.clone());
6960         nodes[1].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
6961         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
6962         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
6963         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
6964         let events = nodes[0].node.get_and_clear_pending_msg_events();
6965         assert_eq!(events.len(), 1);
6966         match events[0] {
6967                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
6968                 _ => panic!("Unexpected event"),
6969         }
6970
6971         //// We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
6972         //// channel smoothly
6973         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags.clone(), flags.clone());
6974         nodes[1].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
6975         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
6976         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
6977         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
6978         let events = nodes[0].node.get_and_clear_pending_msg_events();
6979         assert_eq!(events.len(), 2);
6980         match events[0] {
6981                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
6982                 _ => panic!("Unexpected event"),
6983         }
6984         match events[1] {
6985                 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
6986                 _ => panic!("Unexpected event"),
6987         }
6988 }
6989
6990 #[test]
6991 fn test_user_configurable_csv_delay() {
6992         // We test our channel constructors yield errors when we pass them absurd csv delay
6993
6994         let mut low_our_to_self_config = UserConfig::default();
6995         low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
6996         let mut high_their_to_self_config = UserConfig::default();
6997         high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
6998         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
6999         let chanmon_cfgs = create_chanmon_cfgs(2);
7000         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7001         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7002         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7003
7004         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7005         let keys_manager: Arc<KeysInterface<ChanKeySigner = EnforcingChannelKeys>> = Arc::new(test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet));
7006         if let Err(error) = Channel::new_outbound(&&test_utils::TestFeeEstimator { sat_per_kw: 253 }, &keys_manager, nodes[1].node.get_our_node_id(), 1000000, 1000000, 0, &low_our_to_self_config) {
7007                 match error {
7008                         APIError::APIMisuseError { err } => { assert_eq!(err, "Configured with an unreasonable our_to_self_delay putting user funds at risks"); },
7009                         _ => panic!("Unexpected event"),
7010                 }
7011         } else { assert!(false) }
7012
7013         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7014         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7015         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7016         open_channel.to_self_delay = 200;
7017         if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: 253 }, &keys_manager, nodes[1].node.get_our_node_id(), InitFeatures::known(), &open_channel, 0, &low_our_to_self_config) {
7018                 match error {
7019                         ChannelError::Close(err) => { assert_eq!(err, "Configured with an unreasonable our_to_self_delay putting user funds at risks"); },
7020                         _ => panic!("Unexpected event"),
7021                 }
7022         } else { assert!(false); }
7023
7024         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7025         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7026         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id()));
7027         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7028         accept_channel.to_self_delay = 200;
7029         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7030         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7031                 match action {
7032                         &ErrorAction::SendErrorMessage { ref msg } => {
7033                                 assert_eq!(msg.data,"They wanted our payments to be delayed by a needlessly long period");
7034                         },
7035                         _ => { assert!(false); }
7036                 }
7037         } else { assert!(false); }
7038
7039         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7040         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7041         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7042         open_channel.to_self_delay = 200;
7043         if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: 253 }, &keys_manager, nodes[1].node.get_our_node_id(), InitFeatures::known(), &open_channel, 0, &high_their_to_self_config) {
7044                 match error {
7045                         ChannelError::Close(err) => { assert_eq!(err, "They wanted our payments to be delayed by a needlessly long period"); },
7046                         _ => panic!("Unexpected event"),
7047                 }
7048         } else { assert!(false); }
7049 }
7050
7051 #[test]
7052 fn test_data_loss_protect() {
7053         // We want to be sure that :
7054         // * we don't broadcast our Local Commitment Tx in case of fallen behind
7055         // * we close channel in case of detecting other being fallen behind
7056         // * we are able to claim our own outputs thanks to to_remote being static
7057         let keys_manager;
7058         let logger;
7059         let fee_estimator;
7060         let tx_broadcaster;
7061         let chain_monitor;
7062         let monitor;
7063         let node_state_0;
7064         let chanmon_cfgs = create_chanmon_cfgs(2);
7065         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7066         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7067         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7068
7069         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7070
7071         // Cache node A state before any channel update
7072         let previous_node_state = nodes[0].node.encode();
7073         let mut previous_chan_monitor_state = test_utils::TestVecWriter(Vec::new());
7074         nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut previous_chan_monitor_state).unwrap();
7075
7076         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7077         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7078
7079         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7080         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7081
7082         // Restore node A from previous state
7083         logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7084         let mut chan_monitor = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut ::std::io::Cursor::new(previous_chan_monitor_state.0)).unwrap().1;
7085         chain_monitor = ChainWatchInterfaceUtil::new(Network::Testnet);
7086         tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())};
7087         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
7088         keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
7089         monitor = test_utils::TestChannelMonitor::new(&chain_monitor, &tx_broadcaster, &logger, &fee_estimator);
7090         node_state_0 = {
7091                 let mut channel_monitors = HashMap::new();
7092                 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chan_monitor);
7093                 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut ::std::io::Cursor::new(previous_node_state), ChannelManagerReadArgs {
7094                         keys_manager: &keys_manager,
7095                         fee_estimator: &fee_estimator,
7096                         monitor: &monitor,
7097                         logger: &logger,
7098                         tx_broadcaster: &tx_broadcaster,
7099                         default_config: UserConfig::default(),
7100                         channel_monitors: &mut channel_monitors,
7101                 }).unwrap().1
7102         };
7103         nodes[0].node = &node_state_0;
7104         assert!(monitor.add_monitor(OutPoint { txid: chan.3.txid(), index: 0 }, chan_monitor).is_ok());
7105         nodes[0].chan_monitor = &monitor;
7106         nodes[0].chain_monitor = &chain_monitor;
7107
7108         nodes[0].block_notifier = BlockNotifier::new(&nodes[0].chain_monitor);
7109         nodes[0].block_notifier.register_listener(&nodes[0].chan_monitor.simple_monitor);
7110         nodes[0].block_notifier.register_listener(nodes[0].node);
7111
7112         check_added_monitors!(nodes[0], 1);
7113
7114         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7115         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7116
7117         let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7118
7119         // Check we don't broadcast any transactions following learning of per_commitment_point from B
7120         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7121         check_added_monitors!(nodes[0], 1);
7122
7123         {
7124                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7125                 assert_eq!(node_txn.len(), 0);
7126         }
7127
7128         let mut reestablish_1 = Vec::with_capacity(1);
7129         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7130                 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7131                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7132                         reestablish_1.push(msg.clone());
7133                 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7134                 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7135                         match action {
7136                                 &ErrorAction::SendErrorMessage { ref msg } => {
7137                                         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");
7138                                 },
7139                                 _ => panic!("Unexpected event!"),
7140                         }
7141                 } else {
7142                         panic!("Unexpected event")
7143                 }
7144         }
7145
7146         // Check we close channel detecting A is fallen-behind
7147         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7148         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
7149         check_added_monitors!(nodes[1], 1);
7150
7151
7152         // Check A is able to claim to_remote output
7153         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7154         assert_eq!(node_txn.len(), 1);
7155         check_spends!(node_txn[0], chan.3);
7156         assert_eq!(node_txn[0].output.len(), 3);
7157         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
7158         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()]}, 0);
7159         connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 0, true, header.bitcoin_hash());
7160         let spend_txn = check_spendable_outputs!(nodes[0], 1);
7161         assert_eq!(spend_txn.len(), 1);
7162         check_spends!(spend_txn[0], node_txn[0]);
7163 }
7164
7165 #[test]
7166 fn test_check_htlc_underpaying() {
7167         // Send payment through A -> B but A is maliciously
7168         // sending a probe payment (i.e less than expected value0
7169         // to B, B should refuse payment.
7170
7171         let chanmon_cfgs = create_chanmon_cfgs(2);
7172         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7173         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7174         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7175
7176         // Create some initial channels
7177         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7178
7179         let (payment_preimage, payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 10_000);
7180
7181         // Node 3 is expecting payment of 100_000 but receive 10_000,
7182         // fail htlc like we didn't know the preimage.
7183         nodes[1].node.claim_funds(payment_preimage, &None, 100_000);
7184         nodes[1].node.process_pending_htlc_forwards();
7185
7186         let events = nodes[1].node.get_and_clear_pending_msg_events();
7187         assert_eq!(events.len(), 1);
7188         let (update_fail_htlc, commitment_signed) = match events[0] {
7189                 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 } } => {
7190                         assert!(update_add_htlcs.is_empty());
7191                         assert!(update_fulfill_htlcs.is_empty());
7192                         assert_eq!(update_fail_htlcs.len(), 1);
7193                         assert!(update_fail_malformed_htlcs.is_empty());
7194                         assert!(update_fee.is_none());
7195                         (update_fail_htlcs[0].clone(), commitment_signed)
7196                 },
7197                 _ => panic!("Unexpected event"),
7198         };
7199         check_added_monitors!(nodes[1], 1);
7200
7201         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7202         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7203
7204         // 10_000 msat as u64, followed by a height of 99 as u32
7205         let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7206         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(99));
7207         expect_payment_failed!(nodes[0], payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7208         nodes[1].node.get_and_clear_pending_events();
7209 }
7210
7211 #[test]
7212 fn test_announce_disable_channels() {
7213         // Create 2 channels between A and B. Disconnect B. Call timer_chan_freshness_every_min and check for generated
7214         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7215
7216         let chanmon_cfgs = create_chanmon_cfgs(2);
7217         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7218         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7219         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7220
7221         let short_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7222         let short_id_2 = create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7223         let short_id_3 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7224
7225         // Disconnect peers
7226         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7227         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7228
7229         nodes[0].node.timer_chan_freshness_every_min(); // dirty -> stagged
7230         nodes[0].node.timer_chan_freshness_every_min(); // staged -> fresh
7231         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7232         assert_eq!(msg_events.len(), 3);
7233         for e in msg_events {
7234                 match e {
7235                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7236                                 let short_id = msg.contents.short_channel_id;
7237                                 // Check generated channel_update match list in PendingChannelUpdate
7238                                 if short_id != short_id_1 && short_id != short_id_2 && short_id != short_id_3 {
7239                                         panic!("Generated ChannelUpdate for wrong chan!");
7240                                 }
7241                         },
7242                         _ => panic!("Unexpected event"),
7243                 }
7244         }
7245         // Reconnect peers
7246         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7247         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7248         assert_eq!(reestablish_1.len(), 3);
7249         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7250         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7251         assert_eq!(reestablish_2.len(), 3);
7252
7253         // Reestablish chan_1
7254         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7255         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7256         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7257         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7258         // Reestablish chan_2
7259         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7260         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7261         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7262         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7263         // Reestablish chan_3
7264         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7265         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7266         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7267         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7268
7269         nodes[0].node.timer_chan_freshness_every_min();
7270         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7271 }
7272
7273 #[test]
7274 fn test_bump_penalty_txn_on_revoked_commitment() {
7275         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7276         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7277
7278         let chanmon_cfgs = create_chanmon_cfgs(2);
7279         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7280         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7281         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7282
7283         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7284         let logger = test_utils::TestLogger::new();
7285
7286
7287         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7288         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
7289         let route = get_route(&nodes[1].node.get_our_node_id(), net_graph_msg_handler, &nodes[0].node.get_our_node_id(), None, &Vec::new(), 3000000, 30, &logger).unwrap();
7290         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7291
7292         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7293         // Revoked commitment txn with 5 outputs : to_local, to_remote, anchor, 1 outgoing HTLC, and 1 incoming HTLC
7294         assert_eq!(revoked_txn[0].output.len(), 5);
7295         assert_eq!(revoked_txn[0].input.len(), 1);
7296         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7297         let revoked_txid = revoked_txn[0].txid();
7298
7299         let mut penalty_sum = 0;
7300         for outp in revoked_txn[0].output.iter() {
7301                 if outp.script_pubkey.is_v0_p2wsh() {
7302                         penalty_sum += outp.value;
7303                 }
7304         }
7305
7306         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7307         let header_114 = connect_blocks(&nodes[1].block_notifier, 114, 0, false, Default::default());
7308
7309         // Actually revoke tx by claiming a HTLC
7310         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7311         let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7312         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_txn[0].clone()] }, 115);
7313         check_added_monitors!(nodes[1], 1);
7314
7315         // One or more justice tx should have been broadcast, check it
7316         let penalty_1;
7317         let feerate_1;
7318         {
7319                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7320                 assert_eq!(node_txn.len(), 3); // justice tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout (broadcasted from ChannelManager)
7321                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7322                 assert_eq!(node_txn[0].output.len(), 1);
7323                 check_spends!(node_txn[0], revoked_txn[0]);
7324                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7325                 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
7326                 penalty_1 = node_txn[0].txid();
7327                 node_txn.clear();
7328         };
7329
7330         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7331         let header = connect_blocks(&nodes[1].block_notifier, 3, 115,  true, header.bitcoin_hash());
7332         let mut penalty_2 = penalty_1;
7333         let mut feerate_2 = 0;
7334         {
7335                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7336                 assert_eq!(node_txn.len(), 1);
7337                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7338                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7339                         assert_eq!(node_txn[0].output.len(), 1);
7340                         check_spends!(node_txn[0], revoked_txn[0]);
7341                         penalty_2 = node_txn[0].txid();
7342                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7343                         assert_ne!(penalty_2, penalty_1);
7344                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7345                         feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7346                         // Verify 25% bump heuristic
7347                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7348                         node_txn.clear();
7349                 }
7350         }
7351         assert_ne!(feerate_2, 0);
7352
7353         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7354         connect_blocks(&nodes[1].block_notifier, 3, 118, true, header);
7355         let penalty_3;
7356         let mut feerate_3 = 0;
7357         {
7358                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7359                 assert_eq!(node_txn.len(), 1);
7360                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7361                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7362                         assert_eq!(node_txn[0].output.len(), 1);
7363                         check_spends!(node_txn[0], revoked_txn[0]);
7364                         penalty_3 = node_txn[0].txid();
7365                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7366                         assert_ne!(penalty_3, penalty_2);
7367                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7368                         feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
7369                         // Verify 25% bump heuristic
7370                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7371                         node_txn.clear();
7372                 }
7373         }
7374         assert_ne!(feerate_3, 0);
7375
7376         nodes[1].node.get_and_clear_pending_events();
7377         nodes[1].node.get_and_clear_pending_msg_events();
7378 }
7379
7380 #[test]
7381 fn test_bump_penalty_txn_on_revoked_htlcs() {
7382         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7383         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7384
7385         let chanmon_cfgs = create_chanmon_cfgs(2);
7386         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7387         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7388         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7389
7390         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7391         // Lock HTLC in both directions
7392         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3_000_000).0;
7393         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7394
7395         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7396         assert_eq!(revoked_local_txn[0].input.len(), 1);
7397         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7398
7399         // Revoke local commitment tx
7400         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7401
7402         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7403         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7404         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
7405         check_closed_broadcast!(nodes[1], false);
7406         check_added_monitors!(nodes[1], 1);
7407
7408         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7409         assert_eq!(revoked_htlc_txn.len(), 4);
7410         if revoked_htlc_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7411                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7412                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7413                 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7414                 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7415                 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7416         } else if revoked_htlc_txn[1].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7417                 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7418                 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7419                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7420                 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7421                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7422         }
7423
7424         // Broadcast set of revoked txn on A
7425         let header_128 = connect_blocks(&nodes[0].block_notifier, 128, 0, true, header.bitcoin_hash());
7426         expect_pending_htlcs_forwardable_ignore!(nodes[0]);
7427
7428         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7429         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);
7430         let first;
7431         let feerate_1;
7432         let penalty_txn;
7433         {
7434                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7435                 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7436                 // Verify claim tx are spending revoked HTLC txn
7437                 assert_eq!(node_txn[4].input.len(), 2);
7438                 assert_eq!(node_txn[4].output.len(), 1);
7439                 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7440                 first = node_txn[4].txid();
7441                 // Store both feerates for later comparison
7442                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[4].output[0].value;
7443                 feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
7444                 penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7445                 node_txn.clear();
7446         }
7447
7448         // Connect three more block to see if bumped penalty are issued for HTLC txn
7449         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7450         nodes[0].block_notifier.block_connected(&Block { header: header_130, txdata: penalty_txn }, 130);
7451         {
7452                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7453                 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7454
7455                 check_spends!(node_txn[0], revoked_local_txn[0]);
7456                 check_spends!(node_txn[1], revoked_local_txn[0]);
7457
7458                 node_txn.clear();
7459         };
7460
7461         // Few more blocks to confirm penalty txn
7462         let header_135 = connect_blocks(&nodes[0].block_notifier, 5, 130, true, header_130.bitcoin_hash());
7463         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7464         let header_144 = connect_blocks(&nodes[0].block_notifier, 9, 135, true, header_135);
7465         let node_txn = {
7466                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7467                 assert_eq!(node_txn.len(), 1);
7468
7469                 assert_eq!(node_txn[0].input.len(), 2);
7470                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7471                 // Verify bumped tx is different and 25% bump heuristic
7472                 assert_ne!(first, node_txn[0].txid());
7473                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7474                 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7475                 assert!(feerate_2 * 100 > feerate_1 * 125);
7476                 let txn = vec![node_txn[0].clone()];
7477                 node_txn.clear();
7478                 txn
7479         };
7480         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7481         let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7482         nodes[0].block_notifier.block_connected(&Block { header: header_145, txdata: node_txn }, 145);
7483         connect_blocks(&nodes[0].block_notifier, 20, 145, true, header_145.bitcoin_hash());
7484         {
7485                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7486                 // We verify than no new transaction has been broadcast because previously
7487                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7488                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7489                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7490                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7491                 // up bumped justice generation.
7492                 assert_eq!(node_txn.len(), 0);
7493                 node_txn.clear();
7494         }
7495         check_closed_broadcast!(nodes[0], false);
7496         check_added_monitors!(nodes[0], 1);
7497 }
7498
7499 #[test]
7500 fn test_bump_penalty_txn_on_remote_commitment() {
7501         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7502         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7503
7504         // Create 2 HTLCs
7505         // Provide preimage for one
7506         // Check aggregation
7507
7508         let chanmon_cfgs = create_chanmon_cfgs(2);
7509         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7510         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7511         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7512
7513         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7514         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7515         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7516
7517         // Remote commitment txn with 5 outputs : to_local, to_remote, anchor, 1 outgoing HTLC, and 1 incoming HTLC
7518         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7519         assert_eq!(remote_txn[0].output.len(), 5);
7520         assert_eq!(remote_txn[0].input.len(), 1);
7521         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7522
7523         // Claim a HTLC without revocation (provide B monitor with preimage)
7524         nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000);
7525         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7526         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![remote_txn[0].clone()] }, 1);
7527         check_added_monitors!(nodes[1], 2);
7528
7529         // One or more claim tx should have been broadcast, check it
7530         let timeout;
7531         let preimage;
7532         let feerate_timeout;
7533         let feerate_preimage;
7534         {
7535                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7536                 assert_eq!(node_txn.len(), 5); // 2 * claim tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout + local HTLC-success (broadcasted from ChannelManager)
7537                 assert_eq!(node_txn[0].input.len(), 1);
7538                 assert_eq!(node_txn[1].input.len(), 1);
7539                 check_spends!(node_txn[0], remote_txn[0]);
7540                 check_spends!(node_txn[1], remote_txn[0]);
7541                 check_spends!(node_txn[2], chan.3);
7542                 check_spends!(node_txn[3], node_txn[2]);
7543                 check_spends!(node_txn[4], node_txn[2]);
7544                 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7545                         timeout = node_txn[0].txid();
7546                         let index = node_txn[0].input[0].previous_output.vout;
7547                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7548                         feerate_timeout = fee * 1000 / node_txn[0].get_weight() as u64;
7549
7550                         preimage = node_txn[1].txid();
7551                         let index = node_txn[1].input[0].previous_output.vout;
7552                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7553                         feerate_preimage = fee * 1000 / node_txn[1].get_weight() as u64;
7554                 } else {
7555                         timeout = node_txn[1].txid();
7556                         let index = node_txn[1].input[0].previous_output.vout;
7557                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7558                         feerate_timeout = fee * 1000 / node_txn[1].get_weight() as u64;
7559
7560                         preimage = node_txn[0].txid();
7561                         let index = node_txn[0].input[0].previous_output.vout;
7562                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7563                         feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
7564                 }
7565                 node_txn.clear();
7566         };
7567         assert_ne!(feerate_timeout, 0);
7568         assert_ne!(feerate_preimage, 0);
7569
7570         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7571         connect_blocks(&nodes[1].block_notifier, 15, 1,  true, header.bitcoin_hash());
7572         {
7573                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7574                 assert_eq!(node_txn.len(), 2);
7575                 assert_eq!(node_txn[0].input.len(), 1);
7576                 assert_eq!(node_txn[1].input.len(), 1);
7577                 check_spends!(node_txn[0], remote_txn[0]);
7578                 check_spends!(node_txn[1], remote_txn[0]);
7579                 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7580                         let index = node_txn[0].input[0].previous_output.vout;
7581                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7582                         let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7583                         assert!(new_feerate * 100 > feerate_timeout * 125);
7584                         assert_ne!(timeout, node_txn[0].txid());
7585
7586                         let index = node_txn[1].input[0].previous_output.vout;
7587                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7588                         let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
7589                         assert!(new_feerate * 100 > feerate_preimage * 125);
7590                         assert_ne!(preimage, node_txn[1].txid());
7591                 } else {
7592                         let index = node_txn[1].input[0].previous_output.vout;
7593                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7594                         let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
7595                         assert!(new_feerate * 100 > feerate_timeout * 125);
7596                         assert_ne!(timeout, node_txn[1].txid());
7597
7598                         let index = node_txn[0].input[0].previous_output.vout;
7599                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7600                         let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7601                         assert!(new_feerate * 100 > feerate_preimage * 125);
7602                         assert_ne!(preimage, node_txn[0].txid());
7603                 }
7604                 node_txn.clear();
7605         }
7606
7607         nodes[1].node.get_and_clear_pending_events();
7608         nodes[1].node.get_and_clear_pending_msg_events();
7609 }
7610
7611 #[test]
7612 fn test_set_outpoints_partial_claiming() {
7613         // - remote party claim tx, new bump tx
7614         // - disconnect remote claiming tx, new bump
7615         // - disconnect tx, see no tx anymore
7616         let chanmon_cfgs = create_chanmon_cfgs(2);
7617         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7618         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7619         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7620
7621         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7622         let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7623         let payment_preimage_2 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7624
7625         // Remote commitment txn with 5 outputs: to_local, to_remote, anchor, and 2 outgoing HTLC
7626         let remote_txn = get_local_commitment_txn!(nodes[1], chan.2);
7627         assert_eq!(remote_txn.len(), 3);
7628         assert_eq!(remote_txn[0].output.len(), 5);
7629         assert_eq!(remote_txn[0].input.len(), 1);
7630         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7631         check_spends!(remote_txn[1], remote_txn[0]);
7632         check_spends!(remote_txn[2], remote_txn[0]);
7633
7634         // Connect blocks on node A to advance height towards TEST_FINAL_CLTV
7635         let prev_header_100 = connect_blocks(&nodes[1].block_notifier, 100, 0, false, Default::default());
7636         // Provide node A with both preimage
7637         nodes[0].node.claim_funds(payment_preimage_1, &None, 3_000_000);
7638         nodes[0].node.claim_funds(payment_preimage_2, &None, 3_000_000);
7639         check_added_monitors!(nodes[0], 2);
7640         nodes[0].node.get_and_clear_pending_events();
7641         nodes[0].node.get_and_clear_pending_msg_events();
7642
7643         // Connect blocks on node A commitment transaction
7644         let header = BlockHeader { version: 0x20000000, prev_blockhash: prev_header_100, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7645         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![remote_txn[0].clone()] }, 101);
7646         check_closed_broadcast!(nodes[0], false);
7647         check_added_monitors!(nodes[0], 1);
7648         // Verify node A broadcast tx claiming both HTLCs
7649         {
7650                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7651                 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-Success*2
7652                 assert_eq!(node_txn.len(), 4);
7653                 check_spends!(node_txn[0], remote_txn[0]);
7654                 check_spends!(node_txn[1], chan.3);
7655                 check_spends!(node_txn[2], node_txn[1]);
7656                 check_spends!(node_txn[3], node_txn[1]);
7657                 assert_eq!(node_txn[0].input.len(), 2);
7658                 node_txn.clear();
7659         }
7660
7661         // Connect blocks on node B
7662         connect_blocks(&nodes[1].block_notifier, 135, 0, false, Default::default());
7663         check_closed_broadcast!(nodes[1], false);
7664         check_added_monitors!(nodes[1], 1);
7665         // Verify node B broadcast 2 HTLC-timeout txn
7666         let partial_claim_tx = {
7667                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7668                 assert_eq!(node_txn.len(), 3);
7669                 check_spends!(node_txn[1], node_txn[0]);
7670                 check_spends!(node_txn[2], node_txn[0]);
7671                 assert_eq!(node_txn[1].input.len(), 1);
7672                 assert_eq!(node_txn[2].input.len(), 1);
7673                 node_txn[1].clone()
7674         };
7675
7676         // Broadcast partial claim on node A, should regenerate a claiming tx with HTLC dropped
7677         let header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7678         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![partial_claim_tx.clone()] }, 102);
7679         {
7680                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7681                 assert_eq!(node_txn.len(), 1);
7682                 check_spends!(node_txn[0], remote_txn[0]);
7683                 assert_eq!(node_txn[0].input.len(), 1); //dropped HTLC
7684                 node_txn.clear();
7685         }
7686         nodes[0].node.get_and_clear_pending_msg_events();
7687
7688         // Disconnect last block on node A, should regenerate a claiming tx with HTLC dropped
7689         nodes[0].block_notifier.block_disconnected(&header, 102);
7690         {
7691                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7692                 assert_eq!(node_txn.len(), 1);
7693                 check_spends!(node_txn[0], remote_txn[0]);
7694                 assert_eq!(node_txn[0].input.len(), 2); //resurrected HTLC
7695                 node_txn.clear();
7696         }
7697
7698         //// Disconnect one more block and then reconnect multiple no transaction should be generated
7699         nodes[0].block_notifier.block_disconnected(&header, 101);
7700         connect_blocks(&nodes[1].block_notifier, 15, 101, false, prev_header_100);
7701         {
7702                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7703                 assert_eq!(node_txn.len(), 0);
7704                 node_txn.clear();
7705         }
7706 }
7707
7708 #[test]
7709 fn test_counterparty_raa_skip_no_crash() {
7710         // Previously, if our counterparty sent two RAAs in a row without us having provided a
7711         // commitment transaction, we would have happily carried on and provided them the next
7712         // commitment transaction based on one RAA forward. This would probably eventually have led to
7713         // channel closure, but it would not have resulted in funds loss. Still, our
7714         // EnforcingChannelKeys would have paniced as it doesn't like jumps into the future. Here, we
7715         // check simply that the channel is closed in response to such an RAA, but don't check whether
7716         // we decide to punish our counterparty for revoking their funds (as we don't currently
7717         // implement that).
7718         let chanmon_cfgs = create_chanmon_cfgs(2);
7719         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7720         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7721         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7722         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
7723
7724         let commitment_seed = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&channel_id).unwrap().local_keys.commitment_seed().clone();
7725         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7726         let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7727                 &SecretKey::from_slice(&chan_utils::build_commitment_secret(&commitment_seed, INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7728         let per_commitment_secret = chan_utils::build_commitment_secret(&commitment_seed, INITIAL_COMMITMENT_NUMBER);
7729
7730         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7731                 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
7732         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7733         check_added_monitors!(nodes[1], 1);
7734 }
7735
7736 #[test]
7737 fn test_bump_txn_sanitize_tracking_maps() {
7738         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7739         // verify we clean then right after expiration of ANTI_REORG_DELAY.
7740
7741         let chanmon_cfgs = create_chanmon_cfgs(2);
7742         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7743         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7744         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7745
7746         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7747         // Lock HTLC in both directions
7748         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
7749         route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
7750
7751         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7752         assert_eq!(revoked_local_txn[0].input.len(), 1);
7753         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7754
7755         // Revoke local commitment tx
7756         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 9_000_000);
7757
7758         // Broadcast set of revoked txn on A
7759         let header_128 = connect_blocks(&nodes[0].block_notifier, 128, 0,  false, Default::default());
7760         expect_pending_htlcs_forwardable_ignore!(nodes[0]);
7761
7762         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7763         nodes[0].block_notifier.block_connected(&Block { header: header_129, txdata: vec![revoked_local_txn[0].clone()] }, 129);
7764         check_closed_broadcast!(nodes[0], false);
7765         check_added_monitors!(nodes[0], 1);
7766         let penalty_txn = {
7767                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7768                 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
7769                 check_spends!(node_txn[0], revoked_local_txn[0]);
7770                 check_spends!(node_txn[1], revoked_local_txn[0]);
7771                 check_spends!(node_txn[2], revoked_local_txn[0]);
7772                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7773                 node_txn.clear();
7774                 penalty_txn
7775         };
7776         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7777         nodes[0].block_notifier.block_connected(&Block { header: header_130, txdata: penalty_txn }, 130);
7778         connect_blocks(&nodes[0].block_notifier, 5, 130,  false, header_130.bitcoin_hash());
7779         {
7780                 let monitors = nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap();
7781                 if let Some(monitor) = monitors.get(&OutPoint::new(chan.3.txid(), 0)) {
7782                         assert!(monitor.onchain_tx_handler.pending_claim_requests.is_empty());
7783                         assert!(monitor.onchain_tx_handler.claimable_outpoints.is_empty());
7784                 }
7785         }
7786 }
7787
7788 #[test]
7789 fn test_override_channel_config() {
7790         let chanmon_cfgs = create_chanmon_cfgs(2);
7791         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7792         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7793         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7794
7795         // Node0 initiates a channel to node1 using the override config.
7796         let mut override_config = UserConfig::default();
7797         override_config.own_channel_config.our_to_self_delay = 200;
7798
7799         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
7800
7801         // Assert the channel created by node0 is using the override config.
7802         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7803         assert_eq!(res.channel_flags, 0);
7804         assert_eq!(res.to_self_delay, 200);
7805 }
7806
7807 #[test]
7808 fn test_override_0msat_htlc_minimum() {
7809         let mut zero_config = UserConfig::default();
7810         zero_config.own_channel_config.our_htlc_minimum_msat = 0;
7811         let chanmon_cfgs = create_chanmon_cfgs(2);
7812         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7813         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7814         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7815
7816         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
7817         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7818         assert_eq!(res.htlc_minimum_msat, 1);
7819
7820         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
7821         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7822         assert_eq!(res.htlc_minimum_msat, 1);
7823 }
7824
7825 #[test]
7826 fn test_simple_payment_secret() {
7827         // Simple test of sending a payment with a payment_secret present. This does not use any AMP
7828         // features, however.
7829         let chanmon_cfgs = create_chanmon_cfgs(3);
7830         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7831         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7832         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7833
7834         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7835         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
7836         let logger = test_utils::TestLogger::new();
7837
7838         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
7839         let payment_secret = PaymentSecret([0xdb; 32]);
7840         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
7841         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[2].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
7842         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2]]], 100000, payment_hash, Some(payment_secret.clone()));
7843         // Claiming with all the correct values but the wrong secret should result in nothing...
7844         assert_eq!(nodes[2].node.claim_funds(payment_preimage, &None, 100_000), false);
7845         assert_eq!(nodes[2].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 100_000), false);
7846         // ...but with the right secret we should be able to claim all the way back
7847         claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage, Some(payment_secret.clone()), 100_000);
7848 }
7849
7850 #[test]
7851 fn test_simple_mpp() {
7852         // Simple test of sending a multi-path payment.
7853         let chanmon_cfgs = create_chanmon_cfgs(4);
7854         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7855         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
7856         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7857
7858         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7859         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7860         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7861         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7862         let logger = test_utils::TestLogger::new();
7863
7864         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
7865         let payment_secret = PaymentSecret([0xdb; 32]);
7866         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
7867         let mut route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[3].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
7868         let path = route.paths[0].clone();
7869         route.paths.push(path);
7870         route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
7871         route.paths[0][0].short_channel_id = chan_1_id;
7872         route.paths[0][1].short_channel_id = chan_3_id;
7873         route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
7874         route.paths[1][0].short_channel_id = chan_2_id;
7875         route.paths[1][1].short_channel_id = chan_4_id;
7876         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, Some(payment_secret.clone()));
7877         // Claiming with all the correct values but the wrong secret should result in nothing...
7878         assert_eq!(nodes[3].node.claim_funds(payment_preimage, &None, 200_000), false);
7879         assert_eq!(nodes[3].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 200_000), false);
7880         // ...but with the right secret we should be able to claim all the way back
7881         claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage, Some(payment_secret), 200_000);
7882 }
7883
7884 #[test]
7885 fn test_update_err_monitor_lockdown() {
7886         // Our monitor will lock update of local commitment transaction if a broadcastion condition
7887         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
7888         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
7889         //
7890         // This scenario may happen in a watchtower setup, where watchtower process a block height
7891         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
7892         // commitment at same time.
7893
7894         let chanmon_cfgs = create_chanmon_cfgs(2);
7895         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7896         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7897         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7898
7899         // Create some initial channel
7900         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7901         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
7902
7903         // Rebalance the network to generate htlc in the two directions
7904         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000, 10_000_000);
7905
7906         // Route a HTLC from node 0 to node 1 (but don't settle)
7907         let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
7908
7909         // Copy SimpleManyChannelMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
7910         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7911         let chain_monitor = chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet);
7912         let watchtower = {
7913                 let monitors = nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap();
7914                 let monitor = monitors.get(&outpoint).unwrap();
7915                 let mut w = test_utils::TestVecWriter(Vec::new());
7916                 monitor.write_for_disk(&mut w).unwrap();
7917                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
7918                                 &mut ::std::io::Cursor::new(&w.0)).unwrap().1;
7919                 assert!(new_monitor == *monitor);
7920                 let watchtower = test_utils::TestChannelMonitor::new(&chain_monitor, &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator);
7921                 assert!(watchtower.add_monitor(outpoint, new_monitor).is_ok());
7922                 watchtower
7923         };
7924         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7925         watchtower.simple_monitor.block_connected(&header, 200, &vec![], &vec![]);
7926
7927         // Try to update ChannelMonitor
7928         assert!(nodes[1].node.claim_funds(preimage, &None, 9_000_000));
7929         check_added_monitors!(nodes[1], 1);
7930         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7931         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
7932         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
7933         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
7934                 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator, &node_cfgs[0].logger) {
7935                         if let Err(_) =  watchtower.simple_monitor.update_monitor(outpoint, update.clone()) {} else { assert!(false); }
7936                         if let Ok(_) = nodes[0].chan_monitor.update_monitor(outpoint, update) {} else { assert!(false); }
7937                 } else { assert!(false); }
7938         } else { assert!(false); };
7939         // Our local monitor is in-sync and hasn't processed yet timeout
7940         check_added_monitors!(nodes[0], 1);
7941         let events = nodes[0].node.get_and_clear_pending_events();
7942         assert_eq!(events.len(), 1);
7943 }