Skip to content

Commit 29727a3

Browse files
authored
Merge pull request #1465 from tnull/2022-05-encode-update-type-bytes
Encode & test `channel_update` message type in failure messages.
2 parents b4fdb87 + 6d8be70 commit 29727a3

File tree

4 files changed

+63
-14
lines changed

4 files changed

+63
-14
lines changed

lightning/src/ln/channelmanager.rs

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ use ln::msgs;
4848
use ln::msgs::NetAddress;
4949
use ln::onion_utils;
5050
use ln::msgs::{ChannelMessageHandler, DecodeError, LightningError, MAX_VALUE_MSAT, OptionalField};
51+
use ln::wire::Encode;
5152
use chain::keysinterface::{Sign, KeysInterface, KeysManager, InMemorySigner, Recipient};
5253
use util::config::UserConfig;
5354
use util::events::{EventHandler, EventsProvider, MessageSendEvent, MessageSendEventsProvider, ClosureReason};
@@ -2249,7 +2250,7 @@ impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelMana
22492250
break None;
22502251
}
22512252
{
2252-
let mut res = VecWriter(Vec::with_capacity(chan_update.serialized_length() + 8 + 2));
2253+
let mut res = VecWriter(Vec::with_capacity(chan_update.serialized_length() + 2 + 8 + 2));
22532254
if let Some(chan_update) = chan_update {
22542255
if code == 0x1000 | 11 || code == 0x1000 | 12 {
22552256
msg.amount_msat.write(&mut res).expect("Writes cannot fail");
@@ -2261,7 +2262,8 @@ impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelMana
22612262
// TODO: underspecified, follow https://github.com/lightningnetwork/lightning-rfc/issues/791
22622263
0u16.write(&mut res).expect("Writes cannot fail");
22632264
}
2264-
(chan_update.serialized_length() as u16).write(&mut res).expect("Writes cannot fail");
2265+
(chan_update.serialized_length() as u16 + 2).write(&mut res).expect("Writes cannot fail");
2266+
msgs::ChannelUpdate::TYPE.write(&mut res).expect("Writes cannot fail");
22652267
chan_update.write(&mut res).expect("Writes cannot fail");
22662268
}
22672269
return_err!(err, code, &res.0[..]);
@@ -3543,12 +3545,13 @@ impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelMana
35433545
fn get_htlc_temp_fail_err_and_data(&self, desired_err_code: u16, scid: u64, chan: &Channel<Signer>) -> (u16, Vec<u8>) {
35443546
debug_assert_eq!(desired_err_code & 0x1000, 0x1000);
35453547
if let Ok(upd) = self.get_channel_update_for_onion(scid, chan) {
3546-
let mut enc = VecWriter(Vec::with_capacity(upd.serialized_length() + 4));
3548+
let mut enc = VecWriter(Vec::with_capacity(upd.serialized_length() + 6));
35473549
if desired_err_code == 0x1000 | 20 {
35483550
// TODO: underspecified, follow https://github.com/lightning/bolts/issues/791
35493551
0u16.write(&mut enc).expect("Writes cannot fail");
35503552
}
3551-
(upd.serialized_length() as u16).write(&mut enc).expect("Writes cannot fail");
3553+
(upd.serialized_length() as u16 + 2).write(&mut enc).expect("Writes cannot fail");
3554+
msgs::ChannelUpdate::TYPE.write(&mut enc).expect("Writes cannot fail");
35523555
upd.write(&mut enc).expect("Writes cannot fail");
35533556
(desired_err_code, enc.0)
35543557
} else {

lightning/src/ln/onion_route_tests.rs

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ use routing::router::{get_route, PaymentParameters, Route, RouteHint, RouteHintH
2121
use ln::features::{InitFeatures, InvoiceFeatures, NodeFeatures};
2222
use ln::msgs;
2323
use ln::msgs::{ChannelMessageHandler, ChannelUpdate, OptionalField};
24+
use ln::wire::Encode;
2425
use util::events::{Event, MessageSendEvent, MessageSendEventsProvider};
2526
use util::ser::{Writeable, Writer};
2627
use util::{byte_utils, test_utils};
@@ -438,13 +439,29 @@ fn test_onion_failure() {
438439
Some(BADONION|PERM|6), None, Some(short_channel_id));
439440

440441
let short_channel_id = channels[1].0.contents.short_channel_id;
442+
let chan_update = ChannelUpdate::dummy(short_channel_id);
443+
444+
let mut err_data = Vec::new();
445+
err_data.extend_from_slice(&(chan_update.serialized_length() as u16 + 2).to_be_bytes());
446+
err_data.extend_from_slice(&ChannelUpdate::TYPE.to_be_bytes());
447+
err_data.extend_from_slice(&chan_update.encode());
448+
run_onion_failure_test_with_fail_intercept("temporary_channel_failure", 100, &nodes, &route, &payment_hash, &payment_secret, |msg| {
449+
msg.amount_msat -= 1;
450+
}, |msg| {
451+
let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
452+
let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
453+
msg.reason = onion_utils::build_first_hop_failure_packet(onion_keys[0].shared_secret.as_ref(), UPDATE|7, &err_data);
454+
}, ||{}, true, Some(UPDATE|7), Some(NetworkUpdate::ChannelUpdateMessage{msg: chan_update.clone()}), Some(short_channel_id));
455+
456+
// Check we can still handle onion failures that include channel updates without a type prefix
457+
let err_data_without_type = chan_update.encode_with_len();
441458
run_onion_failure_test_with_fail_intercept("temporary_channel_failure", 100, &nodes, &route, &payment_hash, &payment_secret, |msg| {
442459
msg.amount_msat -= 1;
443460
}, |msg| {
444461
let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
445462
let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
446-
msg.reason = onion_utils::build_first_hop_failure_packet(onion_keys[0].shared_secret.as_ref(), UPDATE|7, &ChannelUpdate::dummy(short_channel_id).encode_with_len()[..]);
447-
}, ||{}, true, Some(UPDATE|7), Some(NetworkUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy(short_channel_id)}), Some(short_channel_id));
463+
msg.reason = onion_utils::build_first_hop_failure_packet(onion_keys[0].shared_secret.as_ref(), UPDATE|7, &err_data_without_type);
464+
}, ||{}, true, Some(UPDATE|7), Some(NetworkUpdate::ChannelUpdateMessage{msg: chan_update}), Some(short_channel_id));
448465

449466
let short_channel_id = channels[1].0.contents.short_channel_id;
450467
run_onion_failure_test_with_fail_intercept("permanent_channel_failure", 100, &nodes, &route, &payment_hash, &payment_secret, |msg| {
@@ -1097,11 +1114,15 @@ fn test_phantom_dust_exposure_failure() {
10971114
commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
10981115

10991116
// Ensure the payment fails with the expected error.
1100-
let mut error_data = channel.1.encode_with_len();
1117+
let mut err_data = Vec::new();
1118+
err_data.extend_from_slice(&(channel.1.serialized_length() as u16 + 2).to_be_bytes());
1119+
err_data.extend_from_slice(&ChannelUpdate::TYPE.to_be_bytes());
1120+
err_data.extend_from_slice(&channel.1.encode());
1121+
11011122
let mut fail_conditions = PaymentFailedConditions::new()
11021123
.blamed_scid(channel.0.contents.short_channel_id)
11031124
.blamed_chan_closed(false)
1104-
.expected_htlc_error_data(0x1000 | 7, &error_data);
1125+
.expected_htlc_error_data(0x1000 | 7, &err_data);
11051126
expect_payment_failed_conditions!(nodes[0], payment_hash, false, fail_conditions);
11061127
}
11071128

lightning/src/ln/onion_utils.rs

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
use ln::{PaymentHash, PaymentPreimage, PaymentSecret};
1111
use ln::channelmanager::HTLCSource;
1212
use ln::msgs;
13+
use ln::wire::Encode;
1314
use routing::network_graph::NetworkUpdate;
1415
use routing::router::RouteHop;
1516
use util::chacha20::{ChaCha20, ChaChaReader};
@@ -404,7 +405,21 @@ pub(super) fn process_onion_failure<T: secp256k1::Signing, L: Deref>(secp_ctx: &
404405
else if error_code & UPDATE == UPDATE {
405406
if let Some(update_len_slice) = err_packet.failuremsg.get(debug_field_size+2..debug_field_size+4) {
406407
let update_len = u16::from_be_bytes(update_len_slice.try_into().expect("len is 2")) as usize;
407-
if let Some(update_slice) = err_packet.failuremsg.get(debug_field_size + 4..debug_field_size + 4 + update_len) {
408+
if let Some(mut update_slice) = err_packet.failuremsg.get(debug_field_size + 4..debug_field_size + 4 + update_len) {
409+
// Historically, the BOLTs were unclear if the message type
410+
// bytes should be included here or not. The BOLTs have now
411+
// been updated to indicate that they *are* included, but many
412+
// nodes still send messages without the type bytes, so we
413+
// support both here.
414+
// TODO: Switch to hard require the type prefix, as the current
415+
// permissiveness introduces the (although small) possibility
416+
// that we fail to decode legitimate channel updates that
417+
// happen to start with ChannelUpdate::TYPE, i.e., [0x01, 0x02].
418+
if update_slice.len() > 2 && update_slice[0..2] == msgs::ChannelUpdate::TYPE.to_be_bytes() {
419+
update_slice = &update_slice[2..];
420+
} else {
421+
log_trace!(logger, "Failure provided features a channel update without type prefix. Deprecated, but allowing for now.");
422+
}
408423
if let Ok(chan_update) = msgs::ChannelUpdate::read(&mut Cursor::new(&update_slice)) {
409424
// if channel_update should NOT have caused the failure:
410425
// MAY treat the channel_update as invalid.
@@ -434,6 +449,8 @@ pub(super) fn process_onion_failure<T: secp256k1::Signing, L: Deref>(secp_ctx: &
434449
// short channel id.
435450
if failing_route_hop.short_channel_id == chan_update.contents.short_channel_id {
436451
short_channel_id = Some(failing_route_hop.short_channel_id);
452+
} else {
453+
log_info!(logger, "Node provided a channel_update for which it was not authoritative, ignoring.");
437454
}
438455
network_update = Some(NetworkUpdate::ChannelUpdateMessage {
439456
msg: chan_update,
@@ -478,10 +495,10 @@ pub(super) fn process_onion_failure<T: secp256k1::Signing, L: Deref>(secp_ctx: &
478495

479496
let (description, title) = errors::get_onion_error_description(error_code);
480497
if debug_field_size > 0 && err_packet.failuremsg.len() >= 4 + debug_field_size {
481-
log_warn!(logger, "Onion Error[from {}: {}({:#x}) {}({})] {}", route_hop.pubkey, title, error_code, debug_field, log_bytes!(&err_packet.failuremsg[4..4+debug_field_size]), description);
498+
log_info!(logger, "Onion Error[from {}: {}({:#x}) {}({})] {}", route_hop.pubkey, title, error_code, debug_field, log_bytes!(&err_packet.failuremsg[4..4+debug_field_size]), description);
482499
}
483500
else {
484-
log_warn!(logger, "Onion Error[from {}: {}({:#x})] {}", route_hop.pubkey, title, error_code, description);
501+
log_info!(logger, "Onion Error[from {}: {}({:#x})] {}", route_hop.pubkey, title, error_code, description);
485502
}
486503
} else {
487504
// Useless packet that we can't use but it passed HMAC, so it

lightning/src/ln/priv_short_conf_tests.rs

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,8 @@ use routing::network_graph::RoutingFees;
1919
use routing::router::{PaymentParameters, RouteHint, RouteHintHop};
2020
use ln::features::{InitFeatures, InvoiceFeatures};
2121
use ln::msgs;
22-
use ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, OptionalField};
22+
use ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, OptionalField, ChannelUpdate};
23+
use ln::wire::Encode;
2324
use util::enforcing_trait_impls::EnforcingSigner;
2425
use util::events::{Event, MessageSendEvent, MessageSendEventsProvider};
2526
use util::config::UserConfig;
@@ -531,9 +532,14 @@ fn test_scid_alias_returned() {
531532
let signature = Secp256k1::new().sign_ecdsa(&hash_to_message!(&msg_hash[..]), &nodes[1].keys_manager.get_node_secret(Recipient::Node).unwrap());
532533
let msg = msgs::ChannelUpdate { signature, contents };
533534

535+
let mut err_data = Vec::new();
536+
err_data.extend_from_slice(&(msg.serialized_length() as u16 + 2).to_be_bytes());
537+
err_data.extend_from_slice(&ChannelUpdate::TYPE.to_be_bytes());
538+
err_data.extend_from_slice(&msg.encode());
539+
534540
expect_payment_failed_conditions!(nodes[0], payment_hash, false,
535541
PaymentFailedConditions::new().blamed_scid(last_hop[0].inbound_scid_alias.unwrap())
536-
.blamed_chan_closed(false).expected_htlc_error_data(0x1000|7, &msg.encode_with_len()));
542+
.blamed_chan_closed(false).expected_htlc_error_data(0x1000|7, &err_data));
537543

538544
route.paths[0][1].fee_msat = 10_000; // Reset to the correct payment amount
539545
route.paths[0][0].fee_msat = 0; // But set fee paid to the middle hop to 0
@@ -551,7 +557,9 @@ fn test_scid_alias_returned() {
551557

552558
let mut err_data = Vec::new();
553559
err_data.extend_from_slice(&10_000u64.to_be_bytes());
554-
err_data.extend_from_slice(&msg.encode_with_len());
560+
err_data.extend_from_slice(&(msg.serialized_length() as u16 + 2).to_be_bytes());
561+
err_data.extend_from_slice(&ChannelUpdate::TYPE.to_be_bytes());
562+
err_data.extend_from_slice(&msg.encode());
555563
expect_payment_failed_conditions!(nodes[0], payment_hash, false,
556564
PaymentFailedConditions::new().blamed_scid(last_hop[0].inbound_scid_alias.unwrap())
557565
.blamed_chan_closed(false).expected_htlc_error_data(0x1000|12, &err_data));

0 commit comments

Comments
 (0)