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.
5 use chain::transaction::OutPoint;
6 use chain::chaininterface::{ChainListener, ChainWatchInterface};
7 use chain::keysinterface::{KeysInterface, SpendableOutputDescriptor, KeysManager};
8 use ln::channel::{COMMITMENT_TX_BASE_WEIGHT, COMMITMENT_TX_WEIGHT_PER_HTLC};
9 use ln::channelmanager::{ChannelManager,ChannelManagerReadArgs,HTLCForwardInfo,RAACommitmentOrder, PaymentPreimage, PaymentHash, BREAKDOWN_TIMEOUT};
10 use ln::channelmonitor::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ManyChannelMonitor, ANTI_REORG_DELAY};
11 use ln::channel::{ACCEPTED_HTLC_SCRIPT_WEIGHT, OFFERED_HTLC_SCRIPT_WEIGHT, Channel, ChannelError};
13 use ln::router::{Route, RouteHop};
15 use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler,HTLCFailChannelUpdate, LocalFeatures, ErrorAction};
17 use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
18 use util::errors::APIError;
19 use util::ser::{Writeable, ReadableArgs};
20 use util::config::UserConfig;
22 use bitcoin::util::hash::BitcoinHash;
23 use bitcoin_hashes::sha256d::Hash as Sha256dHash;
24 use bitcoin::util::bip143;
25 use bitcoin::util::address::Address;
26 use bitcoin::util::bip32::{ChildNumber, ExtendedPubKey, ExtendedPrivKey};
27 use bitcoin::blockdata::block::{Block, BlockHeader};
28 use bitcoin::blockdata::transaction::{Transaction, TxOut, TxIn, SigHashType, OutPoint as BitcoinOutPoint};
29 use bitcoin::blockdata::script::{Builder, Script};
30 use bitcoin::blockdata::opcodes;
31 use bitcoin::blockdata::constants::genesis_block;
32 use bitcoin::network::constants::Network;
34 use bitcoin_hashes::sha256::Hash as Sha256;
35 use bitcoin_hashes::Hash;
37 use secp256k1::{Secp256k1, Message};
38 use secp256k1::key::{PublicKey,SecretKey};
40 use std::collections::{BTreeSet, HashMap, HashSet};
41 use std::default::Default;
43 use std::sync::atomic::Ordering;
46 use rand::{thread_rng, Rng};
48 use ln::functional_test_utils::*;
51 fn test_async_inbound_update_fee() {
52 let mut nodes = create_network(2, &[None, None]);
53 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
54 let channel_id = chan.2;
57 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
61 // send (1) commitment_signed -.
62 // <- update_add_htlc/commitment_signed
63 // send (2) RAA (awaiting remote revoke) -.
64 // (1) commitment_signed is delivered ->
65 // .- send (3) RAA (awaiting remote revoke)
66 // (2) RAA is delivered ->
67 // .- send (4) commitment_signed
68 // <- (3) RAA is delivered
69 // send (5) commitment_signed -.
70 // <- (4) commitment_signed is delivered
72 // (5) commitment_signed is delivered ->
74 // (6) RAA is delivered ->
76 // First nodes[0] generates an update_fee
77 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
78 check_added_monitors!(nodes[0], 1);
80 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
81 assert_eq!(events_0.len(), 1);
82 let (update_msg, commitment_signed) = match events_0[0] { // (1)
83 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
84 (update_fee.as_ref(), commitment_signed)
86 _ => panic!("Unexpected event"),
89 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
91 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
92 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
93 nodes[1].node.send_payment(nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 40000, TEST_FINAL_CLTV).unwrap(), our_payment_hash).unwrap();
94 check_added_monitors!(nodes[1], 1);
97 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
98 assert_eq!(events_1.len(), 1);
99 SendEvent::from_event(events_1.remove(0))
101 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
102 assert_eq!(payment_event.msgs.len(), 1);
104 // ...now when the messages get delivered everyone should be happy
105 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
106 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap(); // (2)
107 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
108 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
109 check_added_monitors!(nodes[0], 1);
111 // deliver(1), generate (3):
112 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
113 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
114 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
115 check_added_monitors!(nodes[1], 1);
117 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap(); // deliver (2)
118 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
119 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
120 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
121 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
122 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
123 assert!(bs_update.update_fee.is_none()); // (4)
124 check_added_monitors!(nodes[1], 1);
126 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap(); // deliver (3)
127 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
128 assert!(as_update.update_add_htlcs.is_empty()); // (5)
129 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
130 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
131 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
132 assert!(as_update.update_fee.is_none()); // (5)
133 check_added_monitors!(nodes[0], 1);
135 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed).unwrap(); // deliver (4)
136 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
137 // only (6) so get_event_msg's assert(len == 1) passes
138 check_added_monitors!(nodes[0], 1);
140 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed).unwrap(); // deliver (5)
141 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
142 check_added_monitors!(nodes[1], 1);
144 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke).unwrap();
145 check_added_monitors!(nodes[0], 1);
147 let events_2 = nodes[0].node.get_and_clear_pending_events();
148 assert_eq!(events_2.len(), 1);
150 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
151 _ => panic!("Unexpected event"),
154 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke).unwrap(); // deliver (6)
155 check_added_monitors!(nodes[1], 1);
159 fn test_update_fee_unordered_raa() {
160 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
161 // crash in an earlier version of the update_fee patch)
162 let mut nodes = create_network(2, &[None, None]);
163 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
164 let channel_id = chan.2;
167 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
169 // First nodes[0] generates an update_fee
170 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
171 check_added_monitors!(nodes[0], 1);
173 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
174 assert_eq!(events_0.len(), 1);
175 let update_msg = match events_0[0] { // (1)
176 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
179 _ => panic!("Unexpected event"),
182 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
184 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
185 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
186 nodes[1].node.send_payment(nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 40000, TEST_FINAL_CLTV).unwrap(), our_payment_hash).unwrap();
187 check_added_monitors!(nodes[1], 1);
189 let payment_event = {
190 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
191 assert_eq!(events_1.len(), 1);
192 SendEvent::from_event(events_1.remove(0))
194 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
195 assert_eq!(payment_event.msgs.len(), 1);
197 // ...now when the messages get delivered everyone should be happy
198 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
199 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap(); // (2)
200 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
201 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
202 check_added_monitors!(nodes[0], 1);
204 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg).unwrap(); // deliver (2)
205 check_added_monitors!(nodes[1], 1);
207 // We can't continue, sadly, because our (1) now has a bogus signature
211 fn test_multi_flight_update_fee() {
212 let nodes = create_network(2, &[None, None]);
213 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
214 let channel_id = chan.2;
217 // update_fee/commitment_signed ->
218 // .- send (1) RAA and (2) commitment_signed
219 // update_fee (never committed) ->
221 // We have to manually generate the above update_fee, it is allowed by the protocol but we
222 // don't track which updates correspond to which revoke_and_ack responses so we're in
223 // AwaitingRAA mode and will not generate the update_fee yet.
224 // <- (1) RAA delivered
225 // (3) is generated and send (4) CS -.
226 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
227 // know the per_commitment_point to use for it.
228 // <- (2) commitment_signed delivered
230 // B should send no response here
231 // (4) commitment_signed delivered ->
232 // <- RAA/commitment_signed delivered
235 // First nodes[0] generates an update_fee
236 let initial_feerate = get_feerate!(nodes[0], channel_id);
237 nodes[0].node.update_fee(channel_id, initial_feerate + 20).unwrap();
238 check_added_monitors!(nodes[0], 1);
240 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
241 assert_eq!(events_0.len(), 1);
242 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
243 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
244 (update_fee.as_ref().unwrap(), commitment_signed)
246 _ => panic!("Unexpected event"),
249 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
250 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1).unwrap();
251 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1).unwrap();
252 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
253 check_added_monitors!(nodes[1], 1);
255 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
257 nodes[0].node.update_fee(channel_id, initial_feerate + 40).unwrap();
258 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
259 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
261 // Create the (3) update_fee message that nodes[0] will generate before it does...
262 let mut update_msg_2 = msgs::UpdateFee {
263 channel_id: update_msg_1.channel_id.clone(),
264 feerate_per_kw: (initial_feerate + 30) as u32,
267 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2).unwrap();
269 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
271 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2).unwrap();
273 // Deliver (1), generating (3) and (4)
274 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg).unwrap();
275 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
276 check_added_monitors!(nodes[0], 1);
277 assert!(as_second_update.update_add_htlcs.is_empty());
278 assert!(as_second_update.update_fulfill_htlcs.is_empty());
279 assert!(as_second_update.update_fail_htlcs.is_empty());
280 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
281 // Check that the update_fee newly generated matches what we delivered:
282 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
283 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
285 // Deliver (2) commitment_signed
286 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed).unwrap();
287 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
288 check_added_monitors!(nodes[0], 1);
289 // No commitment_signed so get_event_msg's assert(len == 1) passes
291 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg).unwrap();
292 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
293 check_added_monitors!(nodes[1], 1);
296 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed).unwrap();
297 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
298 check_added_monitors!(nodes[1], 1);
300 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke).unwrap();
301 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
302 check_added_monitors!(nodes[0], 1);
304 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment).unwrap();
305 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
306 // No commitment_signed so get_event_msg's assert(len == 1) passes
307 check_added_monitors!(nodes[0], 1);
309 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke).unwrap();
310 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
311 check_added_monitors!(nodes[1], 1);
315 fn test_update_fee_vanilla() {
316 let nodes = create_network(2, &[None, None]);
317 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
318 let channel_id = chan.2;
320 let feerate = get_feerate!(nodes[0], channel_id);
321 nodes[0].node.update_fee(channel_id, feerate+25).unwrap();
322 check_added_monitors!(nodes[0], 1);
324 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
325 assert_eq!(events_0.len(), 1);
326 let (update_msg, commitment_signed) = match events_0[0] {
327 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 } } => {
328 (update_fee.as_ref(), commitment_signed)
330 _ => panic!("Unexpected event"),
332 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
334 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
335 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
336 check_added_monitors!(nodes[1], 1);
338 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
339 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
340 check_added_monitors!(nodes[0], 1);
342 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
343 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
344 // No commitment_signed so get_event_msg's assert(len == 1) passes
345 check_added_monitors!(nodes[0], 1);
347 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
348 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
349 check_added_monitors!(nodes[1], 1);
353 fn test_update_fee_that_funder_cannot_afford() {
354 let nodes = create_network(2, &[None, None]);
355 let channel_value = 1888;
356 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000, LocalFeatures::new(), LocalFeatures::new());
357 let channel_id = chan.2;
360 nodes[0].node.update_fee(channel_id, feerate).unwrap();
361 check_added_monitors!(nodes[0], 1);
362 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
364 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap()).unwrap();
366 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
368 //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
369 //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
371 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
372 let chan = chan_lock.by_id.get(&channel_id).unwrap();
374 //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
375 let num_htlcs = chan.last_local_commitment_txn[0].output.len() - 2;
376 let total_fee: u64 = feerate * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
377 let mut actual_fee = chan.last_local_commitment_txn[0].output.iter().fold(0, |acc, output| acc + output.value);
378 actual_fee = channel_value - actual_fee;
379 assert_eq!(total_fee, actual_fee);
382 //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
383 //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
384 nodes[0].node.update_fee(channel_id, feerate+2).unwrap();
385 check_added_monitors!(nodes[0], 1);
387 let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
389 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap()).unwrap();
391 //While producing the commitment_signed response after handling a received update_fee request the
392 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
393 //Should produce and error.
394 let err = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed).unwrap_err();
396 assert!(match err.err {
397 "Funding remote cannot afford proposed new fee" => true,
401 //clear the message we could not handle
402 nodes[1].node.get_and_clear_pending_msg_events();
406 fn test_update_fee_with_fundee_update_add_htlc() {
407 let mut nodes = create_network(2, &[None, None]);
408 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
409 let channel_id = chan.2;
412 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
414 let feerate = get_feerate!(nodes[0], channel_id);
415 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
416 check_added_monitors!(nodes[0], 1);
418 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
419 assert_eq!(events_0.len(), 1);
420 let (update_msg, commitment_signed) = match events_0[0] {
421 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 } } => {
422 (update_fee.as_ref(), commitment_signed)
424 _ => panic!("Unexpected event"),
426 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
427 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
428 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
429 check_added_monitors!(nodes[1], 1);
431 let route = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 800000, TEST_FINAL_CLTV).unwrap();
433 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]);
435 // nothing happens since node[1] is in AwaitingRemoteRevoke
436 nodes[1].node.send_payment(route, our_payment_hash).unwrap();
438 let mut added_monitors = nodes[0].chan_monitor.added_monitors.lock().unwrap();
439 assert_eq!(added_monitors.len(), 0);
440 added_monitors.clear();
442 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
443 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
444 // node[1] has nothing to do
446 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
447 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
448 check_added_monitors!(nodes[0], 1);
450 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
451 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
452 // No commitment_signed so get_event_msg's assert(len == 1) passes
453 check_added_monitors!(nodes[0], 1);
454 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
455 check_added_monitors!(nodes[1], 1);
456 // AwaitingRemoteRevoke ends here
458 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
459 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
460 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
461 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
462 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
463 assert_eq!(commitment_update.update_fee.is_none(), true);
465 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]).unwrap();
466 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
467 check_added_monitors!(nodes[0], 1);
468 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
470 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke).unwrap();
471 check_added_monitors!(nodes[1], 1);
472 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
474 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed).unwrap();
475 check_added_monitors!(nodes[1], 1);
476 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
477 // No commitment_signed so get_event_msg's assert(len == 1) passes
479 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke).unwrap();
480 check_added_monitors!(nodes[0], 1);
481 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
483 expect_pending_htlcs_forwardable!(nodes[0]);
485 let events = nodes[0].node.get_and_clear_pending_events();
486 assert_eq!(events.len(), 1);
488 Event::PaymentReceived { .. } => { },
489 _ => panic!("Unexpected event"),
492 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
494 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
495 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
496 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
500 fn test_update_fee() {
501 let nodes = create_network(2, &[None, None]);
502 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
503 let channel_id = chan.2;
506 // (1) update_fee/commitment_signed ->
507 // <- (2) revoke_and_ack
508 // .- send (3) commitment_signed
509 // (4) update_fee/commitment_signed ->
510 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
511 // <- (3) commitment_signed delivered
512 // send (6) revoke_and_ack -.
513 // <- (5) deliver revoke_and_ack
514 // (6) deliver revoke_and_ack ->
515 // .- send (7) commitment_signed in response to (4)
516 // <- (7) deliver commitment_signed
519 // Create and deliver (1)...
520 let feerate = get_feerate!(nodes[0], channel_id);
521 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
522 check_added_monitors!(nodes[0], 1);
524 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
525 assert_eq!(events_0.len(), 1);
526 let (update_msg, commitment_signed) = match events_0[0] {
527 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 } } => {
528 (update_fee.as_ref(), commitment_signed)
530 _ => panic!("Unexpected event"),
532 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
534 // Generate (2) and (3):
535 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
536 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
537 check_added_monitors!(nodes[1], 1);
540 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
541 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
542 check_added_monitors!(nodes[0], 1);
544 // Create and deliver (4)...
545 nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
546 check_added_monitors!(nodes[0], 1);
547 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
548 assert_eq!(events_0.len(), 1);
549 let (update_msg, commitment_signed) = match events_0[0] {
550 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 } } => {
551 (update_fee.as_ref(), commitment_signed)
553 _ => panic!("Unexpected event"),
556 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
557 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
558 check_added_monitors!(nodes[1], 1);
560 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
561 // No commitment_signed so get_event_msg's assert(len == 1) passes
563 // Handle (3), creating (6):
564 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0).unwrap();
565 check_added_monitors!(nodes[0], 1);
566 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
567 // No commitment_signed so get_event_msg's assert(len == 1) passes
570 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
571 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
572 check_added_monitors!(nodes[0], 1);
574 // Deliver (6), creating (7):
575 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0).unwrap();
576 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
577 assert!(commitment_update.update_add_htlcs.is_empty());
578 assert!(commitment_update.update_fulfill_htlcs.is_empty());
579 assert!(commitment_update.update_fail_htlcs.is_empty());
580 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
581 assert!(commitment_update.update_fee.is_none());
582 check_added_monitors!(nodes[1], 1);
585 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
586 check_added_monitors!(nodes[0], 1);
587 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
588 // No commitment_signed so get_event_msg's assert(len == 1) passes
590 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
591 check_added_monitors!(nodes[1], 1);
592 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
594 assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
595 assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
596 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
600 fn pre_funding_lock_shutdown_test() {
601 // Test sending a shutdown prior to funding_locked after funding generation
602 let nodes = create_network(2, &[None, None]);
603 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 8000000, 0, LocalFeatures::new(), LocalFeatures::new());
604 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
605 nodes[0].chain_monitor.block_connected_checked(&header, 1, &[&tx; 1], &[1; 1]);
606 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&tx; 1], &[1; 1]);
608 nodes[0].node.close_channel(&OutPoint::new(tx.txid(), 0).to_channel_id()).unwrap();
609 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
610 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
611 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
612 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
614 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
615 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
616 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
617 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
618 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
619 assert!(node_0_none.is_none());
621 assert!(nodes[0].node.list_channels().is_empty());
622 assert!(nodes[1].node.list_channels().is_empty());
626 fn updates_shutdown_wait() {
627 // Test sending a shutdown with outstanding updates pending
628 let mut nodes = create_network(3, &[None, None, None]);
629 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
630 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new());
631 let route_1 = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
632 let route_2 = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
634 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
636 nodes[0].node.close_channel(&chan_1.2).unwrap();
637 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
638 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
639 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
640 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
642 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
643 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
645 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
646 if let Err(APIError::ChannelUnavailable {..}) = nodes[0].node.send_payment(route_1, payment_hash) {}
647 else { panic!("New sends should fail!") };
648 if let Err(APIError::ChannelUnavailable {..}) = nodes[1].node.send_payment(route_2, payment_hash) {}
649 else { panic!("New sends should fail!") };
651 assert!(nodes[2].node.claim_funds(our_payment_preimage));
652 check_added_monitors!(nodes[2], 1);
653 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
654 assert!(updates.update_add_htlcs.is_empty());
655 assert!(updates.update_fail_htlcs.is_empty());
656 assert!(updates.update_fail_malformed_htlcs.is_empty());
657 assert!(updates.update_fee.is_none());
658 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
659 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
660 check_added_monitors!(nodes[1], 1);
661 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
662 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
664 assert!(updates_2.update_add_htlcs.is_empty());
665 assert!(updates_2.update_fail_htlcs.is_empty());
666 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
667 assert!(updates_2.update_fee.is_none());
668 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
669 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]).unwrap();
670 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
672 let events = nodes[0].node.get_and_clear_pending_events();
673 assert_eq!(events.len(), 1);
675 Event::PaymentSent { ref payment_preimage } => {
676 assert_eq!(our_payment_preimage, *payment_preimage);
678 _ => panic!("Unexpected event"),
681 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
682 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
683 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
684 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
685 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
686 assert!(node_0_none.is_none());
688 assert!(nodes[0].node.list_channels().is_empty());
690 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
691 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
692 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
693 assert!(nodes[1].node.list_channels().is_empty());
694 assert!(nodes[2].node.list_channels().is_empty());
698 fn htlc_fail_async_shutdown() {
699 // Test HTLCs fail if shutdown starts even if messages are delivered out-of-order
700 let mut nodes = create_network(3, &[None, None, None]);
701 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
702 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new());
704 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
705 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
706 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
707 check_added_monitors!(nodes[0], 1);
708 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
709 assert_eq!(updates.update_add_htlcs.len(), 1);
710 assert!(updates.update_fulfill_htlcs.is_empty());
711 assert!(updates.update_fail_htlcs.is_empty());
712 assert!(updates.update_fail_malformed_htlcs.is_empty());
713 assert!(updates.update_fee.is_none());
715 nodes[1].node.close_channel(&chan_1.2).unwrap();
716 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
717 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
718 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
720 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]).unwrap();
721 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed).unwrap();
722 check_added_monitors!(nodes[1], 1);
723 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
724 commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
726 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
727 assert!(updates_2.update_add_htlcs.is_empty());
728 assert!(updates_2.update_fulfill_htlcs.is_empty());
729 assert_eq!(updates_2.update_fail_htlcs.len(), 1);
730 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
731 assert!(updates_2.update_fee.is_none());
733 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]).unwrap();
734 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
736 let events = nodes[0].node.get_and_clear_pending_events();
737 assert_eq!(events.len(), 1);
739 Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } => {
740 assert_eq!(our_payment_hash, *payment_hash);
741 assert!(!rejected_by_dest);
743 _ => panic!("Unexpected event"),
746 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
747 assert_eq!(msg_events.len(), 2);
748 let node_0_closing_signed = match msg_events[0] {
749 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
750 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
753 _ => panic!("Unexpected event"),
755 match msg_events[1] {
756 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
757 assert_eq!(msg.contents.short_channel_id, chan_1.0.contents.short_channel_id);
759 _ => panic!("Unexpected event"),
762 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
763 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
764 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
765 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
766 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
767 assert!(node_0_none.is_none());
769 assert!(nodes[0].node.list_channels().is_empty());
771 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
772 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
773 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
774 assert!(nodes[1].node.list_channels().is_empty());
775 assert!(nodes[2].node.list_channels().is_empty());
778 fn do_test_shutdown_rebroadcast(recv_count: u8) {
779 // Test that shutdown/closing_signed is re-sent on reconnect with a variable number of
780 // messages delivered prior to disconnect
781 let nodes = create_network(3, &[None, None, None]);
782 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
783 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new());
785 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
787 nodes[1].node.close_channel(&chan_1.2).unwrap();
788 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
790 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
791 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
793 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
797 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
798 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
800 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
801 let node_0_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
802 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
803 let node_1_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
805 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish).unwrap();
806 let node_1_2nd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
807 assert!(node_1_shutdown == node_1_2nd_shutdown);
809 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish).unwrap();
810 let node_0_2nd_shutdown = if recv_count > 0 {
811 let node_0_2nd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
812 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown).unwrap();
815 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
816 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown).unwrap();
817 get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id())
819 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_2nd_shutdown).unwrap();
821 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
822 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
824 assert!(nodes[2].node.claim_funds(our_payment_preimage));
825 check_added_monitors!(nodes[2], 1);
826 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
827 assert!(updates.update_add_htlcs.is_empty());
828 assert!(updates.update_fail_htlcs.is_empty());
829 assert!(updates.update_fail_malformed_htlcs.is_empty());
830 assert!(updates.update_fee.is_none());
831 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
832 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
833 check_added_monitors!(nodes[1], 1);
834 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
835 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
837 assert!(updates_2.update_add_htlcs.is_empty());
838 assert!(updates_2.update_fail_htlcs.is_empty());
839 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
840 assert!(updates_2.update_fee.is_none());
841 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
842 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]).unwrap();
843 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
845 let events = nodes[0].node.get_and_clear_pending_events();
846 assert_eq!(events.len(), 1);
848 Event::PaymentSent { ref payment_preimage } => {
849 assert_eq!(our_payment_preimage, *payment_preimage);
851 _ => panic!("Unexpected event"),
854 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
856 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
857 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
858 assert!(node_1_closing_signed.is_some());
861 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
862 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
864 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
865 let node_0_2nd_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
866 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
868 // If all closing_signeds weren't delivered we can just resume where we left off...
869 let node_1_2nd_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
871 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish).unwrap();
872 let node_0_3rd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
873 assert!(node_0_2nd_shutdown == node_0_3rd_shutdown);
875 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish).unwrap();
876 let node_1_3rd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
877 assert!(node_1_3rd_shutdown == node_1_2nd_shutdown);
879 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_3rd_shutdown).unwrap();
880 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
882 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_3rd_shutdown).unwrap();
883 let node_0_2nd_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
884 assert!(node_0_closing_signed == node_0_2nd_closing_signed);
886 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed).unwrap();
887 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
888 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
889 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
890 assert!(node_0_none.is_none());
892 // If one node, however, received + responded with an identical closing_signed we end
893 // up erroring and node[0] will try to broadcast its own latest commitment transaction.
894 // There isn't really anything better we can do simply, but in the future we might
895 // explore storing a set of recently-closed channels that got disconnected during
896 // closing_signed and avoiding broadcasting local commitment txn for some timeout to
897 // give our counterparty enough time to (potentially) broadcast a cooperative closing
899 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
901 if let Err(msgs::HandleError{action: Some(msgs::ErrorAction::SendErrorMessage{msg}), ..}) =
902 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish) {
903 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msg);
904 let msgs::ErrorMessage {ref channel_id, ..} = msg;
905 assert_eq!(*channel_id, chan_1.2);
906 } else { panic!("Needed SendErrorMessage close"); }
908 // get_closing_signed_broadcast usually eats the BroadcastChannelUpdate for us and
909 // checks it, but in this case nodes[0] didn't ever get a chance to receive a
910 // closing_signed so we do it ourselves
911 check_closed_broadcast!(nodes[0]);
914 assert!(nodes[0].node.list_channels().is_empty());
916 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
917 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
918 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
919 assert!(nodes[1].node.list_channels().is_empty());
920 assert!(nodes[2].node.list_channels().is_empty());
924 fn test_shutdown_rebroadcast() {
925 do_test_shutdown_rebroadcast(0);
926 do_test_shutdown_rebroadcast(1);
927 do_test_shutdown_rebroadcast(2);
931 fn fake_network_test() {
932 // Simple test which builds a network of ChannelManagers, connects them to each other, and
933 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
934 let nodes = create_network(4, &[None, None, None, None]);
936 // Create some initial channels
937 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
938 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new());
939 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, LocalFeatures::new(), LocalFeatures::new());
941 // Rebalance the network a bit by relaying one payment through all the channels...
942 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
943 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
944 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
945 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
947 // Send some more payments
948 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
949 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
950 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
952 // Test failure packets
953 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
954 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
956 // Add a new channel that skips 3
957 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, LocalFeatures::new(), LocalFeatures::new());
959 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
960 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
961 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
962 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
963 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
964 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
965 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
967 // Do some rebalance loop payments, simultaneously
968 let mut hops = Vec::with_capacity(3);
970 pubkey: nodes[2].node.get_our_node_id(),
971 short_channel_id: chan_2.0.contents.short_channel_id,
973 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
976 pubkey: nodes[3].node.get_our_node_id(),
977 short_channel_id: chan_3.0.contents.short_channel_id,
979 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
982 pubkey: nodes[1].node.get_our_node_id(),
983 short_channel_id: chan_4.0.contents.short_channel_id,
985 cltv_expiry_delta: TEST_FINAL_CLTV,
987 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;
988 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;
989 let payment_preimage_1 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
991 let mut hops = Vec::with_capacity(3);
993 pubkey: nodes[3].node.get_our_node_id(),
994 short_channel_id: chan_4.0.contents.short_channel_id,
996 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
999 pubkey: nodes[2].node.get_our_node_id(),
1000 short_channel_id: chan_3.0.contents.short_channel_id,
1002 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1004 hops.push(RouteHop {
1005 pubkey: nodes[1].node.get_our_node_id(),
1006 short_channel_id: chan_2.0.contents.short_channel_id,
1008 cltv_expiry_delta: TEST_FINAL_CLTV,
1010 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;
1011 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;
1012 let payment_hash_2 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1014 // Claim the rebalances...
1015 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1016 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1018 // Add a duplicate new channel from 2 to 4
1019 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, LocalFeatures::new(), LocalFeatures::new());
1021 // Send some payments across both channels
1022 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1023 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1024 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1026 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1028 //TODO: Test that routes work again here as we've been notified that the channel is full
1030 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
1031 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
1032 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
1034 // Close down the channels...
1035 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1036 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1037 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1038 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1039 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1043 fn holding_cell_htlc_counting() {
1044 // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1045 // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1046 // commitment dance rounds.
1047 let mut nodes = create_network(3, &[None, None, None]);
1048 create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
1049 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new());
1051 let mut payments = Vec::new();
1052 for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1053 let route = nodes[1].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV).unwrap();
1054 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1055 nodes[1].node.send_payment(route, payment_hash).unwrap();
1056 payments.push((payment_preimage, payment_hash));
1058 check_added_monitors!(nodes[1], 1);
1060 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1061 assert_eq!(events.len(), 1);
1062 let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1063 assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1065 // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1066 // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1068 let route = nodes[1].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV).unwrap();
1069 let (_, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
1070 if let APIError::ChannelUnavailable { err } = nodes[1].node.send_payment(route, payment_hash_1).unwrap_err() {
1071 assert_eq!(err, "Cannot push more than their max accepted HTLCs");
1072 } else { panic!("Unexpected event"); }
1074 // This should also be true if we try to forward a payment.
1075 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV).unwrap();
1076 let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
1077 nodes[0].node.send_payment(route, payment_hash_2).unwrap();
1078 check_added_monitors!(nodes[0], 1);
1080 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1081 assert_eq!(events.len(), 1);
1082 let payment_event = SendEvent::from_event(events.pop().unwrap());
1083 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1085 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
1086 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1087 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1088 // fails), the second will process the resulting failure and fail the HTLC backward.
1089 expect_pending_htlcs_forwardable!(nodes[1]);
1090 expect_pending_htlcs_forwardable!(nodes[1]);
1091 check_added_monitors!(nodes[1], 1);
1093 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1094 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]).unwrap();
1095 commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1097 let events = nodes[0].node.get_and_clear_pending_msg_events();
1098 assert_eq!(events.len(), 1);
1100 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
1101 assert_eq!(msg.contents.short_channel_id, chan_2.0.contents.short_channel_id);
1103 _ => panic!("Unexpected event"),
1106 let events = nodes[0].node.get_and_clear_pending_events();
1107 assert_eq!(events.len(), 1);
1109 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
1110 assert_eq!(payment_hash, payment_hash_2);
1111 assert!(!rejected_by_dest);
1113 _ => panic!("Unexpected event"),
1116 // Now forward all the pending HTLCs and claim them back
1117 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]).unwrap();
1118 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg).unwrap();
1119 check_added_monitors!(nodes[2], 1);
1121 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1122 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
1123 check_added_monitors!(nodes[1], 1);
1124 let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1126 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed).unwrap();
1127 check_added_monitors!(nodes[1], 1);
1128 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1130 for ref update in as_updates.update_add_htlcs.iter() {
1131 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update).unwrap();
1133 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed).unwrap();
1134 check_added_monitors!(nodes[2], 1);
1135 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
1136 check_added_monitors!(nodes[2], 1);
1137 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1139 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
1140 check_added_monitors!(nodes[1], 1);
1141 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed).unwrap();
1142 check_added_monitors!(nodes[1], 1);
1143 let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1145 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa).unwrap();
1146 check_added_monitors!(nodes[2], 1);
1148 expect_pending_htlcs_forwardable!(nodes[2]);
1150 let events = nodes[2].node.get_and_clear_pending_events();
1151 assert_eq!(events.len(), payments.len());
1152 for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1154 &Event::PaymentReceived { ref payment_hash, .. } => {
1155 assert_eq!(*payment_hash, *hash);
1157 _ => panic!("Unexpected event"),
1161 for (preimage, _) in payments.drain(..) {
1162 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1165 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1169 fn duplicate_htlc_test() {
1170 // Test that we accept duplicate payment_hash HTLCs across the network and that
1171 // claiming/failing them are all separate and don't affect each other
1172 let mut nodes = create_network(6, &[None, None, None, None, None, None]);
1174 // Create some initial channels to route via 3 to 4/5 from 0/1/2
1175 create_announced_chan_between_nodes(&nodes, 0, 3, LocalFeatures::new(), LocalFeatures::new());
1176 create_announced_chan_between_nodes(&nodes, 1, 3, LocalFeatures::new(), LocalFeatures::new());
1177 create_announced_chan_between_nodes(&nodes, 2, 3, LocalFeatures::new(), LocalFeatures::new());
1178 create_announced_chan_between_nodes(&nodes, 3, 4, LocalFeatures::new(), LocalFeatures::new());
1179 create_announced_chan_between_nodes(&nodes, 3, 5, LocalFeatures::new(), LocalFeatures::new());
1181 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1183 *nodes[0].network_payment_count.borrow_mut() -= 1;
1184 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1186 *nodes[0].network_payment_count.borrow_mut() -= 1;
1187 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1189 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1190 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1191 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1194 fn do_channel_reserve_test(test_recv: bool) {
1195 use std::sync::atomic::Ordering;
1196 use ln::msgs::HandleError;
1198 let mut nodes = create_network(3, &[None, None, None]);
1199 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1900, 1001, LocalFeatures::new(), LocalFeatures::new());
1200 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1900, 1001, LocalFeatures::new(), LocalFeatures::new());
1202 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1203 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1205 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1206 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1208 macro_rules! get_route_and_payment_hash {
1209 ($recv_value: expr) => {{
1210 let route = nodes[0].router.get_route(&nodes.last().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV).unwrap();
1211 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1212 (route, payment_hash, payment_preimage)
1216 macro_rules! expect_forward {
1218 let mut events = $node.node.get_and_clear_pending_msg_events();
1219 assert_eq!(events.len(), 1);
1220 check_added_monitors!($node, 1);
1221 let payment_event = SendEvent::from_event(events.remove(0));
1226 let feemsat = 239; // somehow we know?
1227 let total_fee_msat = (nodes.len() - 2) as u64 * 239;
1229 let recv_value_0 = stat01.their_max_htlc_value_in_flight_msat - total_fee_msat;
1231 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1233 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0 + 1);
1234 assert!(route.hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1235 let err = nodes[0].node.send_payment(route, our_payment_hash).err().unwrap();
1237 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over the max HTLC value in flight"),
1238 _ => panic!("Unknown error variants"),
1242 let mut htlc_id = 0;
1243 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1244 // nodes[0]'s wealth
1246 let amt_msat = recv_value_0 + total_fee_msat;
1247 if stat01.value_to_self_msat - amt_msat < stat01.channel_reserve_msat {
1250 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0);
1253 let (stat01_, stat11_, stat12_, stat22_) = (
1254 get_channel_value_stat!(nodes[0], chan_1.2),
1255 get_channel_value_stat!(nodes[1], chan_1.2),
1256 get_channel_value_stat!(nodes[1], chan_2.2),
1257 get_channel_value_stat!(nodes[2], chan_2.2),
1260 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1261 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1262 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1263 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1264 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1268 let recv_value = stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat;
1269 // attempt to get channel_reserve violation
1270 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value + 1);
1271 let err = nodes[0].node.send_payment(route.clone(), our_payment_hash).err().unwrap();
1273 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over the reserve value"),
1274 _ => panic!("Unknown error variants"),
1278 // adding pending output
1279 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat)/2;
1280 let amt_msat_1 = recv_value_1 + total_fee_msat;
1282 let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
1283 let payment_event_1 = {
1284 nodes[0].node.send_payment(route_1, our_payment_hash_1).unwrap();
1285 check_added_monitors!(nodes[0], 1);
1287 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1288 assert_eq!(events.len(), 1);
1289 SendEvent::from_event(events.remove(0))
1291 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]).unwrap();
1293 // channel reserve test with htlc pending output > 0
1294 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat;
1296 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
1297 match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
1298 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over the reserve value"),
1299 _ => panic!("Unknown error variants"),
1304 // test channel_reserve test on nodes[1] side
1305 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
1307 // Need to manually create update_add_htlc message to go around the channel reserve check in send_htlc()
1308 let secp_ctx = Secp256k1::new();
1309 let session_priv = SecretKey::from_slice(&{
1310 let mut session_key = [0; 32];
1311 let mut rng = thread_rng();
1312 rng.fill_bytes(&mut session_key);
1314 }).expect("RNG is bad!");
1316 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1317 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route, &session_priv).unwrap();
1318 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route, cur_height).unwrap();
1319 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, &our_payment_hash);
1320 let msg = msgs::UpdateAddHTLC {
1321 channel_id: chan_1.2,
1323 amount_msat: htlc_msat,
1324 payment_hash: our_payment_hash,
1325 cltv_expiry: htlc_cltv,
1326 onion_routing_packet: onion_packet,
1330 let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg).err().unwrap();
1332 HandleError{err, .. } => assert_eq!(err, "Remote HTLC add would put them over their reserve value"),
1334 // If we send a garbage message, the channel should get closed, making the rest of this test case fail.
1335 assert_eq!(nodes[1].node.list_channels().len(), 1);
1336 assert_eq!(nodes[1].node.list_channels().len(), 1);
1337 check_closed_broadcast!(nodes[1]);
1342 // split the rest to test holding cell
1343 let recv_value_21 = recv_value_2/2;
1344 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat;
1346 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
1347 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);
1350 // now see if they go through on both sides
1351 let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
1352 // but this will stuck in the holding cell
1353 nodes[0].node.send_payment(route_21, our_payment_hash_21).unwrap();
1354 check_added_monitors!(nodes[0], 0);
1355 let events = nodes[0].node.get_and_clear_pending_events();
1356 assert_eq!(events.len(), 0);
1358 // test with outbound holding cell amount > 0
1360 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+1);
1361 match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
1362 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over the reserve value"),
1363 _ => panic!("Unknown error variants"),
1367 let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
1368 // this will also stuck in the holding cell
1369 nodes[0].node.send_payment(route_22, our_payment_hash_22).unwrap();
1370 check_added_monitors!(nodes[0], 0);
1371 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1372 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1374 // flush the pending htlc
1375 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg).unwrap();
1376 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1377 check_added_monitors!(nodes[1], 1);
1379 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
1380 check_added_monitors!(nodes[0], 1);
1381 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1383 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed).unwrap();
1384 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1385 // No commitment_signed so get_event_msg's assert(len == 1) passes
1386 check_added_monitors!(nodes[0], 1);
1388 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
1389 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1390 check_added_monitors!(nodes[1], 1);
1392 expect_pending_htlcs_forwardable!(nodes[1]);
1394 let ref payment_event_11 = expect_forward!(nodes[1]);
1395 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]).unwrap();
1396 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1398 expect_pending_htlcs_forwardable!(nodes[2]);
1399 expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
1401 // flush the htlcs in the holding cell
1402 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1403 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]).unwrap();
1404 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]).unwrap();
1405 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1406 expect_pending_htlcs_forwardable!(nodes[1]);
1408 let ref payment_event_3 = expect_forward!(nodes[1]);
1409 assert_eq!(payment_event_3.msgs.len(), 2);
1410 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]).unwrap();
1411 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]).unwrap();
1413 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1414 expect_pending_htlcs_forwardable!(nodes[2]);
1416 let events = nodes[2].node.get_and_clear_pending_events();
1417 assert_eq!(events.len(), 2);
1419 Event::PaymentReceived { ref payment_hash, amt } => {
1420 assert_eq!(our_payment_hash_21, *payment_hash);
1421 assert_eq!(recv_value_21, amt);
1423 _ => panic!("Unexpected event"),
1426 Event::PaymentReceived { ref payment_hash, amt } => {
1427 assert_eq!(our_payment_hash_22, *payment_hash);
1428 assert_eq!(recv_value_22, amt);
1430 _ => panic!("Unexpected event"),
1433 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
1434 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
1435 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
1437 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);
1438 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
1439 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
1440 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat);
1442 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
1443 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22);
1447 fn channel_reserve_test() {
1448 do_channel_reserve_test(false);
1449 do_channel_reserve_test(true);
1453 fn channel_reserve_in_flight_removes() {
1454 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
1455 // can send to its counterparty, but due to update ordering, the other side may not yet have
1456 // considered those HTLCs fully removed.
1457 // This tests that we don't count HTLCs which will not be included in the next remote
1458 // commitment transaction towards the reserve value (as it implies no commitment transaction
1459 // will be generated which violates the remote reserve value).
1460 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
1462 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
1463 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
1464 // you only consider the value of the first HTLC, it may not),
1465 // * start routing a third HTLC from A to B,
1466 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
1467 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
1468 // * deliver the first fulfill from B
1469 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
1471 // * deliver A's response CS and RAA.
1472 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
1473 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
1474 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
1475 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
1476 let mut nodes = create_network(2, &[None, None]);
1477 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
1479 let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
1480 // Route the first two HTLCs.
1481 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000);
1482 let (payment_preimage_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20000);
1484 // Start routing the third HTLC (this is just used to get everyone in the right state).
1485 let (payment_preimage_3, payment_hash_3) = get_payment_preimage_hash!(nodes[0]);
1487 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
1488 nodes[0].node.send_payment(route, payment_hash_3).unwrap();
1489 check_added_monitors!(nodes[0], 1);
1490 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1491 assert_eq!(events.len(), 1);
1492 SendEvent::from_event(events.remove(0))
1495 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
1496 // initial fulfill/CS.
1497 assert!(nodes[1].node.claim_funds(payment_preimage_1));
1498 check_added_monitors!(nodes[1], 1);
1499 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1501 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
1502 // remove the second HTLC when we send the HTLC back from B to A.
1503 assert!(nodes[1].node.claim_funds(payment_preimage_2));
1504 check_added_monitors!(nodes[1], 1);
1505 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1507 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]).unwrap();
1508 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed).unwrap();
1509 check_added_monitors!(nodes[0], 1);
1510 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1511 expect_payment_sent!(nodes[0], payment_preimage_1);
1513 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]).unwrap();
1514 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg).unwrap();
1515 check_added_monitors!(nodes[1], 1);
1516 // B is already AwaitingRAA, so cant generate a CS here
1517 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1519 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa).unwrap();
1520 check_added_monitors!(nodes[1], 1);
1521 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1523 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa).unwrap();
1524 check_added_monitors!(nodes[0], 1);
1525 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1527 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed).unwrap();
1528 check_added_monitors!(nodes[1], 1);
1529 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1531 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
1532 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
1533 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
1534 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
1535 // on-chain as necessary).
1536 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]).unwrap();
1537 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed).unwrap();
1538 check_added_monitors!(nodes[0], 1);
1539 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1540 expect_payment_sent!(nodes[0], payment_preimage_2);
1542 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa).unwrap();
1543 check_added_monitors!(nodes[1], 1);
1544 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1546 expect_pending_htlcs_forwardable!(nodes[1]);
1547 expect_payment_received!(nodes[1], payment_hash_3, 100000);
1549 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
1550 // resolve the second HTLC from A's point of view.
1551 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa).unwrap();
1552 check_added_monitors!(nodes[0], 1);
1553 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1555 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
1556 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
1557 let (payment_preimage_4, payment_hash_4) = get_payment_preimage_hash!(nodes[1]);
1559 let route = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &[], 10000, TEST_FINAL_CLTV).unwrap();
1560 nodes[1].node.send_payment(route, payment_hash_4).unwrap();
1561 check_added_monitors!(nodes[1], 1);
1562 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1563 assert_eq!(events.len(), 1);
1564 SendEvent::from_event(events.remove(0))
1567 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]).unwrap();
1568 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg).unwrap();
1569 check_added_monitors!(nodes[0], 1);
1570 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1572 // Now just resolve all the outstanding messages/HTLCs for completeness...
1574 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed).unwrap();
1575 check_added_monitors!(nodes[1], 1);
1576 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1578 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa).unwrap();
1579 check_added_monitors!(nodes[1], 1);
1581 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa).unwrap();
1582 check_added_monitors!(nodes[0], 1);
1583 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1585 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed).unwrap();
1586 check_added_monitors!(nodes[1], 1);
1587 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1589 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa).unwrap();
1590 check_added_monitors!(nodes[0], 1);
1592 expect_pending_htlcs_forwardable!(nodes[0]);
1593 expect_payment_received!(nodes[0], payment_hash_4, 10000);
1595 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
1596 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
1600 fn channel_monitor_network_test() {
1601 // Simple test which builds a network of ChannelManagers, connects them to each other, and
1602 // tests that ChannelMonitor is able to recover from various states.
1603 let nodes = create_network(5, &[None, None, None, None, None]);
1605 // Create some initial channels
1606 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
1607 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new());
1608 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, LocalFeatures::new(), LocalFeatures::new());
1609 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, LocalFeatures::new(), LocalFeatures::new());
1611 // Rebalance the network a bit by relaying one payment through all the channels...
1612 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
1613 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
1614 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
1615 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
1617 // Simple case with no pending HTLCs:
1618 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
1620 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
1621 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1622 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
1623 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
1625 get_announce_close_broadcast_events(&nodes, 0, 1);
1626 assert_eq!(nodes[0].node.list_channels().len(), 0);
1627 assert_eq!(nodes[1].node.list_channels().len(), 1);
1629 // One pending HTLC is discarded by the force-close:
1630 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
1632 // Simple case of one pending HTLC to HTLC-Timeout
1633 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
1635 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
1636 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1637 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
1638 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
1640 get_announce_close_broadcast_events(&nodes, 1, 2);
1641 assert_eq!(nodes[1].node.list_channels().len(), 0);
1642 assert_eq!(nodes[2].node.list_channels().len(), 1);
1644 macro_rules! claim_funds {
1645 ($node: expr, $prev_node: expr, $preimage: expr) => {
1647 assert!($node.node.claim_funds($preimage));
1648 check_added_monitors!($node, 1);
1650 let events = $node.node.get_and_clear_pending_msg_events();
1651 assert_eq!(events.len(), 1);
1653 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
1654 assert!(update_add_htlcs.is_empty());
1655 assert!(update_fail_htlcs.is_empty());
1656 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
1658 _ => panic!("Unexpected event"),
1664 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
1665 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
1666 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
1668 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
1670 // Claim the payment on nodes[3], giving it knowledge of the preimage
1671 claim_funds!(nodes[3], nodes[2], payment_preimage_1);
1673 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1674 nodes[3].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 1);
1676 check_preimage_claim(&nodes[3], &node_txn);
1678 get_announce_close_broadcast_events(&nodes, 2, 3);
1679 assert_eq!(nodes[2].node.list_channels().len(), 0);
1680 assert_eq!(nodes[3].node.list_channels().len(), 1);
1682 { // Cheat and reset nodes[4]'s height to 1
1683 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1684 nodes[4].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![] }, 1);
1687 assert_eq!(nodes[3].node.latest_block_height.load(Ordering::Acquire), 1);
1688 assert_eq!(nodes[4].node.latest_block_height.load(Ordering::Acquire), 1);
1689 // One pending HTLC to time out:
1690 let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
1691 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
1695 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1696 nodes[3].chain_monitor.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
1697 for i in 3..TEST_FINAL_CLTV + 2 + LATENCY_GRACE_PERIOD_BLOCKS + 1 {
1698 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1699 nodes[3].chain_monitor.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
1702 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
1704 // Claim the payment on nodes[4], giving it knowledge of the preimage
1705 claim_funds!(nodes[4], nodes[3], payment_preimage_2);
1707 header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1708 nodes[4].chain_monitor.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
1709 for i in 3..TEST_FINAL_CLTV + 2 - CLTV_CLAIM_BUFFER + 1 {
1710 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1711 nodes[4].chain_monitor.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
1714 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
1716 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1717 nodes[4].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, TEST_FINAL_CLTV - 5);
1719 check_preimage_claim(&nodes[4], &node_txn);
1721 get_announce_close_broadcast_events(&nodes, 3, 4);
1722 assert_eq!(nodes[3].node.list_channels().len(), 0);
1723 assert_eq!(nodes[4].node.list_channels().len(), 0);
1727 fn test_justice_tx() {
1728 // Test justice txn built on revoked HTLC-Success tx, against both sides
1730 let mut alice_config = UserConfig::new();
1731 alice_config.channel_options.announced_channel = true;
1732 alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
1733 alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
1734 let mut bob_config = UserConfig::new();
1735 bob_config.channel_options.announced_channel = true;
1736 bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
1737 bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
1738 let nodes = create_network(2, &[Some(alice_config), Some(bob_config)]);
1739 // Create some new channels:
1740 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
1742 // A pending HTLC which will be revoked:
1743 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
1744 // Get the will-be-revoked local txn from nodes[0]
1745 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
1746 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
1747 assert_eq!(revoked_local_txn[0].input.len(), 1);
1748 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
1749 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
1750 assert_eq!(revoked_local_txn[1].input.len(), 1);
1751 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
1752 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
1753 // Revoke the old state
1754 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
1757 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1758 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
1760 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
1761 assert_eq!(node_txn.len(), 3);
1762 assert_eq!(node_txn.pop().unwrap(), node_txn[0]); // An outpoint registration will result in a 2nd block_connected
1763 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
1765 check_spends!(node_txn[0], revoked_local_txn[0].clone());
1766 node_txn.swap_remove(0);
1768 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
1770 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
1771 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
1772 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1773 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
1774 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone());
1776 get_announce_close_broadcast_events(&nodes, 0, 1);
1778 assert_eq!(nodes[0].node.list_channels().len(), 0);
1779 assert_eq!(nodes[1].node.list_channels().len(), 0);
1781 // We test justice_tx build by A on B's revoked HTLC-Success tx
1782 // Create some new channels:
1783 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
1785 // A pending HTLC which will be revoked:
1786 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
1787 // Get the will-be-revoked local txn from B
1788 let revoked_local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
1789 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
1790 assert_eq!(revoked_local_txn[0].input.len(), 1);
1791 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
1792 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
1793 // Revoke the old state
1794 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
1796 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1797 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
1799 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
1800 assert_eq!(node_txn.len(), 3);
1801 assert_eq!(node_txn.pop().unwrap(), node_txn[0]); // An outpoint registration will result in a 2nd block_connected
1802 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
1804 check_spends!(node_txn[0], revoked_local_txn[0].clone());
1805 node_txn.swap_remove(0);
1807 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
1809 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
1810 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
1811 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1812 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
1813 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone());
1815 get_announce_close_broadcast_events(&nodes, 0, 1);
1816 assert_eq!(nodes[0].node.list_channels().len(), 0);
1817 assert_eq!(nodes[1].node.list_channels().len(), 0);
1821 fn revoked_output_claim() {
1822 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
1823 // transaction is broadcast by its counterparty
1824 let nodes = create_network(2, &[None, None]);
1825 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
1826 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
1827 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
1828 assert_eq!(revoked_local_txn.len(), 1);
1829 // Only output is the full channel value back to nodes[0]:
1830 assert_eq!(revoked_local_txn[0].output.len(), 1);
1831 // Send a payment through, updating everyone's latest commitment txn
1832 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
1834 // Inform nodes[1] that nodes[0] broadcast a stale tx
1835 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1836 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
1837 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
1838 assert_eq!(node_txn.len(), 3); // nodes[1] will broadcast justice tx twice, and its own local state once
1840 assert_eq!(node_txn[0], node_txn[2]);
1842 check_spends!(node_txn[0], revoked_local_txn[0].clone());
1843 check_spends!(node_txn[1], chan_1.3.clone());
1845 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
1846 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
1847 get_announce_close_broadcast_events(&nodes, 0, 1);
1851 fn claim_htlc_outputs_shared_tx() {
1852 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
1853 let nodes = create_network(2, &[None, None]);
1855 // Create some new channel:
1856 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
1858 // Rebalance the network to generate htlc in the two directions
1859 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1860 // 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
1861 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
1862 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
1864 // Get the will-be-revoked local txn from node[0]
1865 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
1866 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
1867 assert_eq!(revoked_local_txn[0].input.len(), 1);
1868 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
1869 assert_eq!(revoked_local_txn[1].input.len(), 1);
1870 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
1871 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
1872 check_spends!(revoked_local_txn[1], revoked_local_txn[0].clone());
1874 //Revoke the old state
1875 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
1878 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1879 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
1880 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
1881 connect_blocks(&nodes[1].chain_monitor, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
1883 let events = nodes[1].node.get_and_clear_pending_events();
1884 assert_eq!(events.len(), 1);
1886 Event::PaymentFailed { payment_hash, .. } => {
1887 assert_eq!(payment_hash, payment_hash_2);
1889 _ => panic!("Unexpected event"),
1892 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
1893 assert_eq!(node_txn.len(), 4);
1895 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
1896 check_spends!(node_txn[0], revoked_local_txn[0].clone());
1898 assert_eq!(node_txn[0], node_txn[3]); // justice tx is duplicated due to block re-scanning
1900 let mut witness_lens = BTreeSet::new();
1901 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
1902 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
1903 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
1904 assert_eq!(witness_lens.len(), 3);
1905 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
1906 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
1907 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
1909 // Next nodes[1] broadcasts its current local tx state:
1910 assert_eq!(node_txn[1].input.len(), 1);
1911 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
1913 assert_eq!(node_txn[2].input.len(), 1);
1914 let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
1915 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
1916 assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
1917 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
1918 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
1920 get_announce_close_broadcast_events(&nodes, 0, 1);
1921 assert_eq!(nodes[0].node.list_channels().len(), 0);
1922 assert_eq!(nodes[1].node.list_channels().len(), 0);
1926 fn claim_htlc_outputs_single_tx() {
1927 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
1928 let nodes = create_network(2, &[None, None]);
1930 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
1932 // Rebalance the network to generate htlc in the two directions
1933 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1934 // 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
1935 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
1936 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
1937 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
1939 // Get the will-be-revoked local txn from node[0]
1940 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
1942 //Revoke the old state
1943 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
1946 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1947 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
1948 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
1949 connect_blocks(&nodes[1].chain_monitor, ANTI_REORG_DELAY - 1, 200, true, header.bitcoin_hash());
1951 let events = nodes[1].node.get_and_clear_pending_events();
1952 assert_eq!(events.len(), 1);
1954 Event::PaymentFailed { payment_hash, .. } => {
1955 assert_eq!(payment_hash, payment_hash_2);
1957 _ => panic!("Unexpected event"),
1960 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
1961 assert_eq!(node_txn.len(), 22); // ChannelManager : 2, ChannelMontitor: 8 (1 standard revoked output, 2 revocation htlc tx, 1 local commitment tx + 1 htlc timeout tx) * 2 (block-rescan) + 5 * (1 local commitment tx + 1 htlc timeout tx)
1963 assert_eq!(node_txn[0], node_txn[7]);
1964 assert_eq!(node_txn[1], node_txn[8]);
1965 assert_eq!(node_txn[2], node_txn[9]);
1966 assert_eq!(node_txn[3], node_txn[10]);
1967 assert_eq!(node_txn[4], node_txn[11]);
1968 assert_eq!(node_txn[3], node_txn[5]); //local commitment tx + htlc timeout tx broadcasted by ChannelManger
1969 assert_eq!(node_txn[4], node_txn[6]);
1972 if i % 2 == 0 { assert_eq!(node_txn[3], node_txn[i]); } else { assert_eq!(node_txn[4], node_txn[i]); }
1975 assert_eq!(node_txn[0].input.len(), 1);
1976 assert_eq!(node_txn[1].input.len(), 1);
1977 assert_eq!(node_txn[2].input.len(), 1);
1979 let mut revoked_tx_map = HashMap::new();
1980 revoked_tx_map.insert(revoked_local_txn[0].txid(), revoked_local_txn[0].clone());
1981 node_txn[0].verify(&revoked_tx_map).unwrap();
1982 node_txn[1].verify(&revoked_tx_map).unwrap();
1983 node_txn[2].verify(&revoked_tx_map).unwrap();
1985 let mut witness_lens = BTreeSet::new();
1986 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
1987 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
1988 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
1989 assert_eq!(witness_lens.len(), 3);
1990 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
1991 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
1992 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
1994 assert_eq!(node_txn[3].input.len(), 1);
1995 check_spends!(node_txn[3], chan_1.3.clone());
1997 assert_eq!(node_txn[4].input.len(), 1);
1998 let witness_script = node_txn[4].input[0].witness.last().unwrap();
1999 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2000 assert_eq!(node_txn[4].input[0].previous_output.txid, node_txn[3].txid());
2001 assert_ne!(node_txn[4].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
2002 assert_ne!(node_txn[4].input[0].previous_output.txid, node_txn[1].input[0].previous_output.txid);
2004 get_announce_close_broadcast_events(&nodes, 0, 1);
2005 assert_eq!(nodes[0].node.list_channels().len(), 0);
2006 assert_eq!(nodes[1].node.list_channels().len(), 0);
2010 fn test_htlc_on_chain_success() {
2011 // Test that in case of a unilateral close onchain, we detect the state of output thanks to
2012 // ChainWatchInterface and pass the preimage backward accordingly. So here we test that ChannelManager is
2013 // broadcasting the right event to other nodes in payment path.
2014 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2015 // A --------------------> B ----------------------> C (preimage)
2016 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2017 // commitment transaction was broadcast.
2018 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2020 // B should be able to claim via preimage if A then broadcasts its local tx.
2021 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2022 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2023 // PaymentSent event).
2025 let nodes = create_network(3, &[None, None, None]);
2027 // Create some initial channels
2028 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
2029 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new());
2031 // Rebalance the network a bit by relaying one payment through all the channels...
2032 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2033 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2035 let (our_payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2036 let (our_payment_preimage_2, _payment_hash_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2037 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2039 // Broadcast legit commitment tx from C on B's chain
2040 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2041 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
2042 assert_eq!(commitment_tx.len(), 1);
2043 check_spends!(commitment_tx[0], chan_2.3.clone());
2044 nodes[2].node.claim_funds(our_payment_preimage);
2045 nodes[2].node.claim_funds(our_payment_preimage_2);
2046 check_added_monitors!(nodes[2], 2);
2047 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2048 assert!(updates.update_add_htlcs.is_empty());
2049 assert!(updates.update_fail_htlcs.is_empty());
2050 assert!(updates.update_fail_malformed_htlcs.is_empty());
2051 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2053 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2054 check_closed_broadcast!(nodes[2]);
2055 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx), ChannelMonitor : 4 (2*2 * HTLC-Success tx)
2056 assert_eq!(node_txn.len(), 5);
2057 assert_eq!(node_txn[0], node_txn[3]);
2058 assert_eq!(node_txn[1], node_txn[4]);
2059 assert_eq!(node_txn[2], commitment_tx[0]);
2060 check_spends!(node_txn[0], commitment_tx[0].clone());
2061 check_spends!(node_txn[1], commitment_tx[0].clone());
2062 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2063 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2064 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2065 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2066 assert_eq!(node_txn[0].lock_time, 0);
2067 assert_eq!(node_txn[1].lock_time, 0);
2069 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2070 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: node_txn}, 1);
2071 let events = nodes[1].node.get_and_clear_pending_msg_events();
2073 let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
2074 assert_eq!(added_monitors.len(), 2);
2075 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2076 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2077 added_monitors.clear();
2079 assert_eq!(events.len(), 2);
2081 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2082 _ => panic!("Unexpected event"),
2085 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, .. } } => {
2086 assert!(update_add_htlcs.is_empty());
2087 assert!(update_fail_htlcs.is_empty());
2088 assert_eq!(update_fulfill_htlcs.len(), 1);
2089 assert!(update_fail_malformed_htlcs.is_empty());
2090 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2092 _ => panic!("Unexpected event"),
2094 macro_rules! check_tx_local_broadcast {
2095 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2096 // ChannelManager : 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor : 2 (timeout tx) * 2 (block-rescan)
2097 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2098 assert_eq!(node_txn.len(), 7);
2099 assert_eq!(node_txn[0], node_txn[5]);
2100 assert_eq!(node_txn[1], node_txn[6]);
2101 check_spends!(node_txn[0], $commitment_tx.clone());
2102 check_spends!(node_txn[1], $commitment_tx.clone());
2103 assert_ne!(node_txn[0].lock_time, 0);
2104 assert_ne!(node_txn[1].lock_time, 0);
2106 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2107 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2108 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2109 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2111 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2112 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2113 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2114 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2116 check_spends!(node_txn[2], $chan_tx.clone());
2117 check_spends!(node_txn[3], node_txn[2].clone());
2118 check_spends!(node_txn[4], node_txn[2].clone());
2119 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), 71);
2120 assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2121 assert_eq!(node_txn[4].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2122 assert!(node_txn[3].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2123 assert!(node_txn[4].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2124 assert_ne!(node_txn[3].lock_time, 0);
2125 assert_ne!(node_txn[4].lock_time, 0);
2129 // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2130 // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2131 // timeout-claim of the output that nodes[2] just claimed via success.
2132 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2134 // Broadcast legit commitment tx from A on B's chain
2135 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2136 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
2137 check_spends!(commitment_tx[0], chan_1.3.clone());
2138 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2139 check_closed_broadcast!(nodes[1]);
2140 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx), ChannelMonitor : 1 (HTLC-Success) * 2 (block-rescan)
2141 assert_eq!(node_txn.len(), 3);
2142 assert_eq!(node_txn[0], node_txn[2]);
2143 check_spends!(node_txn[0], commitment_tx[0].clone());
2144 assert_eq!(node_txn[0].input.len(), 2);
2145 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2146 assert_eq!(node_txn[0].input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2147 assert_eq!(node_txn[0].lock_time, 0);
2148 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2149 check_spends!(node_txn[1], chan_1.3.clone());
2150 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
2151 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2152 // we already checked the same situation with A.
2154 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2155 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone()] }, 1);
2156 check_closed_broadcast!(nodes[0]);
2157 let events = nodes[0].node.get_and_clear_pending_events();
2158 assert_eq!(events.len(), 2);
2159 let mut first_claimed = false;
2160 for event in events {
2162 Event::PaymentSent { payment_preimage } => {
2163 if payment_preimage == our_payment_preimage {
2164 assert!(!first_claimed);
2165 first_claimed = true;
2167 assert_eq!(payment_preimage, our_payment_preimage_2);
2170 _ => panic!("Unexpected event"),
2173 check_tx_local_broadcast!(nodes[0], true, commitment_tx[0], chan_1.3);
2177 fn test_htlc_on_chain_timeout() {
2178 // Test that in case of a unilateral close onchain, we detect the state of output thanks to
2179 // ChainWatchInterface and timeout the HTLC backward accordingly. So here we test that ChannelManager is
2180 // broadcasting the right event to other nodes in payment path.
2181 // A ------------------> B ----------------------> C (timeout)
2182 // B's commitment tx C's commitment tx
2184 // B's HTLC timeout tx B's timeout tx
2186 let nodes = create_network(3, &[None, None, None]);
2188 // Create some intial channels
2189 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
2190 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new());
2192 // Rebalance the network a bit by relaying one payment thorugh all the channels...
2193 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2194 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2196 let (_payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2197 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2199 // Broadcast legit commitment tx from C on B's chain
2200 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
2201 check_spends!(commitment_tx[0], chan_2.3.clone());
2202 nodes[2].node.fail_htlc_backwards(&payment_hash);
2203 check_added_monitors!(nodes[2], 0);
2204 expect_pending_htlcs_forwardable!(nodes[2]);
2205 check_added_monitors!(nodes[2], 1);
2207 let events = nodes[2].node.get_and_clear_pending_msg_events();
2208 assert_eq!(events.len(), 1);
2210 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, .. } } => {
2211 assert!(update_add_htlcs.is_empty());
2212 assert!(!update_fail_htlcs.is_empty());
2213 assert!(update_fulfill_htlcs.is_empty());
2214 assert!(update_fail_malformed_htlcs.is_empty());
2215 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2217 _ => panic!("Unexpected event"),
2219 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2220 check_closed_broadcast!(nodes[2]);
2221 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2222 assert_eq!(node_txn.len(), 1);
2223 check_spends!(node_txn[0], chan_2.3.clone());
2224 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2226 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2227 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2228 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
2231 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2232 assert_eq!(node_txn.len(), 8); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 6 (HTLC-Timeout tx, commitment tx, timeout tx) * 2 (block-rescan)
2233 assert_eq!(node_txn[0], node_txn[5]);
2234 assert_eq!(node_txn[1], node_txn[6]);
2235 assert_eq!(node_txn[2], node_txn[7]);
2236 check_spends!(node_txn[0], commitment_tx[0].clone());
2237 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2238 check_spends!(node_txn[1], chan_2.3.clone());
2239 check_spends!(node_txn[2], node_txn[1].clone());
2240 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
2241 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2242 check_spends!(node_txn[3], chan_2.3.clone());
2243 check_spends!(node_txn[4], node_txn[3].clone());
2244 assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
2245 assert_eq!(node_txn[4].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2246 timeout_tx = node_txn[0].clone();
2250 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![timeout_tx]}, 1);
2251 connect_blocks(&nodes[1].chain_monitor, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
2252 check_added_monitors!(nodes[1], 0);
2253 check_closed_broadcast!(nodes[1]);
2255 expect_pending_htlcs_forwardable!(nodes[1]);
2256 check_added_monitors!(nodes[1], 1);
2257 let events = nodes[1].node.get_and_clear_pending_msg_events();
2258 assert_eq!(events.len(), 1);
2260 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, .. } } => {
2261 assert!(update_add_htlcs.is_empty());
2262 assert!(!update_fail_htlcs.is_empty());
2263 assert!(update_fulfill_htlcs.is_empty());
2264 assert!(update_fail_malformed_htlcs.is_empty());
2265 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2267 _ => panic!("Unexpected event"),
2269 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
2270 assert_eq!(node_txn.len(), 0);
2272 // Broadcast legit commitment tx from B on A's chain
2273 let commitment_tx = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
2274 check_spends!(commitment_tx[0], chan_1.3.clone());
2276 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
2277 check_closed_broadcast!(nodes[0]);
2278 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (timeout tx) * 2 block-rescan
2279 assert_eq!(node_txn.len(), 4);
2280 assert_eq!(node_txn[0], node_txn[3]);
2281 check_spends!(node_txn[0], commitment_tx[0].clone());
2282 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2283 check_spends!(node_txn[1], chan_1.3.clone());
2284 check_spends!(node_txn[2], node_txn[1].clone());
2285 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
2286 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2290 fn test_simple_commitment_revoked_fail_backward() {
2291 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
2292 // and fail backward accordingly.
2294 let nodes = create_network(3, &[None, None, None]);
2296 // Create some initial channels
2297 create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
2298 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new());
2300 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2301 // Get the will-be-revoked local txn from nodes[2]
2302 let revoked_local_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
2303 // Revoke the old state
2304 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
2306 route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2308 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2309 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2310 connect_blocks(&nodes[1].chain_monitor, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
2311 check_added_monitors!(nodes[1], 0);
2312 check_closed_broadcast!(nodes[1]);
2314 expect_pending_htlcs_forwardable!(nodes[1]);
2315 check_added_monitors!(nodes[1], 1);
2316 let events = nodes[1].node.get_and_clear_pending_msg_events();
2317 assert_eq!(events.len(), 1);
2319 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, .. } } => {
2320 assert!(update_add_htlcs.is_empty());
2321 assert_eq!(update_fail_htlcs.len(), 1);
2322 assert!(update_fulfill_htlcs.is_empty());
2323 assert!(update_fail_malformed_htlcs.is_empty());
2324 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2326 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]).unwrap();
2327 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
2329 let events = nodes[0].node.get_and_clear_pending_msg_events();
2330 assert_eq!(events.len(), 1);
2332 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
2333 _ => panic!("Unexpected event"),
2335 let events = nodes[0].node.get_and_clear_pending_events();
2336 assert_eq!(events.len(), 1);
2338 Event::PaymentFailed { .. } => {},
2339 _ => panic!("Unexpected event"),
2342 _ => panic!("Unexpected event"),
2346 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
2347 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
2348 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
2349 // commitment transaction anymore.
2350 // To do this, we have the peer which will broadcast a revoked commitment transaction send
2351 // a number of update_fail/commitment_signed updates without ever sending the RAA in
2352 // response to our commitment_signed. This is somewhat misbehavior-y, though not
2353 // technically disallowed and we should probably handle it reasonably.
2354 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
2355 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
2357 // * Once we move it out of our holding cell/add it, we will immediately include it in a
2358 // commitment_signed (implying it will be in the latest remote commitment transaction).
2359 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
2360 // and once they revoke the previous commitment transaction (allowing us to send a new
2361 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
2362 let mut nodes = create_network(3, &[None, None, None]);
2364 // Create some initial channels
2365 create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
2366 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new());
2368 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
2369 // Get the will-be-revoked local txn from nodes[2]
2370 let revoked_local_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
2371 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
2372 // Revoke the old state
2373 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
2375 let value = if use_dust {
2376 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
2377 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
2378 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().our_dust_limit_satoshis * 1000
2381 let (_, first_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2382 let (_, second_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2383 let (_, third_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2385 assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash));
2386 expect_pending_htlcs_forwardable!(nodes[2]);
2387 check_added_monitors!(nodes[2], 1);
2388 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2389 assert!(updates.update_add_htlcs.is_empty());
2390 assert!(updates.update_fulfill_htlcs.is_empty());
2391 assert!(updates.update_fail_malformed_htlcs.is_empty());
2392 assert_eq!(updates.update_fail_htlcs.len(), 1);
2393 assert!(updates.update_fee.is_none());
2394 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
2395 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
2396 // Drop the last RAA from 3 -> 2
2398 assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash));
2399 expect_pending_htlcs_forwardable!(nodes[2]);
2400 check_added_monitors!(nodes[2], 1);
2401 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2402 assert!(updates.update_add_htlcs.is_empty());
2403 assert!(updates.update_fulfill_htlcs.is_empty());
2404 assert!(updates.update_fail_malformed_htlcs.is_empty());
2405 assert_eq!(updates.update_fail_htlcs.len(), 1);
2406 assert!(updates.update_fee.is_none());
2407 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
2408 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed).unwrap();
2409 check_added_monitors!(nodes[1], 1);
2410 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
2411 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
2412 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
2413 check_added_monitors!(nodes[2], 1);
2415 assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash));
2416 expect_pending_htlcs_forwardable!(nodes[2]);
2417 check_added_monitors!(nodes[2], 1);
2418 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2419 assert!(updates.update_add_htlcs.is_empty());
2420 assert!(updates.update_fulfill_htlcs.is_empty());
2421 assert!(updates.update_fail_malformed_htlcs.is_empty());
2422 assert_eq!(updates.update_fail_htlcs.len(), 1);
2423 assert!(updates.update_fee.is_none());
2424 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
2425 // At this point first_payment_hash has dropped out of the latest two commitment
2426 // transactions that nodes[1] is tracking...
2427 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed).unwrap();
2428 check_added_monitors!(nodes[1], 1);
2429 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
2430 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
2431 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
2432 check_added_monitors!(nodes[2], 1);
2434 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
2435 // on nodes[2]'s RAA.
2436 let route = nodes[1].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
2437 let (_, fourth_payment_hash) = get_payment_preimage_hash!(nodes[0]);
2438 nodes[1].node.send_payment(route, fourth_payment_hash).unwrap();
2439 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2440 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2441 check_added_monitors!(nodes[1], 0);
2444 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa).unwrap();
2445 // One monitor for the new revocation preimage, no second on as we won't generate a new
2446 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
2447 check_added_monitors!(nodes[1], 1);
2448 let events = nodes[1].node.get_and_clear_pending_events();
2449 assert_eq!(events.len(), 1);
2451 Event::PendingHTLCsForwardable { .. } => { },
2452 _ => panic!("Unexpected event"),
2454 // Deliberately don't process the pending fail-back so they all fail back at once after
2455 // block connection just like the !deliver_bs_raa case
2458 let mut failed_htlcs = HashSet::new();
2459 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2461 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2462 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2463 connect_blocks(&nodes[1].chain_monitor, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
2465 let events = nodes[1].node.get_and_clear_pending_events();
2466 assert_eq!(events.len(), if deliver_bs_raa { 1 } else { 2 });
2468 Event::PaymentFailed { ref payment_hash, .. } => {
2469 assert_eq!(*payment_hash, fourth_payment_hash);
2471 _ => panic!("Unexpected event"),
2473 if !deliver_bs_raa {
2475 Event::PendingHTLCsForwardable { .. } => { },
2476 _ => panic!("Unexpected event"),
2479 nodes[1].node.process_pending_htlc_forwards();
2480 check_added_monitors!(nodes[1], 1);
2482 let events = nodes[1].node.get_and_clear_pending_msg_events();
2483 assert_eq!(events.len(), if deliver_bs_raa { 3 } else { 2 });
2484 match events[if deliver_bs_raa { 1 } else { 0 }] {
2485 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
2486 _ => panic!("Unexpected event"),
2490 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, .. } } => {
2491 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
2492 assert_eq!(update_add_htlcs.len(), 1);
2493 assert!(update_fulfill_htlcs.is_empty());
2494 assert!(update_fail_htlcs.is_empty());
2495 assert!(update_fail_malformed_htlcs.is_empty());
2497 _ => panic!("Unexpected event"),
2500 match events[if deliver_bs_raa { 2 } else { 1 }] {
2501 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, .. } } => {
2502 assert!(update_add_htlcs.is_empty());
2503 assert_eq!(update_fail_htlcs.len(), 3);
2504 assert!(update_fulfill_htlcs.is_empty());
2505 assert!(update_fail_malformed_htlcs.is_empty());
2506 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2508 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]).unwrap();
2509 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]).unwrap();
2510 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]).unwrap();
2512 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
2514 let events = nodes[0].node.get_and_clear_pending_msg_events();
2515 // If we delivered B's RAA we got an unknown preimage error, not something
2516 // that we should update our routing table for.
2517 assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 3 });
2518 for event in events {
2520 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
2521 _ => panic!("Unexpected event"),
2524 let events = nodes[0].node.get_and_clear_pending_events();
2525 assert_eq!(events.len(), 3);
2527 Event::PaymentFailed { ref payment_hash, .. } => {
2528 assert!(failed_htlcs.insert(payment_hash.0));
2530 _ => panic!("Unexpected event"),
2533 Event::PaymentFailed { ref payment_hash, .. } => {
2534 assert!(failed_htlcs.insert(payment_hash.0));
2536 _ => panic!("Unexpected event"),
2539 Event::PaymentFailed { ref payment_hash, .. } => {
2540 assert!(failed_htlcs.insert(payment_hash.0));
2542 _ => panic!("Unexpected event"),
2545 _ => panic!("Unexpected event"),
2548 assert!(failed_htlcs.contains(&first_payment_hash.0));
2549 assert!(failed_htlcs.contains(&second_payment_hash.0));
2550 assert!(failed_htlcs.contains(&third_payment_hash.0));
2554 fn test_commitment_revoked_fail_backward_exhaustive_a() {
2555 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
2556 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
2557 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
2558 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
2562 fn test_commitment_revoked_fail_backward_exhaustive_b() {
2563 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
2564 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
2565 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
2566 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
2570 fn test_htlc_ignore_latest_remote_commitment() {
2571 // Test that HTLC transactions spending the latest remote commitment transaction are simply
2572 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
2573 let nodes = create_network(2, &[None, None]);
2574 create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
2576 route_payment(&nodes[0], &[&nodes[1]], 10000000);
2577 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id);
2578 check_closed_broadcast!(nodes[0]);
2580 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2581 assert_eq!(node_txn.len(), 2);
2583 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2584 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&node_txn[0], &node_txn[1]], &[1; 2]);
2585 check_closed_broadcast!(nodes[1]);
2587 // Duplicate the block_connected call since this may happen due to other listeners
2588 // registering new transactions
2589 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&node_txn[0], &node_txn[1]], &[1; 2]);
2593 fn test_force_close_fail_back() {
2594 // Check which HTLCs are failed-backwards on channel force-closure
2595 let mut nodes = create_network(3, &[None, None, None]);
2596 create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
2597 create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new());
2599 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, 42).unwrap();
2601 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
2603 let mut payment_event = {
2604 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
2605 check_added_monitors!(nodes[0], 1);
2607 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2608 assert_eq!(events.len(), 1);
2609 SendEvent::from_event(events.remove(0))
2612 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
2613 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
2615 expect_pending_htlcs_forwardable!(nodes[1]);
2617 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
2618 assert_eq!(events_2.len(), 1);
2619 payment_event = SendEvent::from_event(events_2.remove(0));
2620 assert_eq!(payment_event.msgs.len(), 1);
2622 check_added_monitors!(nodes[1], 1);
2623 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
2624 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
2625 check_added_monitors!(nodes[2], 1);
2626 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2628 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
2629 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
2630 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
2632 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id);
2633 check_closed_broadcast!(nodes[2]);
2635 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
2636 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
2637 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
2638 // back to nodes[1] upon timeout otherwise.
2639 assert_eq!(node_txn.len(), 1);
2643 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2644 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&tx], &[1]);
2646 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
2647 check_closed_broadcast!(nodes[1]);
2649 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
2651 let mut monitors = nodes[2].chan_monitor.simple_monitor.monitors.lock().unwrap();
2652 monitors.get_mut(&OutPoint::new(Sha256dHash::from_slice(&payment_event.commitment_msg.channel_id[..]).unwrap(), 0)).unwrap()
2653 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage);
2655 nodes[2].chain_monitor.block_connected_checked(&header, 1, &[&tx], &[1]);
2656 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
2657 assert_eq!(node_txn.len(), 1);
2658 assert_eq!(node_txn[0].input.len(), 1);
2659 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
2660 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
2661 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
2663 check_spends!(node_txn[0], tx);
2667 fn test_unconf_chan() {
2668 // After creating a chan between nodes, we disconnect all blocks previously seen to force a channel close on nodes[0] side
2669 let nodes = create_network(2, &[None, None]);
2670 create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
2672 let channel_state = nodes[0].node.channel_state.lock().unwrap();
2673 assert_eq!(channel_state.by_id.len(), 1);
2674 assert_eq!(channel_state.short_to_id.len(), 1);
2675 mem::drop(channel_state);
2677 let mut headers = Vec::new();
2678 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2679 headers.push(header.clone());
2681 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2682 headers.push(header.clone());
2684 let mut height = 99;
2685 while !headers.is_empty() {
2686 nodes[0].node.block_disconnected(&headers.pop().unwrap(), height);
2689 check_closed_broadcast!(nodes[0]);
2690 let channel_state = nodes[0].node.channel_state.lock().unwrap();
2691 assert_eq!(channel_state.by_id.len(), 0);
2692 assert_eq!(channel_state.short_to_id.len(), 0);
2696 fn test_simple_peer_disconnect() {
2697 // Test that we can reconnect when there are no lost messages
2698 let nodes = create_network(3, &[None, None, None]);
2699 create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
2700 create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new());
2702 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
2703 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
2704 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
2706 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
2707 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
2708 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
2709 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
2711 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
2712 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
2713 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
2715 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
2716 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
2717 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
2718 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
2720 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
2721 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
2723 claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3);
2724 fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
2726 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
2728 let events = nodes[0].node.get_and_clear_pending_events();
2729 assert_eq!(events.len(), 2);
2731 Event::PaymentSent { payment_preimage } => {
2732 assert_eq!(payment_preimage, payment_preimage_3);
2734 _ => panic!("Unexpected event"),
2737 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
2738 assert_eq!(payment_hash, payment_hash_5);
2739 assert!(rejected_by_dest);
2741 _ => panic!("Unexpected event"),
2745 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
2746 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
2749 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
2750 // Test that we can reconnect when in-flight HTLC updates get dropped
2751 let mut nodes = create_network(2, &[None, None]);
2752 if messages_delivered == 0 {
2753 create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, LocalFeatures::new(), LocalFeatures::new());
2754 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
2756 create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
2759 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), Some(&nodes[0].node.list_usable_channels()), &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
2760 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
2762 let payment_event = {
2763 nodes[0].node.send_payment(route.clone(), payment_hash_1).unwrap();
2764 check_added_monitors!(nodes[0], 1);
2766 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2767 assert_eq!(events.len(), 1);
2768 SendEvent::from_event(events.remove(0))
2770 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
2772 if messages_delivered < 2 {
2773 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
2775 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
2776 if messages_delivered >= 3 {
2777 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
2778 check_added_monitors!(nodes[1], 1);
2779 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2781 if messages_delivered >= 4 {
2782 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
2783 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2784 check_added_monitors!(nodes[0], 1);
2786 if messages_delivered >= 5 {
2787 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed).unwrap();
2788 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2789 // No commitment_signed so get_event_msg's assert(len == 1) passes
2790 check_added_monitors!(nodes[0], 1);
2792 if messages_delivered >= 6 {
2793 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
2794 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2795 check_added_monitors!(nodes[1], 1);
2802 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
2803 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
2804 if messages_delivered < 3 {
2805 // Even if the funding_locked messages get exchanged, as long as nothing further was
2806 // received on either side, both sides will need to resend them.
2807 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
2808 } else if messages_delivered == 3 {
2809 // nodes[0] still wants its RAA + commitment_signed
2810 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
2811 } else if messages_delivered == 4 {
2812 // nodes[0] still wants its commitment_signed
2813 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
2814 } else if messages_delivered == 5 {
2815 // nodes[1] still wants its final RAA
2816 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
2817 } else if messages_delivered == 6 {
2818 // Everything was delivered...
2819 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
2822 let events_1 = nodes[1].node.get_and_clear_pending_events();
2823 assert_eq!(events_1.len(), 1);
2825 Event::PendingHTLCsForwardable { .. } => { },
2826 _ => panic!("Unexpected event"),
2829 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
2830 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
2831 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
2833 nodes[1].node.process_pending_htlc_forwards();
2835 let events_2 = nodes[1].node.get_and_clear_pending_events();
2836 assert_eq!(events_2.len(), 1);
2838 Event::PaymentReceived { ref payment_hash, amt } => {
2839 assert_eq!(payment_hash_1, *payment_hash);
2840 assert_eq!(amt, 1000000);
2842 _ => panic!("Unexpected event"),
2845 nodes[1].node.claim_funds(payment_preimage_1);
2846 check_added_monitors!(nodes[1], 1);
2848 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
2849 assert_eq!(events_3.len(), 1);
2850 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
2851 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
2852 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
2853 assert!(updates.update_add_htlcs.is_empty());
2854 assert!(updates.update_fail_htlcs.is_empty());
2855 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2856 assert!(updates.update_fail_malformed_htlcs.is_empty());
2857 assert!(updates.update_fee.is_none());
2858 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
2860 _ => panic!("Unexpected event"),
2863 if messages_delivered >= 1 {
2864 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc).unwrap();
2866 let events_4 = nodes[0].node.get_and_clear_pending_events();
2867 assert_eq!(events_4.len(), 1);
2869 Event::PaymentSent { ref payment_preimage } => {
2870 assert_eq!(payment_preimage_1, *payment_preimage);
2872 _ => panic!("Unexpected event"),
2875 if messages_delivered >= 2 {
2876 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
2877 check_added_monitors!(nodes[0], 1);
2878 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2880 if messages_delivered >= 3 {
2881 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
2882 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2883 check_added_monitors!(nodes[1], 1);
2885 if messages_delivered >= 4 {
2886 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed).unwrap();
2887 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2888 // No commitment_signed so get_event_msg's assert(len == 1) passes
2889 check_added_monitors!(nodes[1], 1);
2891 if messages_delivered >= 5 {
2892 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
2893 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2894 check_added_monitors!(nodes[0], 1);
2901 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
2902 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
2903 if messages_delivered < 2 {
2904 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
2905 //TODO: Deduplicate PaymentSent events, then enable this if:
2906 //if messages_delivered < 1 {
2907 let events_4 = nodes[0].node.get_and_clear_pending_events();
2908 assert_eq!(events_4.len(), 1);
2910 Event::PaymentSent { ref payment_preimage } => {
2911 assert_eq!(payment_preimage_1, *payment_preimage);
2913 _ => panic!("Unexpected event"),
2916 } else if messages_delivered == 2 {
2917 // nodes[0] still wants its RAA + commitment_signed
2918 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
2919 } else if messages_delivered == 3 {
2920 // nodes[0] still wants its commitment_signed
2921 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
2922 } else if messages_delivered == 4 {
2923 // nodes[1] still wants its final RAA
2924 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
2925 } else if messages_delivered == 5 {
2926 // Everything was delivered...
2927 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
2930 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
2931 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
2932 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
2934 // Channel should still work fine...
2935 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
2936 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
2940 fn test_drop_messages_peer_disconnect_a() {
2941 do_test_drop_messages_peer_disconnect(0);
2942 do_test_drop_messages_peer_disconnect(1);
2943 do_test_drop_messages_peer_disconnect(2);
2944 do_test_drop_messages_peer_disconnect(3);
2948 fn test_drop_messages_peer_disconnect_b() {
2949 do_test_drop_messages_peer_disconnect(4);
2950 do_test_drop_messages_peer_disconnect(5);
2951 do_test_drop_messages_peer_disconnect(6);
2955 fn test_funding_peer_disconnect() {
2956 // Test that we can lock in our funding tx while disconnected
2957 let nodes = create_network(2, &[None, None]);
2958 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, LocalFeatures::new(), LocalFeatures::new());
2960 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
2961 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
2963 confirm_transaction(&nodes[0].chain_monitor, &tx, tx.version);
2964 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
2965 assert_eq!(events_1.len(), 1);
2967 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
2968 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
2970 _ => panic!("Unexpected event"),
2973 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
2975 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
2976 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
2978 confirm_transaction(&nodes[1].chain_monitor, &tx, tx.version);
2979 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
2980 assert_eq!(events_2.len(), 2);
2982 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
2983 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
2985 _ => panic!("Unexpected event"),
2988 MessageSendEvent::SendAnnouncementSignatures { ref node_id, msg: _ } => {
2989 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
2991 _ => panic!("Unexpected event"),
2994 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
2996 // TODO: We shouldn't need to manually pass list_usable_chanels here once we support
2997 // rebroadcasting announcement_signatures upon reconnect.
2999 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), Some(&nodes[0].node.list_usable_channels()), &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
3000 let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
3001 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
3005 fn test_drop_messages_peer_disconnect_dual_htlc() {
3006 // Test that we can handle reconnecting when both sides of a channel have pending
3007 // commitment_updates when we disconnect.
3008 let mut nodes = create_network(2, &[None, None]);
3009 create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
3011 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3013 // Now try to send a second payment which will fail to send
3014 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
3015 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
3017 nodes[0].node.send_payment(route.clone(), payment_hash_2).unwrap();
3018 check_added_monitors!(nodes[0], 1);
3020 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3021 assert_eq!(events_1.len(), 1);
3023 MessageSendEvent::UpdateHTLCs { .. } => {},
3024 _ => panic!("Unexpected event"),
3027 assert!(nodes[1].node.claim_funds(payment_preimage_1));
3028 check_added_monitors!(nodes[1], 1);
3030 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3031 assert_eq!(events_2.len(), 1);
3033 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 } } => {
3034 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3035 assert!(update_add_htlcs.is_empty());
3036 assert_eq!(update_fulfill_htlcs.len(), 1);
3037 assert!(update_fail_htlcs.is_empty());
3038 assert!(update_fail_malformed_htlcs.is_empty());
3039 assert!(update_fee.is_none());
3041 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]).unwrap();
3042 let events_3 = nodes[0].node.get_and_clear_pending_events();
3043 assert_eq!(events_3.len(), 1);
3045 Event::PaymentSent { ref payment_preimage } => {
3046 assert_eq!(*payment_preimage, payment_preimage_1);
3048 _ => panic!("Unexpected event"),
3051 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed).unwrap();
3052 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3053 // No commitment_signed so get_event_msg's assert(len == 1) passes
3054 check_added_monitors!(nodes[0], 1);
3056 _ => panic!("Unexpected event"),
3059 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3060 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3062 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
3063 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3064 assert_eq!(reestablish_1.len(), 1);
3065 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
3066 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3067 assert_eq!(reestablish_2.len(), 1);
3069 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
3070 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3071 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
3072 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
3074 assert!(as_resp.0.is_none());
3075 assert!(bs_resp.0.is_none());
3077 assert!(bs_resp.1.is_none());
3078 assert!(bs_resp.2.is_none());
3080 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
3082 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
3083 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
3084 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
3085 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
3086 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
3087 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]).unwrap();
3088 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed).unwrap();
3089 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3090 // No commitment_signed so get_event_msg's assert(len == 1) passes
3091 check_added_monitors!(nodes[1], 1);
3093 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap()).unwrap();
3094 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3095 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
3096 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
3097 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
3098 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
3099 assert!(bs_second_commitment_signed.update_fee.is_none());
3100 check_added_monitors!(nodes[1], 1);
3102 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
3103 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3104 assert!(as_commitment_signed.update_add_htlcs.is_empty());
3105 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
3106 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
3107 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
3108 assert!(as_commitment_signed.update_fee.is_none());
3109 check_added_monitors!(nodes[0], 1);
3111 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed).unwrap();
3112 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3113 // No commitment_signed so get_event_msg's assert(len == 1) passes
3114 check_added_monitors!(nodes[0], 1);
3116 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed).unwrap();
3117 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3118 // No commitment_signed so get_event_msg's assert(len == 1) passes
3119 check_added_monitors!(nodes[1], 1);
3121 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
3122 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3123 check_added_monitors!(nodes[1], 1);
3125 expect_pending_htlcs_forwardable!(nodes[1]);
3127 let events_5 = nodes[1].node.get_and_clear_pending_events();
3128 assert_eq!(events_5.len(), 1);
3130 Event::PaymentReceived { ref payment_hash, amt: _ } => {
3131 assert_eq!(payment_hash_2, *payment_hash);
3133 _ => panic!("Unexpected event"),
3136 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack).unwrap();
3137 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3138 check_added_monitors!(nodes[0], 1);
3140 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3144 fn test_invalid_channel_announcement() {
3145 //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
3146 let secp_ctx = Secp256k1::new();
3147 let nodes = create_network(2, &[None, None]);
3149 let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1], LocalFeatures::new(), LocalFeatures::new());
3151 let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
3152 let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
3153 let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
3154 let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
3156 let _ = nodes[0].router.handle_htlc_fail_channel_update(&msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id : as_chan.get_short_channel_id().unwrap(), is_permanent: false } );
3158 let as_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &as_chan.get_local_keys().funding_key);
3159 let bs_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &bs_chan.get_local_keys().funding_key);
3161 let as_network_key = nodes[0].node.get_our_node_id();
3162 let bs_network_key = nodes[1].node.get_our_node_id();
3164 let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
3166 let mut chan_announcement;
3168 macro_rules! dummy_unsigned_msg {
3170 msgs::UnsignedChannelAnnouncement {
3171 features: msgs::GlobalFeatures::new(),
3172 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
3173 short_channel_id: as_chan.get_short_channel_id().unwrap(),
3174 node_id_1: if were_node_one { as_network_key } else { bs_network_key },
3175 node_id_2: if were_node_one { bs_network_key } else { as_network_key },
3176 bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
3177 bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
3178 excess_data: Vec::new(),
3183 macro_rules! sign_msg {
3184 ($unsigned_msg: expr) => {
3185 let msghash = Message::from_slice(&Sha256dHash::hash(&$unsigned_msg.encode()[..])[..]).unwrap();
3186 let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_local_keys().funding_key);
3187 let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_local_keys().funding_key);
3188 let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].keys_manager.get_node_secret());
3189 let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].keys_manager.get_node_secret());
3190 chan_announcement = msgs::ChannelAnnouncement {
3191 node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
3192 node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
3193 bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
3194 bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
3195 contents: $unsigned_msg
3200 let unsigned_msg = dummy_unsigned_msg!();
3201 sign_msg!(unsigned_msg);
3202 assert_eq!(nodes[0].router.handle_channel_announcement(&chan_announcement).unwrap(), true);
3203 let _ = nodes[0].router.handle_htlc_fail_channel_update(&msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id : as_chan.get_short_channel_id().unwrap(), is_permanent: false } );
3205 // Configured with Network::Testnet
3206 let mut unsigned_msg = dummy_unsigned_msg!();
3207 unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.bitcoin_hash();
3208 sign_msg!(unsigned_msg);
3209 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
3211 let mut unsigned_msg = dummy_unsigned_msg!();
3212 unsigned_msg.chain_hash = Sha256dHash::hash(&[1,2,3,4,5,6,7,8,9]);
3213 sign_msg!(unsigned_msg);
3214 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
3218 fn test_no_txn_manager_serialize_deserialize() {
3219 let mut nodes = create_network(2, &[None, None]);
3221 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, LocalFeatures::new(), LocalFeatures::new());
3223 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3225 let nodes_0_serialized = nodes[0].node.encode();
3226 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3227 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
3229 nodes[0].chan_monitor = Arc::new(test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), Arc::new(test_utils::TestLogger::new()), Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 })));
3230 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
3231 let (_, chan_0_monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
3232 assert!(chan_0_monitor_read.is_empty());
3234 let mut nodes_0_read = &nodes_0_serialized[..];
3235 let config = UserConfig::new();
3236 let keys_manager = Arc::new(test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
3237 let (_, nodes_0_deserialized) = {
3238 let mut channel_monitors = HashMap::new();
3239 channel_monitors.insert(chan_0_monitor.get_funding_txo().unwrap(), &chan_0_monitor);
3240 <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3241 default_config: config,
3243 fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
3244 monitor: nodes[0].chan_monitor.clone(),
3245 chain_monitor: nodes[0].chain_monitor.clone(),
3246 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3247 logger: Arc::new(test_utils::TestLogger::new()),
3248 channel_monitors: &channel_monitors,
3251 assert!(nodes_0_read.is_empty());
3253 assert!(nodes[0].chan_monitor.add_update_monitor(chan_0_monitor.get_funding_txo().unwrap(), chan_0_monitor).is_ok());
3254 nodes[0].node = Arc::new(nodes_0_deserialized);
3255 let nodes_0_as_listener: Arc<ChainListener> = nodes[0].node.clone();
3256 nodes[0].chain_monitor.register_listener(Arc::downgrade(&nodes_0_as_listener));
3257 assert_eq!(nodes[0].node.list_channels().len(), 1);
3258 check_added_monitors!(nodes[0], 1);
3260 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
3261 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3262 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
3263 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3265 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
3266 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3267 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
3268 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3270 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
3271 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
3272 for node in nodes.iter() {
3273 assert!(node.router.handle_channel_announcement(&announcement).unwrap());
3274 node.router.handle_channel_update(&as_update).unwrap();
3275 node.router.handle_channel_update(&bs_update).unwrap();
3278 send_payment(&nodes[0], &[&nodes[1]], 1000000);
3282 fn test_simple_manager_serialize_deserialize() {
3283 let mut nodes = create_network(2, &[None, None]);
3284 create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
3286 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3287 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3289 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3291 let nodes_0_serialized = nodes[0].node.encode();
3292 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3293 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
3295 nodes[0].chan_monitor = Arc::new(test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), Arc::new(test_utils::TestLogger::new()), Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 })));
3296 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
3297 let (_, chan_0_monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
3298 assert!(chan_0_monitor_read.is_empty());
3300 let mut nodes_0_read = &nodes_0_serialized[..];
3301 let keys_manager = Arc::new(test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
3302 let (_, nodes_0_deserialized) = {
3303 let mut channel_monitors = HashMap::new();
3304 channel_monitors.insert(chan_0_monitor.get_funding_txo().unwrap(), &chan_0_monitor);
3305 <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3306 default_config: UserConfig::new(),
3308 fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
3309 monitor: nodes[0].chan_monitor.clone(),
3310 chain_monitor: nodes[0].chain_monitor.clone(),
3311 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3312 logger: Arc::new(test_utils::TestLogger::new()),
3313 channel_monitors: &channel_monitors,
3316 assert!(nodes_0_read.is_empty());
3318 assert!(nodes[0].chan_monitor.add_update_monitor(chan_0_monitor.get_funding_txo().unwrap(), chan_0_monitor).is_ok());
3319 nodes[0].node = Arc::new(nodes_0_deserialized);
3320 check_added_monitors!(nodes[0], 1);
3322 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3324 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
3325 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
3329 fn test_manager_serialize_deserialize_inconsistent_monitor() {
3330 // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
3331 let mut nodes = create_network(4, &[None, None, None, None]);
3332 create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
3333 create_announced_chan_between_nodes(&nodes, 2, 0, LocalFeatures::new(), LocalFeatures::new());
3334 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, LocalFeatures::new(), LocalFeatures::new());
3336 let (our_payment_preimage, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
3338 // Serialize the ChannelManager here, but the monitor we keep up-to-date
3339 let nodes_0_serialized = nodes[0].node.encode();
3341 route_payment(&nodes[0], &[&nodes[3]], 1000000);
3342 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3343 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3344 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3346 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
3348 let mut node_0_monitors_serialized = Vec::new();
3349 for monitor in nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter() {
3350 let mut writer = test_utils::TestVecWriter(Vec::new());
3351 monitor.1.write_for_disk(&mut writer).unwrap();
3352 node_0_monitors_serialized.push(writer.0);
3355 nodes[0].chan_monitor = Arc::new(test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), Arc::new(test_utils::TestLogger::new()), Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 })));
3356 let mut node_0_monitors = Vec::new();
3357 for serialized in node_0_monitors_serialized.iter() {
3358 let mut read = &serialized[..];
3359 let (_, monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut read, Arc::new(test_utils::TestLogger::new())).unwrap();
3360 assert!(read.is_empty());
3361 node_0_monitors.push(monitor);
3364 let mut nodes_0_read = &nodes_0_serialized[..];
3365 let keys_manager = Arc::new(test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
3366 let (_, nodes_0_deserialized) = <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3367 default_config: UserConfig::new(),
3369 fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
3370 monitor: nodes[0].chan_monitor.clone(),
3371 chain_monitor: nodes[0].chain_monitor.clone(),
3372 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3373 logger: Arc::new(test_utils::TestLogger::new()),
3374 channel_monitors: &node_0_monitors.iter().map(|monitor| { (monitor.get_funding_txo().unwrap(), monitor) }).collect(),
3376 assert!(nodes_0_read.is_empty());
3378 { // Channel close should result in a commitment tx and an HTLC tx
3379 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3380 assert_eq!(txn.len(), 2);
3381 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
3382 assert_eq!(txn[1].input[0].previous_output.txid, txn[0].txid());
3385 for monitor in node_0_monitors.drain(..) {
3386 assert!(nodes[0].chan_monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor).is_ok());
3387 check_added_monitors!(nodes[0], 1);
3389 nodes[0].node = Arc::new(nodes_0_deserialized);
3391 // nodes[1] and nodes[2] have no lost state with nodes[0]...
3392 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3393 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3394 //... and we can even still claim the payment!
3395 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
3397 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id());
3398 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
3399 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id());
3400 if let Err(msgs::HandleError { action: Some(msgs::ErrorAction::SendErrorMessage { msg }), .. }) = nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish) {
3401 assert_eq!(msg.channel_id, channel_id);
3402 } else { panic!("Unexpected result"); }
3405 macro_rules! check_spendable_outputs {
3406 ($node: expr, $der_idx: expr) => {
3408 let events = $node.chan_monitor.simple_monitor.get_and_clear_pending_events();
3409 let mut txn = Vec::new();
3410 for event in events {
3412 Event::SpendableOutputs { ref outputs } => {
3413 for outp in outputs {
3415 SpendableOutputDescriptor::DynamicOutputP2WPKH { ref outpoint, ref key, ref output } => {
3417 previous_output: outpoint.clone(),
3418 script_sig: Script::new(),
3420 witness: Vec::new(),
3423 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
3424 value: output.value,
3426 let mut spend_tx = Transaction {
3432 let secp_ctx = Secp256k1::new();
3433 let remotepubkey = PublicKey::from_secret_key(&secp_ctx, &key);
3434 let witness_script = Address::p2pkh(&::bitcoin::PublicKey{compressed: true, key: remotepubkey}, Network::Testnet).script_pubkey();
3435 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
3436 let remotesig = secp_ctx.sign(&sighash, key);
3437 spend_tx.input[0].witness.push(remotesig.serialize_der().to_vec());
3438 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
3439 spend_tx.input[0].witness.push(remotepubkey.serialize().to_vec());
3442 SpendableOutputDescriptor::DynamicOutputP2WSH { ref outpoint, ref key, ref witness_script, ref to_self_delay, ref output } => {
3444 previous_output: outpoint.clone(),
3445 script_sig: Script::new(),
3446 sequence: *to_self_delay as u32,
3447 witness: Vec::new(),
3450 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
3451 value: output.value,
3453 let mut spend_tx = Transaction {
3459 let secp_ctx = Secp256k1::new();
3460 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], witness_script, output.value)[..]).unwrap();
3461 let local_delaysig = secp_ctx.sign(&sighash, key);
3462 spend_tx.input[0].witness.push(local_delaysig.serialize_der().to_vec());
3463 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
3464 spend_tx.input[0].witness.push(vec!(0));
3465 spend_tx.input[0].witness.push(witness_script.clone().into_bytes());
3468 SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
3469 let secp_ctx = Secp256k1::new();
3471 previous_output: outpoint.clone(),
3472 script_sig: Script::new(),
3474 witness: Vec::new(),
3477 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
3478 value: output.value,
3480 let mut spend_tx = Transaction {
3484 output: vec![outp.clone()],
3487 match ExtendedPrivKey::new_master(Network::Testnet, &$node.node_seed) {
3489 match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx($der_idx).expect("key space exhausted")) {
3491 Err(_) => panic!("Your RNG is busted"),
3494 Err(_) => panic!("Your rng is busted"),
3497 let pubkey = ExtendedPubKey::from_private(&secp_ctx, &secret).public_key;
3498 let witness_script = Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
3499 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
3500 let sig = secp_ctx.sign(&sighash, &secret.private_key.key);
3501 spend_tx.input[0].witness.push(sig.serialize_der().to_vec());
3502 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
3503 spend_tx.input[0].witness.push(pubkey.key.serialize().to_vec());
3509 _ => panic!("Unexpected event"),
3518 fn test_claim_sizeable_push_msat() {
3519 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
3520 let nodes = create_network(2, &[None, None]);
3522 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, LocalFeatures::new(), LocalFeatures::new());
3523 nodes[1].node.force_close_channel(&chan.2);
3524 check_closed_broadcast!(nodes[1]);
3525 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3526 assert_eq!(node_txn.len(), 1);
3527 check_spends!(node_txn[0], chan.3.clone());
3528 assert_eq!(node_txn[0].output.len(), 2); // We can't force trimming of to_remote output as channel_reserve_satoshis block us to do so at channel opening
3530 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3531 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
3532 let spend_txn = check_spendable_outputs!(nodes[1], 1);
3533 assert_eq!(spend_txn.len(), 1);
3534 check_spends!(spend_txn[0], node_txn[0].clone());
3538 fn test_claim_on_remote_sizeable_push_msat() {
3539 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
3540 // to_remote output is encumbered by a P2WPKH
3542 let nodes = create_network(2, &[None, None]);
3544 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, LocalFeatures::new(), LocalFeatures::new());
3545 nodes[0].node.force_close_channel(&chan.2);
3546 check_closed_broadcast!(nodes[0]);
3548 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3549 assert_eq!(node_txn.len(), 1);
3550 check_spends!(node_txn[0], chan.3.clone());
3551 assert_eq!(node_txn[0].output.len(), 2); // We can't force trimming of to_remote output as channel_reserve_satoshis block us to do so at channel opening
3553 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3554 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
3555 check_closed_broadcast!(nodes[1]);
3556 let spend_txn = check_spendable_outputs!(nodes[1], 1);
3557 assert_eq!(spend_txn.len(), 2);
3558 assert_eq!(spend_txn[0], spend_txn[1]);
3559 check_spends!(spend_txn[0], node_txn[0].clone());
3563 fn test_claim_on_remote_revoked_sizeable_push_msat() {
3564 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
3565 // to_remote output is encumbered by a P2WPKH
3567 let nodes = create_network(2, &[None, None]);
3569 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, LocalFeatures::new(), LocalFeatures::new());
3570 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
3571 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn.clone();
3572 assert_eq!(revoked_local_txn[0].input.len(), 1);
3573 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
3575 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
3576 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3577 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3578 check_closed_broadcast!(nodes[1]);
3580 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3581 let spend_txn = check_spendable_outputs!(nodes[1], 1);
3582 assert_eq!(spend_txn.len(), 4);
3583 assert_eq!(spend_txn[0], spend_txn[2]); // to_remote output on revoked remote commitment_tx
3584 check_spends!(spend_txn[0], revoked_local_txn[0].clone());
3585 assert_eq!(spend_txn[1], spend_txn[3]); // to_local output on local commitment tx
3586 check_spends!(spend_txn[1], node_txn[0].clone());
3590 fn test_static_spendable_outputs_preimage_tx() {
3591 let nodes = create_network(2, &[None, None]);
3593 // Create some initial channels
3594 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
3596 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
3598 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
3599 assert_eq!(commitment_tx[0].input.len(), 1);
3600 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
3602 // Settle A's commitment tx on B's chain
3603 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3604 assert!(nodes[1].node.claim_funds(payment_preimage));
3605 check_added_monitors!(nodes[1], 1);
3606 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()] }, 1);
3607 let events = nodes[1].node.get_and_clear_pending_msg_events();
3609 MessageSendEvent::UpdateHTLCs { .. } => {},
3610 _ => panic!("Unexpected event"),
3613 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
3614 _ => panic!("Unexepected event"),
3617 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
3618 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 1 (local commitment tx), ChannelMonitor: 2 (1 preimage tx) * 2 (block-rescan)
3619 check_spends!(node_txn[0], commitment_tx[0].clone());
3620 assert_eq!(node_txn[0], node_txn[2]);
3621 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3622 check_spends!(node_txn[1], chan_1.3.clone());
3624 let spend_txn = check_spendable_outputs!(nodes[1], 1); // , 0, 0, 1, 1);
3625 assert_eq!(spend_txn.len(), 2);
3626 assert_eq!(spend_txn[0], spend_txn[1]);
3627 check_spends!(spend_txn[0], node_txn[0].clone());
3631 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
3632 let nodes = create_network(2, &[None, None]);
3634 // Create some initial channels
3635 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
3637 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
3638 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
3639 assert_eq!(revoked_local_txn[0].input.len(), 1);
3640 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
3642 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
3644 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3645 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3646 check_closed_broadcast!(nodes[1]);
3648 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3649 assert_eq!(node_txn.len(), 3);
3650 assert_eq!(node_txn.pop().unwrap(), node_txn[0]);
3651 assert_eq!(node_txn[0].input.len(), 2);
3652 check_spends!(node_txn[0], revoked_local_txn[0].clone());
3654 let spend_txn = check_spendable_outputs!(nodes[1], 1);
3655 assert_eq!(spend_txn.len(), 2);
3656 assert_eq!(spend_txn[0], spend_txn[1]);
3657 check_spends!(spend_txn[0], node_txn[0].clone());
3661 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
3662 let nodes = create_network(2, &[None, None]);
3664 // Create some initial channels
3665 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
3667 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
3668 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
3669 assert_eq!(revoked_local_txn[0].input.len(), 1);
3670 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
3672 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
3674 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3675 // A will generate HTLC-Timeout from revoked commitment tx
3676 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3677 check_closed_broadcast!(nodes[0]);
3679 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3680 assert_eq!(revoked_htlc_txn.len(), 3);
3681 assert_eq!(revoked_htlc_txn[0], revoked_htlc_txn[2]);
3682 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
3683 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3684 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0].clone());
3685 check_spends!(revoked_htlc_txn[1], chan_1.3.clone());
3687 // B will generate justice tx from A's revoked commitment/HTLC tx
3688 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
3689 check_closed_broadcast!(nodes[1]);
3691 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3692 assert_eq!(node_txn.len(), 4);
3693 assert_eq!(node_txn[3].input.len(), 1);
3694 check_spends!(node_txn[3], revoked_htlc_txn[0].clone());
3696 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
3697 let spend_txn = check_spendable_outputs!(nodes[1], 1);
3698 assert_eq!(spend_txn.len(), 3);
3699 assert_eq!(spend_txn[0], spend_txn[1]);
3700 check_spends!(spend_txn[0], node_txn[0].clone());
3701 check_spends!(spend_txn[2], node_txn[3].clone());
3705 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
3706 let nodes = create_network(2, &[None, None]);
3708 // Create some initial channels
3709 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
3711 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
3712 let revoked_local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
3713 assert_eq!(revoked_local_txn[0].input.len(), 1);
3714 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
3716 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
3718 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3719 // B will generate HTLC-Success from revoked commitment tx
3720 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3721 check_closed_broadcast!(nodes[1]);
3722 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3724 assert_eq!(revoked_htlc_txn.len(), 3);
3725 assert_eq!(revoked_htlc_txn[0], revoked_htlc_txn[2]);
3726 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
3727 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3728 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0].clone());
3730 // A will generate justice tx from B's revoked commitment/HTLC tx
3731 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
3732 check_closed_broadcast!(nodes[0]);
3734 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3735 assert_eq!(node_txn.len(), 4);
3736 assert_eq!(node_txn[3].input.len(), 1);
3737 check_spends!(node_txn[3], revoked_htlc_txn[0].clone());
3739 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
3740 let spend_txn = check_spendable_outputs!(nodes[0], 1);
3741 assert_eq!(spend_txn.len(), 5);
3742 assert_eq!(spend_txn[0], spend_txn[2]);
3743 assert_eq!(spend_txn[1], spend_txn[3]);
3744 check_spends!(spend_txn[0], revoked_local_txn[0].clone()); // spending to_remote output from revoked local tx
3745 check_spends!(spend_txn[1], node_txn[2].clone()); // spending justice tx output from revoked local tx htlc received output
3746 check_spends!(spend_txn[4], node_txn[3].clone()); // spending justice tx output on htlc success tx
3750 fn test_onchain_to_onchain_claim() {
3751 // Test that in case of channel closure, we detect the state of output thanks to
3752 // ChainWatchInterface and claim HTLC on downstream peer's remote commitment tx.
3753 // First, have C claim an HTLC against its own latest commitment transaction.
3754 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
3756 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
3759 let nodes = create_network(3, &[None, None, None]);
3761 // Create some initial channels
3762 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
3763 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new());
3765 // Rebalance the network a bit by relaying one payment through all the channels ...
3766 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
3767 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
3769 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
3770 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
3771 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
3772 check_spends!(commitment_tx[0], chan_2.3.clone());
3773 nodes[2].node.claim_funds(payment_preimage);
3774 check_added_monitors!(nodes[2], 1);
3775 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3776 assert!(updates.update_add_htlcs.is_empty());
3777 assert!(updates.update_fail_htlcs.is_empty());
3778 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3779 assert!(updates.update_fail_malformed_htlcs.is_empty());
3781 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
3782 check_closed_broadcast!(nodes[2]);
3784 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
3785 assert_eq!(c_txn.len(), 3);
3786 assert_eq!(c_txn[0], c_txn[2]);
3787 assert_eq!(commitment_tx[0], c_txn[1]);
3788 check_spends!(c_txn[1], chan_2.3.clone());
3789 check_spends!(c_txn[2], c_txn[1].clone());
3790 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
3791 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3792 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
3793 assert_eq!(c_txn[0].lock_time, 0); // Success tx
3795 // 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
3796 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]}, 1);
3798 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3799 assert_eq!(b_txn.len(), 4);
3800 assert_eq!(b_txn[0], b_txn[3]);
3801 check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager
3802 check_spends!(b_txn[2], b_txn[1].clone()); // HTLC-Timeout on B local commitment tx, issued by ChannelManager
3803 assert_eq!(b_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3804 assert!(b_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
3805 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
3806 check_spends!(b_txn[0], c_txn[1].clone()); // timeout tx on C remote commitment tx, issued by ChannelMonitor, * 2 due to block rescan
3807 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3808 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
3809 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
3812 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
3813 check_added_monitors!(nodes[1], 1);
3814 match msg_events[0] {
3815 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
3816 _ => panic!("Unexpected event"),
3818 match msg_events[1] {
3819 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, .. } } => {
3820 assert!(update_add_htlcs.is_empty());
3821 assert!(update_fail_htlcs.is_empty());
3822 assert_eq!(update_fulfill_htlcs.len(), 1);
3823 assert!(update_fail_malformed_htlcs.is_empty());
3824 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3826 _ => panic!("Unexpected event"),
3828 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
3829 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
3830 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
3831 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3832 assert_eq!(b_txn.len(), 3);
3833 check_spends!(b_txn[1], chan_1.3); // Local commitment tx, issued by ChannelManager
3834 assert_eq!(b_txn[0], b_txn[2]); // HTLC-Success tx, issued by ChannelMonitor, * 2 due to block rescan
3835 check_spends!(b_txn[0], commitment_tx[0].clone());
3836 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3837 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
3838 assert_eq!(b_txn[2].lock_time, 0); // Success tx
3840 check_closed_broadcast!(nodes[1]);
3844 fn test_duplicate_payment_hash_one_failure_one_success() {
3845 // Topology : A --> B --> C
3846 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
3847 let mut nodes = create_network(3, &[None, None, None]);
3849 create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
3850 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new());
3852 let (our_payment_preimage, duplicate_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
3853 *nodes[0].network_payment_count.borrow_mut() -= 1;
3854 assert_eq!(route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, duplicate_payment_hash);
3856 let commitment_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
3857 assert_eq!(commitment_txn[0].input.len(), 1);
3858 check_spends!(commitment_txn[0], chan_2.3.clone());
3860 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3861 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
3862 check_closed_broadcast!(nodes[1]);
3864 let htlc_timeout_tx;
3865 { // Extract one of the two HTLC-Timeout transaction
3866 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3867 assert_eq!(node_txn.len(), 7);
3868 assert_eq!(node_txn[0], node_txn[5]);
3869 assert_eq!(node_txn[1], node_txn[6]);
3870 check_spends!(node_txn[0], commitment_txn[0].clone());
3871 assert_eq!(node_txn[0].input.len(), 1);
3872 check_spends!(node_txn[1], commitment_txn[0].clone());
3873 assert_eq!(node_txn[1].input.len(), 1);
3874 assert_ne!(node_txn[0].input[0], node_txn[1].input[0]);
3875 check_spends!(node_txn[2], chan_2.3.clone());
3876 check_spends!(node_txn[3], node_txn[2].clone());
3877 check_spends!(node_txn[4], node_txn[2].clone());
3878 htlc_timeout_tx = node_txn[1].clone();
3881 nodes[2].node.claim_funds(our_payment_preimage);
3882 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
3883 check_added_monitors!(nodes[2], 2);
3884 let events = nodes[2].node.get_and_clear_pending_msg_events();
3886 MessageSendEvent::UpdateHTLCs { .. } => {},
3887 _ => panic!("Unexpected event"),
3890 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
3891 _ => panic!("Unexepected event"),
3893 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
3894 assert_eq!(htlc_success_txn.len(), 5);
3895 check_spends!(htlc_success_txn[2], chan_2.3.clone());
3896 assert_eq!(htlc_success_txn[0], htlc_success_txn[3]);
3897 assert_eq!(htlc_success_txn[0].input.len(), 1);
3898 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3899 assert_eq!(htlc_success_txn[1], htlc_success_txn[4]);
3900 assert_eq!(htlc_success_txn[1].input.len(), 1);
3901 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3902 assert_ne!(htlc_success_txn[0].input[0], htlc_success_txn[1].input[0]);
3903 check_spends!(htlc_success_txn[0], commitment_txn[0].clone());
3904 check_spends!(htlc_success_txn[1], commitment_txn[0].clone());
3906 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![htlc_timeout_tx] }, 200);
3907 connect_blocks(&nodes[1].chain_monitor, ANTI_REORG_DELAY - 1, 200, true, header.bitcoin_hash());
3908 expect_pending_htlcs_forwardable!(nodes[1]);
3909 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3910 assert!(htlc_updates.update_add_htlcs.is_empty());
3911 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
3912 assert_eq!(htlc_updates.update_fail_htlcs[0].htlc_id, 1);
3913 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
3914 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
3915 check_added_monitors!(nodes[1], 1);
3917 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]).unwrap();
3918 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3920 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
3921 let events = nodes[0].node.get_and_clear_pending_msg_events();
3922 assert_eq!(events.len(), 1);
3924 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. } } => {
3926 _ => { panic!("Unexpected event"); }
3929 let events = nodes[0].node.get_and_clear_pending_events();
3931 Event::PaymentFailed { ref payment_hash, .. } => {
3932 assert_eq!(*payment_hash, duplicate_payment_hash);
3934 _ => panic!("Unexpected event"),
3937 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
3938 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![htlc_success_txn[0].clone()] }, 200);
3939 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3940 assert!(updates.update_add_htlcs.is_empty());
3941 assert!(updates.update_fail_htlcs.is_empty());
3942 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3943 assert_eq!(updates.update_fulfill_htlcs[0].htlc_id, 0);
3944 assert!(updates.update_fail_malformed_htlcs.is_empty());
3945 check_added_monitors!(nodes[1], 1);
3947 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
3948 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
3950 let events = nodes[0].node.get_and_clear_pending_events();
3952 Event::PaymentSent { ref payment_preimage } => {
3953 assert_eq!(*payment_preimage, our_payment_preimage);
3955 _ => panic!("Unexpected event"),
3960 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
3961 let nodes = create_network(2, &[None, None]);
3963 // Create some initial channels
3964 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
3966 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
3967 let local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
3968 assert_eq!(local_txn[0].input.len(), 1);
3969 check_spends!(local_txn[0], chan_1.3.clone());
3971 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
3972 nodes[1].node.claim_funds(payment_preimage);
3973 check_added_monitors!(nodes[1], 1);
3974 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3975 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![local_txn[0].clone()] }, 1);
3976 let events = nodes[1].node.get_and_clear_pending_msg_events();
3978 MessageSendEvent::UpdateHTLCs { .. } => {},
3979 _ => panic!("Unexpected event"),
3982 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
3983 _ => panic!("Unexepected event"),
3985 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3986 assert_eq!(node_txn[0].input.len(), 1);
3987 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3988 check_spends!(node_txn[0], local_txn[0].clone());
3990 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
3991 let spend_txn = check_spendable_outputs!(nodes[1], 1);
3992 assert_eq!(spend_txn.len(), 2);
3993 check_spends!(spend_txn[0], node_txn[0].clone());
3994 check_spends!(spend_txn[1], node_txn[2].clone());
3997 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
3998 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
3999 // unrevoked commitment transaction.
4000 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
4001 // a remote RAA before they could be failed backwards (and combinations thereof).
4002 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
4003 // use the same payment hashes.
4004 // Thus, we use a six-node network:
4009 // And test where C fails back to A/B when D announces its latest commitment transaction
4010 let nodes = create_network(6, &[None, None, None, None, None, None]);
4012 create_announced_chan_between_nodes(&nodes, 0, 2, LocalFeatures::new(), LocalFeatures::new());
4013 create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new());
4014 let chan = create_announced_chan_between_nodes(&nodes, 2, 3, LocalFeatures::new(), LocalFeatures::new());
4015 create_announced_chan_between_nodes(&nodes, 3, 4, LocalFeatures::new(), LocalFeatures::new());
4016 create_announced_chan_between_nodes(&nodes, 3, 5, LocalFeatures::new(), LocalFeatures::new());
4018 // Rebalance and check output sanity...
4019 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
4020 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
4021 assert_eq!(nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn[0].output.len(), 2);
4023 let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
4025 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
4027 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
4028 let route = nodes[1].router.get_route(&nodes[5].node.get_our_node_id(), None, &Vec::new(), ds_dust_limit*1000, TEST_FINAL_CLTV).unwrap();
4030 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
4032 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
4034 let (_, payment_hash_3) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4036 let (_, payment_hash_4) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4037 let route = nodes[1].router.get_route(&nodes[5].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
4039 send_along_route_with_hash(&nodes[1], route.clone(), &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_3);
4041 send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_4);
4044 let (_, payment_hash_5) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4046 let route = nodes[1].router.get_route(&nodes[5].node.get_our_node_id(), None, &Vec::new(), ds_dust_limit*1000, TEST_FINAL_CLTV).unwrap();
4047 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
4050 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
4052 let route = nodes[1].router.get_route(&nodes[5].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
4053 send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_6);
4055 // Double-check that six of the new HTLC were added
4056 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
4057 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
4058 assert_eq!(nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn.len(), 1);
4059 assert_eq!(nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn[0].output.len(), 8);
4061 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
4062 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
4063 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1));
4064 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3));
4065 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5));
4066 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6));
4067 check_added_monitors!(nodes[4], 0);
4068 expect_pending_htlcs_forwardable!(nodes[4]);
4069 check_added_monitors!(nodes[4], 1);
4071 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
4072 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]).unwrap();
4073 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]).unwrap();
4074 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]).unwrap();
4075 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]).unwrap();
4076 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
4078 // Fail 3rd below-dust and 7th above-dust HTLCs
4079 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2));
4080 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4));
4081 check_added_monitors!(nodes[5], 0);
4082 expect_pending_htlcs_forwardable!(nodes[5]);
4083 check_added_monitors!(nodes[5], 1);
4085 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
4086 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]).unwrap();
4087 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]).unwrap();
4088 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
4090 let ds_prev_commitment_tx = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn.clone();
4092 expect_pending_htlcs_forwardable!(nodes[3]);
4093 check_added_monitors!(nodes[3], 1);
4094 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
4095 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]).unwrap();
4096 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]).unwrap();
4097 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]).unwrap();
4098 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]).unwrap();
4099 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]).unwrap();
4100 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]).unwrap();
4101 if deliver_last_raa {
4102 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
4104 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
4107 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
4108 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
4109 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
4110 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
4112 // We now broadcast the latest commitment transaction, which *should* result in failures for
4113 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
4114 // the non-broadcast above-dust HTLCs.
4116 // Alternatively, we may broadcast the previous commitment transaction, which should only
4117 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
4118 let ds_last_commitment_tx = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn.clone();
4120 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4121 if announce_latest {
4122 nodes[2].chain_monitor.block_connected_checked(&header, 1, &[&ds_last_commitment_tx[0]], &[1; 1]);
4124 nodes[2].chain_monitor.block_connected_checked(&header, 1, &[&ds_prev_commitment_tx[0]], &[1; 1]);
4126 connect_blocks(&nodes[2].chain_monitor, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4127 check_closed_broadcast!(nodes[2]);
4128 expect_pending_htlcs_forwardable!(nodes[2]);
4129 check_added_monitors!(nodes[2], 2);
4131 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
4132 assert_eq!(cs_msgs.len(), 2);
4133 let mut a_done = false;
4134 for msg in cs_msgs {
4136 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
4137 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
4138 // should be failed-backwards here.
4139 let target = if *node_id == nodes[0].node.get_our_node_id() {
4140 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
4141 for htlc in &updates.update_fail_htlcs {
4142 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 });
4144 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
4149 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
4150 for htlc in &updates.update_fail_htlcs {
4151 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
4153 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
4154 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
4157 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
4158 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]).unwrap();
4159 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]).unwrap();
4160 if announce_latest {
4161 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]).unwrap();
4162 if *node_id == nodes[0].node.get_our_node_id() {
4163 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]).unwrap();
4166 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
4168 _ => panic!("Unexpected event"),
4172 let as_events = nodes[0].node.get_and_clear_pending_events();
4173 assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
4174 let mut as_failds = HashSet::new();
4175 for event in as_events.iter() {
4176 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
4177 assert!(as_failds.insert(*payment_hash));
4178 if *payment_hash != payment_hash_2 {
4179 assert_eq!(*rejected_by_dest, deliver_last_raa);
4181 assert!(!rejected_by_dest);
4183 } else { panic!("Unexpected event"); }
4185 assert!(as_failds.contains(&payment_hash_1));
4186 assert!(as_failds.contains(&payment_hash_2));
4187 if announce_latest {
4188 assert!(as_failds.contains(&payment_hash_3));
4189 assert!(as_failds.contains(&payment_hash_5));
4191 assert!(as_failds.contains(&payment_hash_6));
4193 let bs_events = nodes[1].node.get_and_clear_pending_events();
4194 assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
4195 let mut bs_failds = HashSet::new();
4196 for event in bs_events.iter() {
4197 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
4198 assert!(bs_failds.insert(*payment_hash));
4199 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
4200 assert_eq!(*rejected_by_dest, deliver_last_raa);
4202 assert!(!rejected_by_dest);
4204 } else { panic!("Unexpected event"); }
4206 assert!(bs_failds.contains(&payment_hash_1));
4207 assert!(bs_failds.contains(&payment_hash_2));
4208 if announce_latest {
4209 assert!(bs_failds.contains(&payment_hash_4));
4211 assert!(bs_failds.contains(&payment_hash_5));
4213 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
4214 // get a PaymentFailureNetworkUpdate. A should have gotten 4 HTLCs which were failed-back due
4215 // to unknown-preimage-etc, B should have gotten 2. Thus, in the
4216 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2
4217 // PaymentFailureNetworkUpdates.
4218 let as_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4219 assert_eq!(as_msg_events.len(), if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
4220 let bs_msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4221 assert_eq!(bs_msg_events.len(), if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
4222 for event in as_msg_events.iter().chain(bs_msg_events.iter()) {
4224 &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
4225 _ => panic!("Unexpected event"),
4231 fn test_fail_backwards_latest_remote_announce_a() {
4232 do_test_fail_backwards_unrevoked_remote_announce(false, true);
4236 fn test_fail_backwards_latest_remote_announce_b() {
4237 do_test_fail_backwards_unrevoked_remote_announce(true, true);
4241 fn test_fail_backwards_previous_remote_announce() {
4242 do_test_fail_backwards_unrevoked_remote_announce(false, false);
4243 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
4244 // tested for in test_commitment_revoked_fail_backward_exhaustive()
4248 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
4249 let nodes = create_network(2, &[None, None]);
4251 // Create some initial channels
4252 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
4254 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
4255 let local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
4256 assert_eq!(local_txn[0].input.len(), 1);
4257 check_spends!(local_txn[0], chan_1.3.clone());
4259 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
4260 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4261 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![local_txn[0].clone()] }, 200);
4262 check_closed_broadcast!(nodes[0]);
4264 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4265 assert_eq!(node_txn[0].input.len(), 1);
4266 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4267 check_spends!(node_txn[0], local_txn[0].clone());
4269 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
4270 let spend_txn = check_spendable_outputs!(nodes[0], 1);
4271 assert_eq!(spend_txn.len(), 8);
4272 assert_eq!(spend_txn[0], spend_txn[2]);
4273 assert_eq!(spend_txn[0], spend_txn[4]);
4274 assert_eq!(spend_txn[0], spend_txn[6]);
4275 assert_eq!(spend_txn[1], spend_txn[3]);
4276 assert_eq!(spend_txn[1], spend_txn[5]);
4277 assert_eq!(spend_txn[1], spend_txn[7]);
4278 check_spends!(spend_txn[0], local_txn[0].clone());
4279 check_spends!(spend_txn[1], node_txn[0].clone());
4283 fn test_static_output_closing_tx() {
4284 let nodes = create_network(2, &[None, None]);
4286 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
4288 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4289 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
4291 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4292 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![closing_tx.clone()] }, 1);
4293 let spend_txn = check_spendable_outputs!(nodes[0], 2);
4294 assert_eq!(spend_txn.len(), 1);
4295 check_spends!(spend_txn[0], closing_tx.clone());
4297 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![closing_tx.clone()] }, 1);
4298 let spend_txn = check_spendable_outputs!(nodes[1], 2);
4299 assert_eq!(spend_txn.len(), 1);
4300 check_spends!(spend_txn[0], closing_tx);
4303 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
4304 let nodes = create_network(2, &[None, None]);
4305 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
4307 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
4309 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
4310 // present in B's local commitment transaction, but none of A's commitment transactions.
4311 assert!(nodes[1].node.claim_funds(our_payment_preimage));
4312 check_added_monitors!(nodes[1], 1);
4314 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4315 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]).unwrap();
4316 let events = nodes[0].node.get_and_clear_pending_events();
4317 assert_eq!(events.len(), 1);
4319 Event::PaymentSent { payment_preimage } => {
4320 assert_eq!(payment_preimage, our_payment_preimage);
4322 _ => panic!("Unexpected event"),
4325 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed).unwrap();
4326 check_added_monitors!(nodes[0], 1);
4327 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4328 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0).unwrap();
4329 check_added_monitors!(nodes[1], 1);
4331 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4332 for i in 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + CHAN_CONFIRM_DEPTH + 1 {
4333 nodes[1].chain_monitor.block_connected_checked(&header, i, &Vec::new(), &Vec::new());
4334 header.prev_blockhash = header.bitcoin_hash();
4336 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
4337 check_closed_broadcast!(nodes[1]);
4340 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
4341 let mut nodes = create_network(2, &[None, None]);
4342 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
4344 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), if use_dust { 50000 } else { 3000000 }, TEST_FINAL_CLTV).unwrap();
4345 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
4346 nodes[0].node.send_payment(route, payment_hash).unwrap();
4347 check_added_monitors!(nodes[0], 1);
4349 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4351 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
4352 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
4353 // to "time out" the HTLC.
4355 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4356 for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
4357 nodes[0].chain_monitor.block_connected_checked(&header, i, &Vec::new(), &Vec::new());
4358 header.prev_blockhash = header.bitcoin_hash();
4360 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
4361 check_closed_broadcast!(nodes[0]);
4364 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
4365 let nodes = create_network(3, &[None, None, None]);
4366 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
4368 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
4369 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
4370 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
4371 // actually revoked.
4372 let htlc_value = if use_dust { 50000 } else { 3000000 };
4373 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
4374 assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash));
4375 expect_pending_htlcs_forwardable!(nodes[1]);
4376 check_added_monitors!(nodes[1], 1);
4378 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4379 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]).unwrap();
4380 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed).unwrap();
4381 check_added_monitors!(nodes[0], 1);
4382 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4383 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0).unwrap();
4384 check_added_monitors!(nodes[1], 1);
4385 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1).unwrap();
4386 check_added_monitors!(nodes[1], 1);
4387 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4389 if check_revoke_no_close {
4390 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
4391 check_added_monitors!(nodes[0], 1);
4394 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4395 for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
4396 nodes[0].chain_monitor.block_connected_checked(&header, i, &Vec::new(), &Vec::new());
4397 header.prev_blockhash = header.bitcoin_hash();
4399 if !check_revoke_no_close {
4400 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
4401 check_closed_broadcast!(nodes[0]);
4403 let events = nodes[0].node.get_and_clear_pending_events();
4404 assert_eq!(events.len(), 1);
4406 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
4407 assert_eq!(payment_hash, our_payment_hash);
4408 assert!(rejected_by_dest);
4410 _ => panic!("Unexpected event"),
4415 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
4416 // There are only a few cases to test here:
4417 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
4418 // broadcastable commitment transactions result in channel closure,
4419 // * its included in an unrevoked-but-previous remote commitment transaction,
4420 // * its included in the latest remote or local commitment transactions.
4421 // We test each of the three possible commitment transactions individually and use both dust and
4423 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
4424 // assume they are handled the same across all six cases, as both outbound and inbound failures are
4425 // tested for at least one of the cases in other tests.
4427 fn htlc_claim_single_commitment_only_a() {
4428 do_htlc_claim_local_commitment_only(true);
4429 do_htlc_claim_local_commitment_only(false);
4431 do_htlc_claim_current_remote_commitment_only(true);
4432 do_htlc_claim_current_remote_commitment_only(false);
4436 fn htlc_claim_single_commitment_only_b() {
4437 do_htlc_claim_previous_remote_commitment_only(true, false);
4438 do_htlc_claim_previous_remote_commitment_only(false, false);
4439 do_htlc_claim_previous_remote_commitment_only(true, true);
4440 do_htlc_claim_previous_remote_commitment_only(false, true);
4443 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>)
4444 where F1: for <'a> FnMut(&'a mut msgs::UpdateAddHTLC),
4447 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);
4451 // 0: node1 fails backward
4452 // 1: final node fails backward
4453 // 2: payment completed but the user rejects the payment
4454 // 3: final node fails backward (but tamper onion payloads from node0)
4455 // 100: trigger error in the intermediate node and tamper returning fail_htlc
4456 // 200: trigger error in the final node and tamper returning fail_htlc
4457 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>)
4458 where F1: for <'a> FnMut(&'a mut msgs::UpdateAddHTLC),
4459 F2: for <'a> FnMut(&'a mut msgs::UpdateFailHTLC),
4462 use ln::msgs::HTLCFailChannelUpdate;
4464 // reset block height
4465 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4466 for ix in 0..nodes.len() {
4467 nodes[ix].chain_monitor.block_connected_checked(&header, 1, &Vec::new()[..], &[0; 0]);
4470 macro_rules! expect_event {
4471 ($node: expr, $event_type: path) => {{
4472 let events = $node.node.get_and_clear_pending_events();
4473 assert_eq!(events.len(), 1);
4475 $event_type { .. } => {},
4476 _ => panic!("Unexpected event"),
4481 macro_rules! expect_htlc_forward {
4483 expect_event!($node, Event::PendingHTLCsForwardable);
4484 $node.node.process_pending_htlc_forwards();
4488 // 0 ~~> 2 send payment
4489 nodes[0].node.send_payment(route.clone(), payment_hash.clone()).unwrap();
4490 check_added_monitors!(nodes[0], 1);
4491 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4492 // temper update_add (0 => 1)
4493 let mut update_add_0 = update_0.update_add_htlcs[0].clone();
4494 if test_case == 0 || test_case == 3 || test_case == 100 {
4495 callback_msg(&mut update_add_0);
4498 // 0 => 1 update_add & CS
4499 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add_0).unwrap();
4500 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
4502 let update_1_0 = match test_case {
4503 0|100 => { // intermediate node failure; fail backward to 0
4504 let update_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4505 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));
4508 1|2|3|200 => { // final node failure; forwarding to 2
4509 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4511 if test_case != 200 {
4514 expect_htlc_forward!(&nodes[1]);
4516 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
4517 check_added_monitors!(&nodes[1], 1);
4518 assert_eq!(update_1.update_add_htlcs.len(), 1);
4519 // tamper update_add (1 => 2)
4520 let mut update_add_1 = update_1.update_add_htlcs[0].clone();
4521 if test_case != 3 && test_case != 200 {
4522 callback_msg(&mut update_add_1);
4526 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_1).unwrap();
4527 commitment_signed_dance!(nodes[2], nodes[1], update_1.commitment_signed, false, true);
4529 if test_case == 2 || test_case == 200 {
4530 expect_htlc_forward!(&nodes[2]);
4531 expect_event!(&nodes[2], Event::PaymentReceived);
4533 expect_pending_htlcs_forwardable!(nodes[2]);
4536 let update_2_1 = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4537 if test_case == 2 || test_case == 200 {
4538 check_added_monitors!(&nodes[2], 1);
4540 assert!(update_2_1.update_fail_htlcs.len() == 1);
4542 let mut fail_msg = update_2_1.update_fail_htlcs[0].clone();
4543 if test_case == 200 {
4544 callback_fail(&mut fail_msg);
4548 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_msg).unwrap();
4549 commitment_signed_dance!(nodes[1], nodes[2], update_2_1.commitment_signed, true);
4551 // backward fail on 1
4552 let update_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4553 assert!(update_1_0.update_fail_htlcs.len() == 1);
4556 _ => unreachable!(),
4559 // 1 => 0 commitment_signed_dance
4560 if update_1_0.update_fail_htlcs.len() > 0 {
4561 let mut fail_msg = update_1_0.update_fail_htlcs[0].clone();
4562 if test_case == 100 {
4563 callback_fail(&mut fail_msg);
4565 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg).unwrap();
4567 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_1_0.update_fail_malformed_htlcs[0]).unwrap();
4570 commitment_signed_dance!(nodes[0], nodes[1], update_1_0.commitment_signed, false, true);
4572 let events = nodes[0].node.get_and_clear_pending_events();
4573 assert_eq!(events.len(), 1);
4574 if let &Event::PaymentFailed { payment_hash:_, ref rejected_by_dest, ref error_code } = &events[0] {
4575 assert_eq!(*rejected_by_dest, !expected_retryable);
4576 assert_eq!(*error_code, expected_error_code);
4578 panic!("Uexpected event");
4581 let events = nodes[0].node.get_and_clear_pending_msg_events();
4582 if expected_channel_update.is_some() {
4583 assert_eq!(events.len(), 1);
4585 MessageSendEvent::PaymentFailureNetworkUpdate { ref update } => {
4587 &HTLCFailChannelUpdate::ChannelUpdateMessage { .. } => {
4588 if let HTLCFailChannelUpdate::ChannelUpdateMessage { .. } = expected_channel_update.unwrap() {} else {
4589 panic!("channel_update not found!");
4592 &HTLCFailChannelUpdate::ChannelClosed { ref short_channel_id, ref is_permanent } => {
4593 if let HTLCFailChannelUpdate::ChannelClosed { short_channel_id: ref expected_short_channel_id, is_permanent: ref expected_is_permanent } = expected_channel_update.unwrap() {
4594 assert!(*short_channel_id == *expected_short_channel_id);
4595 assert!(*is_permanent == *expected_is_permanent);
4597 panic!("Unexpected message event");
4600 &HTLCFailChannelUpdate::NodeFailure { ref node_id, ref is_permanent } => {
4601 if let HTLCFailChannelUpdate::NodeFailure { node_id: ref expected_node_id, is_permanent: ref expected_is_permanent } = expected_channel_update.unwrap() {
4602 assert!(*node_id == *expected_node_id);
4603 assert!(*is_permanent == *expected_is_permanent);
4605 panic!("Unexpected message event");
4610 _ => panic!("Unexpected message event"),
4613 assert_eq!(events.len(), 0);
4617 impl msgs::ChannelUpdate {
4618 fn dummy() -> msgs::ChannelUpdate {
4619 use secp256k1::ffi::Signature as FFISignature;
4620 use secp256k1::Signature;
4621 msgs::ChannelUpdate {
4622 signature: Signature::from(FFISignature::new()),
4623 contents: msgs::UnsignedChannelUpdate {
4624 chain_hash: Sha256dHash::hash(&vec![0u8][..]),
4625 short_channel_id: 0,
4628 cltv_expiry_delta: 0,
4629 htlc_minimum_msat: 0,
4631 fee_proportional_millionths: 0,
4632 excess_data: vec![],
4639 fn test_onion_failure() {
4640 use ln::msgs::ChannelUpdate;
4641 use ln::channelmanager::CLTV_FAR_FAR_AWAY;
4644 const BADONION: u16 = 0x8000;
4645 const PERM: u16 = 0x4000;
4646 const NODE: u16 = 0x2000;
4647 const UPDATE: u16 = 0x1000;
4649 let mut nodes = create_network(3, &[None, None, None]);
4650 for node in nodes.iter() {
4651 *node.keys_manager.override_session_priv.lock().unwrap() = Some(SecretKey::from_slice(&[3; 32]).unwrap());
4653 let channels = [create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new()), create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new())];
4654 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
4655 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 40000, TEST_FINAL_CLTV).unwrap();
4657 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 40000);
4659 // intermediate node failure
4660 run_onion_failure_test("invalid_realm", 0, &nodes, &route, &payment_hash, |msg| {
4661 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4662 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
4663 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4664 let (mut onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(&route, cur_height).unwrap();
4665 onion_payloads[0].realm = 3;
4666 msg.onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, &payment_hash);
4667 }, ||{}, true, Some(PERM|1), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));//XXX incremented channels idx here
4669 // final node failure
4670 run_onion_failure_test("invalid_realm", 3, &nodes, &route, &payment_hash, |msg| {
4671 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4672 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
4673 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4674 let (mut onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(&route, cur_height).unwrap();
4675 onion_payloads[1].realm = 3;
4676 msg.onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, &payment_hash);
4677 }, ||{}, false, Some(PERM|1), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
4679 // the following three with run_onion_failure_test_with_fail_intercept() test only the origin node
4680 // receiving simulated fail messages
4681 // intermediate node failure
4682 run_onion_failure_test_with_fail_intercept("temporary_node_failure", 100, &nodes, &route, &payment_hash, |msg| {
4684 msg.amount_msat -= 1;
4686 // and tamper returning error message
4687 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4688 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4689 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], NODE|2, &[0;0]);
4690 }, ||{}, true, Some(NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[0].pubkey, is_permanent: false}));
4692 // final node failure
4693 run_onion_failure_test_with_fail_intercept("temporary_node_failure", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
4694 // and tamper returning error message
4695 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4696 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4697 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], NODE|2, &[0;0]);
4699 nodes[2].node.fail_htlc_backwards(&payment_hash);
4700 }, true, Some(NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[1].pubkey, is_permanent: false}));
4702 // intermediate node failure
4703 run_onion_failure_test_with_fail_intercept("permanent_node_failure", 100, &nodes, &route, &payment_hash, |msg| {
4704 msg.amount_msat -= 1;
4706 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4707 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4708 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|NODE|2, &[0;0]);
4709 }, ||{}, true, Some(PERM|NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[0].pubkey, is_permanent: true}));
4711 // final node failure
4712 run_onion_failure_test_with_fail_intercept("permanent_node_failure", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
4713 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4714 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4715 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], PERM|NODE|2, &[0;0]);
4717 nodes[2].node.fail_htlc_backwards(&payment_hash);
4718 }, false, Some(PERM|NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[1].pubkey, is_permanent: true}));
4720 // intermediate node failure
4721 run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 100, &nodes, &route, &payment_hash, |msg| {
4722 msg.amount_msat -= 1;
4724 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4725 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4726 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|NODE|3, &[0;0]);
4728 nodes[2].node.fail_htlc_backwards(&payment_hash);
4729 }, true, Some(PERM|NODE|3), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[0].pubkey, is_permanent: true}));
4731 // final node failure
4732 run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
4733 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4734 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4735 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], PERM|NODE|3, &[0;0]);
4737 nodes[2].node.fail_htlc_backwards(&payment_hash);
4738 }, false, Some(PERM|NODE|3), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[1].pubkey, is_permanent: true}));
4740 run_onion_failure_test("invalid_onion_version", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.version = 1; }, ||{}, true,
4741 Some(BADONION|PERM|4), None);
4743 run_onion_failure_test("invalid_onion_hmac", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.hmac = [3; 32]; }, ||{}, true,
4744 Some(BADONION|PERM|5), None);
4746 run_onion_failure_test("invalid_onion_key", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.public_key = Err(secp256k1::Error::InvalidPublicKey);}, ||{}, true,
4747 Some(BADONION|PERM|6), None);
4749 run_onion_failure_test_with_fail_intercept("temporary_channel_failure", 100, &nodes, &route, &payment_hash, |msg| {
4750 msg.amount_msat -= 1;
4752 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4753 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4754 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], UPDATE|7, &ChannelUpdate::dummy().encode_with_len()[..]);
4755 }, ||{}, true, Some(UPDATE|7), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
4757 run_onion_failure_test_with_fail_intercept("permanent_channel_failure", 100, &nodes, &route, &payment_hash, |msg| {
4758 msg.amount_msat -= 1;
4760 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4761 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4762 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|8, &[0;0]);
4763 // short_channel_id from the processing node
4764 }, ||{}, true, Some(PERM|8), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
4766 run_onion_failure_test_with_fail_intercept("required_channel_feature_missing", 100, &nodes, &route, &payment_hash, |msg| {
4767 msg.amount_msat -= 1;
4769 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4770 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4771 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|9, &[0;0]);
4772 // short_channel_id from the processing node
4773 }, ||{}, true, Some(PERM|9), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
4775 let mut bogus_route = route.clone();
4776 bogus_route.hops[1].short_channel_id -= 1;
4777 run_onion_failure_test("unknown_next_peer", 0, &nodes, &bogus_route, &payment_hash, |_| {}, ||{}, true, Some(PERM|10),
4778 Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: bogus_route.hops[1].short_channel_id, is_permanent:true}));
4780 let amt_to_forward = nodes[1].node.channel_state.lock().unwrap().by_id.get(&channels[1].2).unwrap().get_their_htlc_minimum_msat() - 1;
4781 let mut bogus_route = route.clone();
4782 let route_len = bogus_route.hops.len();
4783 bogus_route.hops[route_len-1].fee_msat = amt_to_forward;
4784 run_onion_failure_test("amount_below_minimum", 0, &nodes, &bogus_route, &payment_hash, |_| {}, ||{}, true, Some(UPDATE|11), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
4786 //TODO: with new config API, we will be able to generate both valid and
4787 //invalid channel_update cases.
4788 run_onion_failure_test("fee_insufficient", 0, &nodes, &route, &payment_hash, |msg| {
4789 msg.amount_msat -= 1;
4790 }, || {}, true, Some(UPDATE|12), Some(msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id: channels[0].0.contents.short_channel_id, is_permanent: true}));
4792 run_onion_failure_test("incorrect_cltv_expiry", 0, &nodes, &route, &payment_hash, |msg| {
4793 // need to violate: cltv_expiry - cltv_expiry_delta >= outgoing_cltv_value
4794 msg.cltv_expiry -= 1;
4795 }, || {}, true, Some(UPDATE|13), Some(msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id: channels[0].0.contents.short_channel_id, is_permanent: true}));
4797 run_onion_failure_test("expiry_too_soon", 0, &nodes, &route, &payment_hash, |msg| {
4798 let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS + 1;
4799 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4800 nodes[1].chain_monitor.block_connected_checked(&header, height, &Vec::new()[..], &[0; 0]);
4801 }, ||{}, true, Some(UPDATE|14), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
4803 run_onion_failure_test("unknown_payment_hash", 2, &nodes, &route, &payment_hash, |_| {}, || {
4804 nodes[2].node.fail_htlc_backwards(&payment_hash);
4805 }, false, Some(PERM|15), None);
4807 run_onion_failure_test("final_expiry_too_soon", 1, &nodes, &route, &payment_hash, |msg| {
4808 let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS + 1;
4809 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4810 nodes[2].chain_monitor.block_connected_checked(&header, height, &Vec::new()[..], &[0; 0]);
4811 }, || {}, true, Some(17), None);
4813 run_onion_failure_test("final_incorrect_cltv_expiry", 1, &nodes, &route, &payment_hash, |_| {}, || {
4814 for (_, pending_forwards) in nodes[1].node.channel_state.lock().unwrap().borrow_parts().forward_htlcs.iter_mut() {
4815 for f in pending_forwards.iter_mut() {
4817 &mut HTLCForwardInfo::AddHTLC { ref mut forward_info, .. } =>
4818 forward_info.outgoing_cltv_value += 1,
4823 }, true, Some(18), None);
4825 run_onion_failure_test("final_incorrect_htlc_amount", 1, &nodes, &route, &payment_hash, |_| {}, || {
4826 // violate amt_to_forward > msg.amount_msat
4827 for (_, pending_forwards) in nodes[1].node.channel_state.lock().unwrap().borrow_parts().forward_htlcs.iter_mut() {
4828 for f in pending_forwards.iter_mut() {
4830 &mut HTLCForwardInfo::AddHTLC { ref mut forward_info, .. } =>
4831 forward_info.amt_to_forward -= 1,
4836 }, true, Some(19), None);
4838 run_onion_failure_test("channel_disabled", 0, &nodes, &route, &payment_hash, |_| {}, || {
4839 // disconnect event to the channel between nodes[1] ~ nodes[2]
4840 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
4841 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4842 }, true, Some(UPDATE|20), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
4843 reconnect_nodes(&nodes[1], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4845 run_onion_failure_test("expiry_too_far", 0, &nodes, &route, &payment_hash, |msg| {
4846 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4847 let mut route = route.clone();
4849 route.hops[1].cltv_expiry_delta += CLTV_FAR_FAR_AWAY + route.hops[0].cltv_expiry_delta + 1;
4850 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4851 let (onion_payloads, _, htlc_cltv) = onion_utils::build_onion_payloads(&route, height).unwrap();
4852 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, &payment_hash);
4853 msg.cltv_expiry = htlc_cltv;
4854 msg.onion_routing_packet = onion_packet;
4855 }, ||{}, true, Some(21), None);
4860 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
4861 let nodes = create_network(2, &[None, None]);
4862 //Force duplicate channel ids
4863 for node in nodes.iter() {
4864 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
4867 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
4868 let channel_value_satoshis=10000;
4869 let push_msat=10001;
4870 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42).unwrap();
4871 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
4872 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), LocalFeatures::new(), &node0_to_1_send_open_channel).unwrap();
4874 //Create a second channel with a channel_id collision
4875 assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42).is_err());
4879 fn bolt2_open_channel_sending_node_checks_part2() {
4880 let nodes = create_network(2, &[None, None]);
4882 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
4883 let channel_value_satoshis=2^24;
4884 let push_msat=10001;
4885 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42).is_err());
4887 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
4888 let channel_value_satoshis=10000;
4889 // Test when push_msat is equal to 1000 * funding_satoshis.
4890 let push_msat=1000*channel_value_satoshis+1;
4891 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42).is_err());
4893 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
4894 let channel_value_satoshis=10000;
4895 let push_msat=10001;
4896 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42).is_ok()); //Create a valid channel
4897 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
4898 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
4900 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
4901 // 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
4902 assert!(node0_to_1_send_open_channel.channel_flags<=1);
4904 // 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.
4905 assert!(BREAKDOWN_TIMEOUT>0);
4906 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
4908 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
4909 let chain_hash=genesis_block(Network::Testnet).header.bitcoin_hash();
4910 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
4912 // 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.
4913 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
4914 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
4915 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
4916 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_basepoint.serialize()).is_ok());
4917 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
4920 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
4921 // 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.
4922 //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.
4925 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
4926 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
4927 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
4928 let mut nodes = create_network(2, &[None, None]);
4929 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, LocalFeatures::new(), LocalFeatures::new());
4930 let mut route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
4931 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4933 route.hops[0].fee_msat = 0;
4935 let err = nodes[0].node.send_payment(route, our_payment_hash);
4937 if let Err(APIError::ChannelUnavailable{err}) = err {
4938 assert_eq!(err, "Cannot send less than their minimum HTLC value");
4945 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
4946 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
4947 //It is enforced when constructing a route.
4948 let mut nodes = create_network(2, &[None, None]);
4949 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 0, LocalFeatures::new(), LocalFeatures::new());
4950 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000000, 500000001).unwrap();
4951 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4953 let err = nodes[0].node.send_payment(route, our_payment_hash);
4955 if let Err(APIError::RouteError{err}) = err {
4956 assert_eq!(err, "Channel CLTV overflowed?!");
4963 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
4964 //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.
4965 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
4966 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
4967 let mut nodes = create_network(2, &[None, None]);
4968 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, LocalFeatures::new(), LocalFeatures::new());
4969 let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().their_max_accepted_htlcs as u64;
4971 for i in 0..max_accepted_htlcs {
4972 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
4973 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4974 let payment_event = {
4975 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
4976 check_added_monitors!(nodes[0], 1);
4978 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4979 assert_eq!(events.len(), 1);
4980 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
4981 assert_eq!(htlcs[0].htlc_id, i);
4985 SendEvent::from_event(events.remove(0))
4987 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4988 check_added_monitors!(nodes[1], 0);
4989 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4991 expect_pending_htlcs_forwardable!(nodes[1]);
4992 expect_payment_received!(nodes[1], our_payment_hash, 100000);
4994 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
4995 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4996 let err = nodes[0].node.send_payment(route, our_payment_hash);
4998 if let Err(APIError::ChannelUnavailable{err}) = err {
4999 assert_eq!(err, "Cannot push more than their max accepted HTLCs");
5006 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
5007 //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.
5008 let mut nodes = create_network(2, &[None, None]);
5009 let channel_value = 100000;
5010 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, LocalFeatures::new(), LocalFeatures::new());
5011 let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).their_max_htlc_value_in_flight_msat;
5013 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
5015 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], max_in_flight+1, TEST_FINAL_CLTV).unwrap();
5016 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5017 let err = nodes[0].node.send_payment(route, our_payment_hash);
5019 if let Err(APIError::ChannelUnavailable{err}) = err {
5020 assert_eq!(err, "Cannot send value that would put us over the max HTLC value in flight");
5025 send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
5028 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
5030 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
5031 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
5032 let mut nodes = create_network(2, &[None, None]);
5033 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, LocalFeatures::new(), LocalFeatures::new());
5034 let htlc_minimum_msat: u64;
5036 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
5037 let channel = chan_lock.by_id.get(&chan.2).unwrap();
5038 htlc_minimum_msat = channel.get_our_htlc_minimum_msat();
5040 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], htlc_minimum_msat, TEST_FINAL_CLTV).unwrap();
5041 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5042 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5043 check_added_monitors!(nodes[0], 1);
5044 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5045 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
5046 let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5047 if let Err(msgs::HandleError{err, action: Some(msgs::ErrorAction::SendErrorMessage {..})}) = err {
5048 assert_eq!(err, "Remote side tried to send less than our minimum HTLC value");
5052 assert!(nodes[1].node.list_channels().is_empty());
5053 check_closed_broadcast!(nodes[1]);
5057 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
5058 //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
5059 let mut nodes = create_network(2, &[None, None]);
5060 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, LocalFeatures::new(), LocalFeatures::new());
5062 let their_channel_reserve = get_channel_value_stat!(nodes[0], chan.2).channel_reserve_msat;
5064 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 5000000-their_channel_reserve, TEST_FINAL_CLTV).unwrap();
5065 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5066 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5067 check_added_monitors!(nodes[0], 1);
5068 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5070 updates.update_add_htlcs[0].amount_msat = 5000000-their_channel_reserve+1;
5071 let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5073 if let Err(msgs::HandleError{err, action: Some(msgs::ErrorAction::SendErrorMessage {..})}) = err {
5074 assert_eq!(err, "Remote HTLC add would put them over their reserve value");
5079 assert!(nodes[1].node.list_channels().is_empty());
5080 check_closed_broadcast!(nodes[1]);
5084 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
5085 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
5086 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
5087 let mut nodes = create_network(2, &[None, None]);
5088 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, LocalFeatures::new(), LocalFeatures::new());
5089 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 3999999, TEST_FINAL_CLTV).unwrap();
5090 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5092 let session_priv = SecretKey::from_slice(&{
5093 let mut session_key = [0; 32];
5094 let mut rng = thread_rng();
5095 rng.fill_bytes(&mut session_key);
5097 }).expect("RNG is bad!");
5099 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
5100 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route, &session_priv).unwrap();
5101 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route, cur_height).unwrap();
5102 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, &our_payment_hash);
5104 let mut msg = msgs::UpdateAddHTLC {
5108 payment_hash: our_payment_hash,
5109 cltv_expiry: htlc_cltv,
5110 onion_routing_packet: onion_packet.clone(),
5113 for i in 0..super::channel::OUR_MAX_HTLCS {
5114 msg.htlc_id = i as u64;
5115 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg).unwrap();
5117 msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
5118 let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
5120 if let Err(msgs::HandleError{err, action: Some(msgs::ErrorAction::SendErrorMessage {..})}) = err {
5121 assert_eq!(err, "Remote tried to push more than our max accepted HTLCs");
5126 assert!(nodes[1].node.list_channels().is_empty());
5127 check_closed_broadcast!(nodes[1]);
5131 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
5132 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
5133 let mut nodes = create_network(2, &[None, None]);
5134 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, LocalFeatures::new(), LocalFeatures::new());
5135 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
5136 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5137 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5138 check_added_monitors!(nodes[0], 1);
5139 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5140 updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).their_max_htlc_value_in_flight_msat + 1;
5141 let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5143 if let Err(msgs::HandleError{err, action: Some(msgs::ErrorAction::SendErrorMessage {..})}) = err {
5144 assert_eq!(err,"Remote HTLC add would put them over their max HTLC value in flight");
5149 assert!(nodes[1].node.list_channels().is_empty());
5150 check_closed_broadcast!(nodes[1]);
5154 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
5155 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
5156 let mut nodes = create_network(2, &[None, None]);
5157 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, LocalFeatures::new(), LocalFeatures::new());
5158 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 3999999, TEST_FINAL_CLTV).unwrap();
5159 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5160 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5161 check_added_monitors!(nodes[0], 1);
5162 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5163 updates.update_add_htlcs[0].cltv_expiry = 500000000;
5164 let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5166 if let Err(msgs::HandleError{err, action: Some(msgs::ErrorAction::SendErrorMessage {..})}) = err {
5167 assert_eq!(err,"Remote provided CLTV expiry in seconds instead of block height");
5172 assert!(nodes[1].node.list_channels().is_empty());
5173 check_closed_broadcast!(nodes[1]);
5177 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
5178 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
5179 // We test this by first testing that that repeated HTLCs pass commitment signature checks
5180 // after disconnect and that non-sequential htlc_ids result in a channel failure.
5181 let mut nodes = create_network(2, &[None, None]);
5182 create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
5183 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
5184 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5185 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5186 check_added_monitors!(nodes[0], 1);
5187 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5188 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]).unwrap();
5190 //Disconnect and Reconnect
5191 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5192 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5193 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
5194 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
5195 assert_eq!(reestablish_1.len(), 1);
5196 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
5197 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
5198 assert_eq!(reestablish_2.len(), 1);
5199 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
5200 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
5201 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
5202 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
5205 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]).unwrap();
5206 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
5207 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed).unwrap();
5208 check_added_monitors!(nodes[1], 1);
5209 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5211 let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5212 if let Err(msgs::HandleError{err, action: Some(msgs::ErrorAction::SendErrorMessage {..})}) = err {
5213 assert_eq!(err, "Remote skipped HTLC ID");
5218 assert!(nodes[1].node.list_channels().is_empty());
5219 check_closed_broadcast!(nodes[1]);
5223 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
5224 //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.
5226 let mut nodes = create_network(2, &[None, None]);
5227 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
5229 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
5230 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5231 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5232 check_added_monitors!(nodes[0], 1);
5233 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5234 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]).unwrap();
5236 let update_msg = msgs::UpdateFulfillHTLC{
5239 payment_preimage: our_payment_preimage,
5242 let err = nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
5244 if let Err(msgs::HandleError{err, action: Some(msgs::ErrorAction::SendErrorMessage {..})}) = err {
5245 assert_eq!(err, "Remote tried to fulfill/fail HTLC before it had been committed");
5250 assert!(nodes[0].node.list_channels().is_empty());
5251 check_closed_broadcast!(nodes[0]);
5255 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
5256 //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.
5258 let mut nodes = create_network(2, &[None, None]);
5259 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
5261 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
5262 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5263 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5264 check_added_monitors!(nodes[0], 1);
5265 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5266 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]).unwrap();
5268 let update_msg = msgs::UpdateFailHTLC{
5271 reason: msgs::OnionErrorPacket { data: Vec::new()},
5274 let err = nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
5276 if let Err(msgs::HandleError{err, action: Some(msgs::ErrorAction::SendErrorMessage {..})}) = err {
5277 assert_eq!(err, "Remote tried to fulfill/fail HTLC before it had been committed");
5282 assert!(nodes[0].node.list_channels().is_empty());
5283 check_closed_broadcast!(nodes[0]);
5287 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
5288 //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.
5290 let mut nodes = create_network(2, &[None, None]);
5291 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
5293 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
5294 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5295 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5296 check_added_monitors!(nodes[0], 1);
5297 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5298 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]).unwrap();
5300 let update_msg = msgs::UpdateFailMalformedHTLC{
5303 sha256_of_onion: [1; 32],
5304 failure_code: 0x8000,
5307 let err = nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
5309 if let Err(msgs::HandleError{err, action: Some(msgs::ErrorAction::SendErrorMessage {..})}) = err {
5310 assert_eq!(err, "Remote tried to fulfill/fail HTLC before it had been committed");
5315 assert!(nodes[0].node.list_channels().is_empty());
5316 check_closed_broadcast!(nodes[0]);
5320 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
5321 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
5323 let nodes = create_network(2, &[None, None]);
5324 create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
5326 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
5328 nodes[1].node.claim_funds(our_payment_preimage);
5329 check_added_monitors!(nodes[1], 1);
5331 let events = nodes[1].node.get_and_clear_pending_msg_events();
5332 assert_eq!(events.len(), 1);
5333 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
5335 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, .. } } => {
5336 assert!(update_add_htlcs.is_empty());
5337 assert_eq!(update_fulfill_htlcs.len(), 1);
5338 assert!(update_fail_htlcs.is_empty());
5339 assert!(update_fail_malformed_htlcs.is_empty());
5340 assert!(update_fee.is_none());
5341 update_fulfill_htlcs[0].clone()
5343 _ => panic!("Unexpected event"),
5347 update_fulfill_msg.htlc_id = 1;
5349 let err = nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
5350 if let Err(msgs::HandleError{err, action: Some(msgs::ErrorAction::SendErrorMessage {..})}) = err {
5351 assert_eq!(err, "Remote tried to fulfill/fail an HTLC we couldn't find");
5356 assert!(nodes[0].node.list_channels().is_empty());
5357 check_closed_broadcast!(nodes[0]);
5361 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
5362 //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.
5364 let nodes = create_network(2, &[None, None]);
5365 create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
5367 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
5369 nodes[1].node.claim_funds(our_payment_preimage);
5370 check_added_monitors!(nodes[1], 1);
5372 let events = nodes[1].node.get_and_clear_pending_msg_events();
5373 assert_eq!(events.len(), 1);
5374 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
5376 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, .. } } => {
5377 assert!(update_add_htlcs.is_empty());
5378 assert_eq!(update_fulfill_htlcs.len(), 1);
5379 assert!(update_fail_htlcs.is_empty());
5380 assert!(update_fail_malformed_htlcs.is_empty());
5381 assert!(update_fee.is_none());
5382 update_fulfill_htlcs[0].clone()
5384 _ => panic!("Unexpected event"),
5388 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
5390 let err = nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
5391 if let Err(msgs::HandleError{err, action: Some(msgs::ErrorAction::SendErrorMessage {..})}) = err {
5392 assert_eq!(err, "Remote tried to fulfill HTLC with an incorrect preimage");
5397 assert!(nodes[0].node.list_channels().is_empty());
5398 check_closed_broadcast!(nodes[0]);
5403 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
5404 //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.
5406 let mut nodes = create_network(2, &[None, None]);
5407 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, LocalFeatures::new(), LocalFeatures::new());
5408 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
5409 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5410 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5411 check_added_monitors!(nodes[0], 1);
5413 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5414 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
5416 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]).unwrap();
5417 check_added_monitors!(nodes[1], 0);
5418 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
5420 let events = nodes[1].node.get_and_clear_pending_msg_events();
5422 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
5424 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, .. } } => {
5425 assert!(update_add_htlcs.is_empty());
5426 assert!(update_fulfill_htlcs.is_empty());
5427 assert!(update_fail_htlcs.is_empty());
5428 assert_eq!(update_fail_malformed_htlcs.len(), 1);
5429 assert!(update_fee.is_none());
5430 update_fail_malformed_htlcs[0].clone()
5432 _ => panic!("Unexpected event"),
5435 update_msg.failure_code &= !0x8000;
5436 let err = nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
5437 if let Err(msgs::HandleError{err, action: Some(msgs::ErrorAction::SendErrorMessage {..})}) = err {
5438 assert_eq!(err, "Got update_fail_malformed_htlc with BADONION not set");
5443 assert!(nodes[0].node.list_channels().is_empty());
5444 check_closed_broadcast!(nodes[0]);
5448 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
5449 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
5450 // * 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.
5452 let mut nodes = create_network(3, &[None, None, None]);
5453 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, LocalFeatures::new(), LocalFeatures::new());
5454 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, LocalFeatures::new(), LocalFeatures::new());
5456 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV).unwrap();
5457 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5460 let mut payment_event = {
5461 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5462 check_added_monitors!(nodes[0], 1);
5463 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5464 assert_eq!(events.len(), 1);
5465 SendEvent::from_event(events.remove(0))
5467 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
5468 check_added_monitors!(nodes[1], 0);
5469 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5470 expect_pending_htlcs_forwardable!(nodes[1]);
5471 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
5472 assert_eq!(events_2.len(), 1);
5473 check_added_monitors!(nodes[1], 1);
5474 payment_event = SendEvent::from_event(events_2.remove(0));
5475 assert_eq!(payment_event.msgs.len(), 1);
5478 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
5479 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
5480 check_added_monitors!(nodes[2], 0);
5481 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
5483 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
5484 assert_eq!(events_3.len(), 1);
5485 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
5487 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 } } => {
5488 assert!(update_add_htlcs.is_empty());
5489 assert!(update_fulfill_htlcs.is_empty());
5490 assert!(update_fail_htlcs.is_empty());
5491 assert_eq!(update_fail_malformed_htlcs.len(), 1);
5492 assert!(update_fee.is_none());
5493 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
5495 _ => panic!("Unexpected event"),
5499 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0).unwrap();
5501 check_added_monitors!(nodes[1], 0);
5502 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
5503 expect_pending_htlcs_forwardable!(nodes[1]);
5504 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
5505 assert_eq!(events_4.len(), 1);
5507 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
5509 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, .. } } => {
5510 assert!(update_add_htlcs.is_empty());
5511 assert!(update_fulfill_htlcs.is_empty());
5512 assert_eq!(update_fail_htlcs.len(), 1);
5513 assert!(update_fail_malformed_htlcs.is_empty());
5514 assert!(update_fee.is_none());
5516 _ => panic!("Unexpected event"),
5519 check_added_monitors!(nodes[1], 1);
5522 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
5523 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
5524 // 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
5525 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
5527 let nodes = create_network(2, &[None, None]);
5528 let chan =create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
5530 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
5532 // We route 2 dust-HTLCs between A and B
5533 let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
5534 let (_, payment_hash_2) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
5535 route_payment(&nodes[0], &[&nodes[1]], 1000000);
5537 // Cache one local commitment tx as previous
5538 let as_prev_commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn.clone();
5540 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
5541 assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2));
5542 check_added_monitors!(nodes[1], 0);
5543 expect_pending_htlcs_forwardable!(nodes[1]);
5544 check_added_monitors!(nodes[1], 1);
5546 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5547 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]).unwrap();
5548 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed).unwrap();
5549 check_added_monitors!(nodes[0], 1);
5551 // Cache one local commitment tx as lastest
5552 let as_last_commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn.clone();
5554 let events = nodes[0].node.get_and_clear_pending_msg_events();
5556 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
5557 assert_eq!(node_id, nodes[1].node.get_our_node_id());
5559 _ => panic!("Unexpected event"),
5562 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
5563 assert_eq!(node_id, nodes[1].node.get_our_node_id());
5565 _ => panic!("Unexpected event"),
5568 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
5569 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
5570 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5571 if announce_latest {
5572 nodes[0].chain_monitor.block_connected_checked(&header, 1, &[&as_last_commitment_tx[0]], &[1; 1]);
5574 nodes[0].chain_monitor.block_connected_checked(&header, 1, &[&as_prev_commitment_tx[0]], &[1; 1]);
5577 let events = nodes[0].node.get_and_clear_pending_msg_events();
5578 assert_eq!(events.len(), 1);
5580 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5581 _ => panic!("Unexpected event"),
5584 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
5585 connect_blocks(&nodes[0].chain_monitor, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
5586 let events = nodes[0].node.get_and_clear_pending_events();
5587 // Only 2 PaymentFailed events should show up, over-dust HTLC has to be failed by timeout tx
5588 assert_eq!(events.len(), 2);
5589 let mut first_failed = false;
5590 for event in events {
5592 Event::PaymentFailed { payment_hash, .. } => {
5593 if payment_hash == payment_hash_1 {
5594 assert!(!first_failed);
5595 first_failed = true;
5597 assert_eq!(payment_hash, payment_hash_2);
5600 _ => panic!("Unexpected event"),
5606 fn test_failure_delay_dust_htlc_local_commitment() {
5607 do_test_failure_delay_dust_htlc_local_commitment(true);
5608 do_test_failure_delay_dust_htlc_local_commitment(false);
5612 fn test_no_failure_dust_htlc_local_commitment() {
5613 // Transaction filters for failing back dust htlc based on local commitment txn infos has been
5614 // prone to error, we test here that a dummy transaction don't fail them.
5616 let nodes = create_network(2, &[None, None]);
5617 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
5620 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5622 let as_dust_limit = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
5623 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
5625 // We route 2 dust-HTLCs between A and B
5626 let (preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
5627 let (preimage_2, _) = route_payment(&nodes[1], &[&nodes[0]], as_dust_limit*1000);
5629 // Build a dummy invalid transaction trying to spend a commitment tx
5631 previous_output: BitcoinOutPoint { txid: chan.3.txid(), vout: 0 },
5632 script_sig: Script::new(),
5634 witness: Vec::new(),
5638 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
5642 let dummy_tx = Transaction {
5649 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5650 nodes[0].chan_monitor.simple_monitor.block_connected(&header, 1, &[&dummy_tx], &[1;1]);
5651 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
5652 assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 0);
5653 // We broadcast a few more block to check everything is all right
5654 connect_blocks(&nodes[0].chain_monitor, 20, 1, true, header.bitcoin_hash());
5655 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
5656 assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 0);
5658 claim_payment(&nodes[0], &vec!(&nodes[1])[..], preimage_1);
5659 claim_payment(&nodes[1], &vec!(&nodes[0])[..], preimage_2);
5662 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
5663 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
5664 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
5665 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
5666 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
5667 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
5668 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
5670 let nodes = create_network(3, &[None, None, None]);
5671 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
5673 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
5675 let (_payment_preimage_1, dust_hash) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
5676 let (_payment_preimage_2, non_dust_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
5678 let as_commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn.clone();
5679 let bs_commitment_tx = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn.clone();
5681 // We revoked bs_commitment_tx
5683 let (payment_preimage_3, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
5684 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
5687 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5688 let mut timeout_tx = Vec::new();
5690 // We fail dust-HTLC 1 by broadcast of local commitment tx
5691 nodes[0].chain_monitor.block_connected_checked(&header, 1, &[&as_commitment_tx[0]], &[1; 1]);
5692 let events = nodes[0].node.get_and_clear_pending_msg_events();
5693 assert_eq!(events.len(), 1);
5695 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5696 _ => panic!("Unexpected event"),
5698 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
5699 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
5700 let parent_hash = connect_blocks(&nodes[0].chain_monitor, ANTI_REORG_DELAY - 1, 2, true, header.bitcoin_hash());
5701 let events = nodes[0].node.get_and_clear_pending_events();
5702 assert_eq!(events.len(), 1);
5704 Event::PaymentFailed { payment_hash, .. } => {
5705 assert_eq!(payment_hash, dust_hash);
5707 _ => panic!("Unexpected event"),
5709 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5710 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
5711 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5712 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
5713 nodes[0].chain_monitor.block_connected_checked(&header_2, 7, &[&timeout_tx[0]], &[1; 1]);
5714 let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5715 connect_blocks(&nodes[0].chain_monitor, ANTI_REORG_DELAY - 1, 8, true, header_3.bitcoin_hash());
5716 let events = nodes[0].node.get_and_clear_pending_events();
5717 assert_eq!(events.len(), 1);
5719 Event::PaymentFailed { payment_hash, .. } => {
5720 assert_eq!(payment_hash, non_dust_hash);
5722 _ => panic!("Unexpected event"),
5725 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
5726 nodes[0].chain_monitor.block_connected_checked(&header, 1, &[&bs_commitment_tx[0]], &[1; 1]);
5727 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
5728 let events = nodes[0].node.get_and_clear_pending_msg_events();
5729 assert_eq!(events.len(), 1);
5731 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5732 _ => panic!("Unexpected event"),
5734 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
5735 let parent_hash = connect_blocks(&nodes[0].chain_monitor, ANTI_REORG_DELAY - 1, 2, true, header.bitcoin_hash());
5736 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5738 let events = nodes[0].node.get_and_clear_pending_events();
5739 assert_eq!(events.len(), 1);
5741 Event::PaymentFailed { payment_hash, .. } => {
5742 assert_eq!(payment_hash, dust_hash);
5744 _ => panic!("Unexpected event"),
5746 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5747 // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
5748 nodes[0].chain_monitor.block_connected_checked(&header_2, 7, &[&timeout_tx[0]], &[1; 1]);
5749 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
5750 let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5751 connect_blocks(&nodes[0].chain_monitor, ANTI_REORG_DELAY - 1, 8, true, header_3.bitcoin_hash());
5752 let events = nodes[0].node.get_and_clear_pending_events();
5753 assert_eq!(events.len(), 1);
5755 Event::PaymentFailed { payment_hash, .. } => {
5756 assert_eq!(payment_hash, non_dust_hash);
5758 _ => panic!("Unexpected event"),
5761 // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
5763 let events = nodes[0].node.get_and_clear_pending_events();
5764 assert_eq!(events.len(), 2);
5767 Event::PaymentFailed { payment_hash, .. } => {
5768 if payment_hash == dust_hash { first = true; }
5769 else { first = false; }
5771 _ => panic!("Unexpected event"),
5774 Event::PaymentFailed { payment_hash, .. } => {
5775 if first { assert_eq!(payment_hash, non_dust_hash); }
5776 else { assert_eq!(payment_hash, dust_hash); }
5778 _ => panic!("Unexpected event"),
5785 fn test_sweep_outbound_htlc_failure_update() {
5786 do_test_sweep_outbound_htlc_failure_update(false, true);
5787 do_test_sweep_outbound_htlc_failure_update(false, false);
5788 do_test_sweep_outbound_htlc_failure_update(true, false);
5792 fn test_upfront_shutdown_script() {
5793 // BOLT 2 : Option upfront shutdown script, if peer commit its closing_script at channel opening
5794 // enforce it at shutdown message
5796 let mut config = UserConfig::new();
5797 config.channel_options.announced_channel = true;
5798 config.peer_channel_config_limits.force_announced_channel_preference = false;
5799 config.channel_options.commit_upfront_shutdown_pubkey = false;
5800 let nodes = create_network(3, &[None, Some(config), None]);
5802 // We test that in case of peer committing upfront to a script, if it changes at closing, we refuse to sign
5803 let flags = LocalFeatures::new();
5804 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
5805 nodes[0].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
5806 let mut node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
5807 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
5808 // Test we enforce upfront_scriptpbukey if by providing a diffrent one at closing that we disconnect peer
5809 if let Err(error) = nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown) {
5810 if let Some(error) = error.action {
5812 ErrorAction::SendErrorMessage { msg } => {
5813 assert_eq!(msg.data,"Got shutdown request with a scriptpubkey which did not match their previous scriptpubkey");
5815 _ => { assert!(false); }
5817 } else { assert!(false); }
5818 } else { assert!(false); }
5819 let events = nodes[2].node.get_and_clear_pending_msg_events();
5820 assert_eq!(events.len(), 1);
5822 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5823 _ => panic!("Unexpected event"),
5826 // We test that in case of peer committing upfront to a script, if it doesn't change at closing, we sign
5827 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
5828 nodes[0].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
5829 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
5830 // We test that in case of peer committing upfront to a script, if it oesn't change at closing, we sign
5831 if let Ok(_) = nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown) {}
5832 else { assert!(false) }
5833 let events = nodes[2].node.get_and_clear_pending_msg_events();
5834 assert_eq!(events.len(), 1);
5836 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
5837 _ => panic!("Unexpected event"),
5840 // We test that if case of peer non-signaling we don't enforce committed script at channel opening
5841 let mut flags_no = LocalFeatures::new();
5842 flags_no.unset_upfront_shutdown_script();
5843 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags_no, flags.clone());
5844 nodes[0].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
5845 let mut node_1_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
5846 node_1_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
5847 if let Ok(_) = nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_1_shutdown) {}
5848 else { assert!(false) }
5849 let events = nodes[1].node.get_and_clear_pending_msg_events();
5850 assert_eq!(events.len(), 1);
5852 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
5853 _ => panic!("Unexpected event"),
5856 // We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
5857 // channel smoothly, opt-out is from channel initiator here
5858 let chan = create_announced_chan_between_nodes_with_value(&nodes, 1, 0, 1000000, 1000000, flags.clone(), flags.clone());
5859 nodes[1].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
5860 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
5861 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
5862 if let Ok(_) = nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown) {}
5863 else { assert!(false) }
5864 let events = nodes[0].node.get_and_clear_pending_msg_events();
5865 assert_eq!(events.len(), 1);
5867 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
5868 _ => panic!("Unexpected event"),
5871 //// We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
5872 //// channel smoothly
5873 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags.clone(), flags.clone());
5874 nodes[1].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
5875 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
5876 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
5877 if let Ok(_) = nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown) {}
5878 else { assert!(false) }
5879 let events = nodes[0].node.get_and_clear_pending_msg_events();
5880 assert_eq!(events.len(), 2);
5882 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
5883 _ => panic!("Unexpected event"),
5886 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
5887 _ => panic!("Unexpected event"),
5892 fn test_user_configurable_csv_delay() {
5893 // We test our channel constructors yield errors when we pass them absurd csv delay
5895 let mut low_our_to_self_config = UserConfig::new();
5896 low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
5897 let mut high_their_to_self_config = UserConfig::new();
5898 high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
5899 let nodes = create_network(2, &[Some(high_their_to_self_config.clone()), None]);
5901 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
5902 let keys_manager: Arc<KeysInterface> = Arc::new(KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new()), 10, 20));
5903 if let Err(error) = Channel::new_outbound(&test_utils::TestFeeEstimator { sat_per_kw: 253 }, &keys_manager, nodes[1].node.get_our_node_id(), 1000000, 1000000, 0, Arc::new(test_utils::TestLogger::new()), &low_our_to_self_config) {
5905 APIError::APIMisuseError { err } => { assert_eq!(err, "Configured with an unreasonable our_to_self_delay putting user funds at risks"); },
5906 _ => panic!("Unexpected event"),
5908 } else { assert!(false) }
5910 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
5911 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42).unwrap();
5912 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
5913 open_channel.to_self_delay = 200;
5914 if let Err(error) = Channel::new_from_req(&test_utils::TestFeeEstimator { sat_per_kw: 253 }, &keys_manager, nodes[1].node.get_our_node_id(), LocalFeatures::new(), &open_channel, 0, Arc::new(test_utils::TestLogger::new()), &low_our_to_self_config) {
5916 ChannelError::Close(err) => { assert_eq!(err, "Configured with an unreasonable our_to_self_delay putting user funds at risks"); },
5917 _ => panic!("Unexpected event"),
5919 } else { assert!(false); }
5921 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
5922 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42).unwrap();
5923 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), LocalFeatures::new(), &get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id())).unwrap();
5924 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
5925 accept_channel.to_self_delay = 200;
5926 if let Err(error) = nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), LocalFeatures::new(), &accept_channel) {
5927 if let Some(error) = error.action {
5929 ErrorAction::SendErrorMessage { msg } => {
5930 assert_eq!(msg.data,"They wanted our payments to be delayed by a needlessly long period");
5932 _ => { assert!(false); }
5934 } else { assert!(false); }
5935 } else { assert!(false); }
5937 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
5938 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42).unwrap();
5939 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
5940 open_channel.to_self_delay = 200;
5941 if let Err(error) = Channel::new_from_req(&test_utils::TestFeeEstimator { sat_per_kw: 253 }, &keys_manager, nodes[1].node.get_our_node_id(), LocalFeatures::new(), &open_channel, 0, Arc::new(test_utils::TestLogger::new()), &high_their_to_self_config) {
5943 ChannelError::Close(err) => { assert_eq!(err, "They wanted our payments to be delayed by a needlessly long period"); },
5944 _ => panic!("Unexpected event"),
5946 } else { assert!(false); }