Skip to content

Commit 43de15e

Browse files
authored
Merge pull request #3177 from shaavan/padding
Introduce Padding for Payment and Message Blinded Tlvs
2 parents 071aa85 + f8ffc1a commit 43de15e

File tree

6 files changed

+210
-30
lines changed

6 files changed

+210
-30
lines changed

lightning/src/blinded_path/message.rs

+18-6
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ use bitcoin::secp256k1::{self, PublicKey, Secp256k1, SecretKey};
1414
#[allow(unused_imports)]
1515
use crate::prelude::*;
1616

17-
use crate::blinded_path::utils;
17+
use crate::blinded_path::utils::{self, BlindedPathWithPadding};
1818
use crate::blinded_path::{BlindedHop, BlindedPath, Direction, IntroductionNode, NodeIdLookUp};
1919
use crate::crypto::streams::ChaChaPolyReadAdapter;
2020
use crate::io;
@@ -265,7 +265,6 @@ impl Writeable for ForwardTlvs {
265265
NextMessageHop::NodeId(pubkey) => (Some(pubkey), None),
266266
NextMessageHop::ShortChannelId(scid) => (None, Some(scid)),
267267
};
268-
// TODO: write padding
269268
encode_tlv_stream!(writer, {
270269
(2, short_channel_id, option),
271270
(4, next_node_id, option),
@@ -277,7 +276,6 @@ impl Writeable for ForwardTlvs {
277276

278277
impl Writeable for ReceiveTlvs {
279278
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
280-
// TODO: write padding
281279
encode_tlv_stream!(writer, {
282280
(65537, self.context, option),
283281
});
@@ -495,6 +493,10 @@ impl_writeable_tlv_based!(DNSResolverContext, {
495493
(0, nonce, required),
496494
});
497495

496+
/// Represents the padding round off size (in bytes) that is used
497+
/// to pad message blinded path's [`BlindedHop`]
498+
pub(crate) const MESSAGE_PADDING_ROUND_OFF: usize = 100;
499+
498500
/// Construct blinded onion message hops for the given `intermediate_nodes` and `recipient_node_id`.
499501
pub(super) fn blinded_hops<T: secp256k1::Signing + secp256k1::Verification>(
500502
secp_ctx: &Secp256k1<T>, intermediate_nodes: &[MessageForwardNode],
@@ -504,6 +506,8 @@ pub(super) fn blinded_hops<T: secp256k1::Signing + secp256k1::Verification>(
504506
.iter()
505507
.map(|node| node.node_id)
506508
.chain(core::iter::once(recipient_node_id));
509+
let is_compact = intermediate_nodes.iter().any(|node| node.short_channel_id.is_some());
510+
507511
let tlvs = pks
508512
.clone()
509513
.skip(1) // The first node's TLVs contains the next node's pubkey
@@ -517,7 +521,15 @@ pub(super) fn blinded_hops<T: secp256k1::Signing + secp256k1::Verification>(
517521
})
518522
.chain(core::iter::once(ControlTlvs::Receive(ReceiveTlvs { context: Some(context) })));
519523

520-
let path = pks.zip(tlvs);
521-
522-
utils::construct_blinded_hops(secp_ctx, path, session_priv)
524+
if is_compact {
525+
let path = pks.zip(tlvs);
526+
utils::construct_blinded_hops(secp_ctx, path, session_priv)
527+
} else {
528+
let path =
529+
pks.zip(tlvs.map(|tlv| BlindedPathWithPadding {
530+
tlvs: tlv,
531+
round_off: MESSAGE_PADDING_ROUND_OFF,
532+
}));
533+
utils::construct_blinded_hops(secp_ctx, path, session_priv)
534+
}
523535
}

lightning/src/blinded_path/payment.rs

+12-5
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ use bitcoin::hashes::sha256::Hash as Sha256;
1414
use bitcoin::secp256k1::ecdh::SharedSecret;
1515
use bitcoin::secp256k1::{self, PublicKey, Secp256k1, SecretKey};
1616

17-
use crate::blinded_path::utils;
17+
use crate::blinded_path::utils::{self, BlindedPathWithPadding};
1818
use crate::blinded_path::{BlindedHop, BlindedPath, IntroductionNode, NodeIdLookUp};
1919
use crate::crypto::streams::ChaChaPolyReadAdapter;
2020
use crate::io;
@@ -508,7 +508,6 @@ impl Writeable for UnauthenticatedReceiveTlvs {
508508

509509
impl<'a> Writeable for BlindedPaymentTlvsRef<'a> {
510510
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
511-
// TODO: write padding
512511
match self {
513512
Self::Forward(tlvs) => tlvs.write(w)?,
514513
Self::Receive(tlvs) => tlvs.write(w)?,
@@ -520,7 +519,10 @@ impl<'a> Writeable for BlindedPaymentTlvsRef<'a> {
520519
impl Readable for BlindedPaymentTlvs {
521520
fn read<R: io::Read>(r: &mut R) -> Result<Self, DecodeError> {
522521
_init_and_read_tlv_stream!(r, {
523-
(1, _padding, option),
522+
// Reasoning: Padding refers to filler data added to a packet to increase
523+
// its size and obscure its actual length. Since padding contains no meaningful
524+
// information, we can safely omit reading it here.
525+
// (1, _padding, option),
524526
(2, scid, option),
525527
(8, next_blinding_override, option),
526528
(10, payment_relay, option),
@@ -530,7 +532,6 @@ impl Readable for BlindedPaymentTlvs {
530532
(65537, payment_context, option),
531533
(65539, authentication, option),
532534
});
533-
let _padding: Option<utils::Padding> = _padding;
534535

535536
if let Some(short_channel_id) = scid {
536537
if payment_secret.is_some() {
@@ -559,6 +560,10 @@ impl Readable for BlindedPaymentTlvs {
559560
}
560561
}
561562

563+
/// Represents the padding round off size (in bytes) that
564+
/// is used to pad payment bilnded path's [`BlindedHop`]
565+
pub(crate) const PAYMENT_PADDING_ROUND_OFF: usize = 30;
566+
562567
/// Construct blinded payment hops for the given `intermediate_nodes` and payee info.
563568
pub(super) fn blinded_hops<T: secp256k1::Signing + secp256k1::Verification>(
564569
secp_ctx: &Secp256k1<T>, intermediate_nodes: &[PaymentForwardNode], payee_node_id: PublicKey,
@@ -571,7 +576,9 @@ pub(super) fn blinded_hops<T: secp256k1::Signing + secp256k1::Verification>(
571576
.map(|node| BlindedPaymentTlvsRef::Forward(&node.tlvs))
572577
.chain(core::iter::once(BlindedPaymentTlvsRef::Receive(&payee_tlvs)));
573578

574-
let path = pks.zip(tlvs);
579+
let path = pks.zip(
580+
tlvs.map(|tlv| BlindedPathWithPadding { tlvs: tlv, round_off: PAYMENT_PADDING_ROUND_OFF }),
581+
);
575582

576583
utils::construct_blinded_hops(secp_ctx, path, session_priv)
577584
}

lightning/src/blinded_path/utils.rs

+74-13
Original file line numberDiff line numberDiff line change
@@ -18,12 +18,10 @@ use bitcoin::secp256k1::{self, PublicKey, Scalar, Secp256k1, SecretKey};
1818
use super::message::BlindedMessagePath;
1919
use super::{BlindedHop, BlindedPath};
2020
use crate::crypto::streams::ChaChaPolyWriteAdapter;
21-
use crate::ln::msgs::DecodeError;
21+
use crate::io;
2222
use crate::ln::onion_utils;
2323
use crate::onion_message::messenger::Destination;
24-
use crate::util::ser::{Readable, Writeable};
25-
26-
use crate::io;
24+
use crate::util::ser::{Writeable, Writer};
2725

2826
use core::borrow::Borrow;
2927

@@ -196,19 +194,82 @@ fn encrypt_payload<P: Writeable>(payload: P, encrypted_tlvs_rho: [u8; 32]) -> Ve
196194
write_adapter.encode()
197195
}
198196

199-
/// Blinded path encrypted payloads may be padded to ensure they are equal length.
197+
/// A data structure used exclusively to pad blinded path payloads, ensuring they are of
198+
/// equal length. Padding is written at Type 1 for compatibility with the lightning specification.
200199
///
201-
/// Reads padding to the end, ignoring what's read.
202-
pub(crate) struct Padding {}
203-
impl Readable for Padding {
204-
#[inline]
205-
fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
200+
/// For more details, see the [BOLTs Specification - Encrypted Recipient Data](https://github.com./lightning/bolts/blob/8707471dbc23245fb4d84c5f5babac1197f1583e/04-onion-routing.md#inside-encrypted_recipient_data-encrypted_data_tlv).
201+
pub(crate) struct BlindedPathPadding {
202+
length: usize,
203+
}
204+
205+
impl BlindedPathPadding {
206+
/// Creates a new [`BlindedPathPadding`] instance with a specified size.
207+
/// Use this method when defining the padding size before writing
208+
/// an encrypted payload.
209+
pub fn new(length: usize) -> Self {
210+
Self { length }
211+
}
212+
}
213+
214+
impl Writeable for BlindedPathPadding {
215+
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
216+
const BUFFER_SIZE: usize = 1024;
217+
let buffer = [0u8; BUFFER_SIZE];
218+
219+
let mut remaining = self.length;
206220
loop {
207-
let mut buf = [0; 8192];
208-
if reader.read(&mut buf[..])? == 0 {
221+
let to_write = core::cmp::min(remaining, BUFFER_SIZE);
222+
writer.write_all(&buffer[..to_write])?;
223+
remaining -= to_write;
224+
if remaining == 0 {
209225
break;
210226
}
211227
}
212-
Ok(Self {})
228+
Ok(())
229+
}
230+
}
231+
232+
/// Padding storage requires two extra bytes:
233+
/// - One byte for the type.
234+
/// - One byte for the padding length.
235+
/// This constant accounts for that overhead.
236+
const TLV_OVERHEAD: usize = 2;
237+
238+
/// A generic struct that applies padding to blinded path TLVs, rounding their size off to `round_off`
239+
pub(crate) struct BlindedPathWithPadding<T: Writeable> {
240+
pub(crate) tlvs: T,
241+
pub(crate) round_off: usize,
242+
}
243+
244+
impl<T: Writeable> Writeable for BlindedPathWithPadding<T> {
245+
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
246+
let tlv_length = self.tlvs.serialized_length();
247+
let total_length = tlv_length + TLV_OVERHEAD;
248+
249+
let padding_length =
250+
(total_length + self.round_off - 1) / self.round_off * self.round_off - total_length;
251+
252+
let padding = Some(BlindedPathPadding::new(padding_length));
253+
254+
encode_tlv_stream!(writer, {
255+
(1, padding, option),
256+
});
257+
258+
self.tlvs.write(writer)
213259
}
214260
}
261+
262+
#[cfg(test)]
263+
/// Checks if all the packets in the blinded path are properly padded.
264+
pub fn is_padded(hops: &[BlindedHop], padding_round_off: usize) -> bool {
265+
let first_hop = hops.first().expect("BlindedPath must have at least one hop");
266+
let first_payload_size = first_hop.encrypted_payload.len();
267+
268+
// The unencrypted payload data is padded before getting encrypted.
269+
// Assuming the first payload is padded properly, get the extra data length.
270+
let extra_length = first_payload_size % padding_round_off;
271+
hops.iter().all(|hop| {
272+
// Check that every packet is padded to the round off length subtracting the extra length.
273+
(hop.encrypted_payload.len() - extra_length) % padding_round_off == 0
274+
})
275+
}

lightning/src/ln/blinded_payment_tests.rs

+41-2
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,8 @@ use bitcoin::secp256k1::{PublicKey, Scalar, Secp256k1, SecretKey, schnorr};
1313
use bitcoin::secp256k1::ecdh::SharedSecret;
1414
use bitcoin::secp256k1::ecdsa::{RecoverableSignature, Signature};
1515
use crate::blinded_path;
16-
use crate::blinded_path::payment::{BlindedPaymentPath, Bolt12RefundContext, PaymentForwardNode, ForwardTlvs, PaymentConstraints, PaymentContext, PaymentRelay, UnauthenticatedReceiveTlvs};
16+
use crate::blinded_path::payment::{BlindedPaymentPath, Bolt12RefundContext, ForwardTlvs, PaymentConstraints, PaymentContext, PaymentForwardNode, PaymentRelay, UnauthenticatedReceiveTlvs, PAYMENT_PADDING_ROUND_OFF};
17+
use crate::blinded_path::utils::is_padded;
1718
use crate::events::{Event, HTLCDestination, PaymentFailureReason};
1819
use crate::ln::types::ChannelId;
1920
use crate::types::payment::{PaymentHash, PaymentSecret};
@@ -367,7 +368,7 @@ fn do_forward_checks_failure(check: ForwardCheckFail, intro_fails: bool) {
367368
let mut route_params = get_blinded_route_parameters(amt_msat, payment_secret, 1, 1_0000_0000,
368369
nodes.iter().skip(1).map(|n| n.node.get_our_node_id()).collect(),
369370
&[&chan_upd_1_2, &chan_upd_2_3], &chanmon_cfgs[3].keys_manager);
370-
route_params.payment_params.max_path_length = 17;
371+
route_params.payment_params.max_path_length = 16;
371372

372373
let route = get_route(&nodes[0], &route_params).unwrap();
373374
node_cfgs[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
@@ -892,6 +893,8 @@ fn do_multi_hop_receiver_fail(check: ReceiveCheckFail) {
892893
nodes.iter().skip(1).map(|n| n.node.get_our_node_id()).collect(), &[&chan_upd_1_2],
893894
&chanmon_cfgs[2].keys_manager);
894895

896+
route_params.payment_params.max_path_length = 17;
897+
895898
let route = if check == ReceiveCheckFail::ProcessPendingHTLCsCheck {
896899
let mut route = get_route(&nodes[0], &route_params).unwrap();
897900
// Set the final CLTV expiry too low to trigger the failure in process_pending_htlc_forwards.
@@ -1446,6 +1449,42 @@ fn fails_receive_tlvs_authentication() {
14461449
);
14471450
}
14481451

1452+
#[test]
1453+
fn blinded_payment_path_padding() {
1454+
// Make sure that for a blinded payment path, all encrypted payloads are padded to equal lengths.
1455+
let chanmon_cfgs = create_chanmon_cfgs(5);
1456+
let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
1457+
let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
1458+
let mut nodes = create_network(5, &node_cfgs, &node_chanmgrs);
1459+
create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
1460+
create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1_000_000, 0);
1461+
let chan_upd_2_3 = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 1_000_000, 0).0.contents;
1462+
let chan_upd_3_4 = create_announced_chan_between_nodes_with_value(&nodes, 3, 4, 1_000_000, 0).0.contents;
1463+
1464+
// Get all our nodes onto the same height so payments don't fail for CLTV violations.
1465+
connect_blocks(&nodes[0], nodes[4].best_block_info().1 - nodes[0].best_block_info().1);
1466+
connect_blocks(&nodes[1], nodes[4].best_block_info().1 - nodes[1].best_block_info().1);
1467+
connect_blocks(&nodes[2], nodes[4].best_block_info().1 - nodes[2].best_block_info().1);
1468+
assert_eq!(nodes[4].best_block_info().1, nodes[3].best_block_info().1);
1469+
1470+
let amt_msat = 5000;
1471+
let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[4], Some(amt_msat), None);
1472+
1473+
let blinded_path = blinded_payment_path(payment_secret, 1, 1_0000_0000,
1474+
nodes.iter().skip(2).map(|n| n.node.get_our_node_id()).collect(), &[&chan_upd_2_3, &chan_upd_3_4],
1475+
&chanmon_cfgs[4].keys_manager
1476+
);
1477+
1478+
assert!(is_padded(&blinded_path.blinded_hops(), PAYMENT_PADDING_ROUND_OFF));
1479+
1480+
let route_params = RouteParameters::from_payment_params_and_value(PaymentParameters::blinded(vec![blinded_path]), amt_msat);
1481+
1482+
nodes[0].node.send_payment(payment_hash, RecipientOnionFields::spontaneous_empty(), PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap();
1483+
check_added_monitors(&nodes[0], 1);
1484+
pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2], &nodes[3], &nodes[4]]], amt_msat, payment_hash, payment_secret);
1485+
claim_payment(&nodes[0], &[&nodes[1], &nodes[2], &nodes[3], &nodes[4]], payment_preimage);
1486+
}
1487+
14491488
fn secret_from_hex(hex: &str) -> SecretKey {
14501489
SecretKey::from_slice(&<Vec<u8>>::from_hex(hex).unwrap()).unwrap()
14511490
}

lightning/src/onion_message/functional_tests.rs

+61-1
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,9 @@ use super::offers::{OffersMessage, OffersMessageHandler};
2121
use super::packet::{OnionMessageContents, Packet};
2222
use crate::blinded_path::message::{
2323
AsyncPaymentsContext, BlindedMessagePath, DNSResolverContext, MessageContext,
24-
MessageForwardNode, OffersContext,
24+
MessageForwardNode, OffersContext, MESSAGE_PADDING_ROUND_OFF,
2525
};
26+
use crate::blinded_path::utils::is_padded;
2627
use crate::blinded_path::EmptyNodeIdLookUp;
2728
use crate::events::{Event, EventsProvider};
2829
use crate::ln::msgs::{self, BaseMessageHandler, DecodeError, OnionMessageHandler};
@@ -596,6 +597,65 @@ fn too_big_packet_error() {
596597
assert_eq!(err, SendError::TooBigPacket);
597598
}
598599

600+
#[test]
601+
fn test_blinded_path_padding_for_full_length_path() {
602+
// Check that for a full blinded path, all encrypted payload are padded to rounded-off length.
603+
let nodes = create_nodes(4);
604+
let test_msg = TestCustomMessage::Pong;
605+
606+
let secp_ctx = Secp256k1::new();
607+
let intermediate_nodes = [
608+
MessageForwardNode { node_id: nodes[1].node_id, short_channel_id: None },
609+
MessageForwardNode { node_id: nodes[2].node_id, short_channel_id: None },
610+
];
611+
// Update the context to create a larger final receive TLVs, ensuring that
612+
// the hop sizes vary before padding.
613+
let context = MessageContext::Custom(vec![0u8; 42]);
614+
let blinded_path = BlindedMessagePath::new(
615+
&intermediate_nodes,
616+
nodes[3].node_id,
617+
context,
618+
&*nodes[3].entropy_source,
619+
&secp_ctx,
620+
)
621+
.unwrap();
622+
623+
assert!(is_padded(&blinded_path.blinded_hops(), MESSAGE_PADDING_ROUND_OFF));
624+
625+
let destination = Destination::BlindedPath(blinded_path);
626+
let instructions = MessageSendInstructions::WithoutReplyPath { destination };
627+
628+
nodes[0].messenger.send_onion_message(test_msg, instructions).unwrap();
629+
nodes[3].custom_message_handler.expect_message(TestCustomMessage::Pong);
630+
pass_along_path(&nodes);
631+
}
632+
633+
#[test]
634+
fn test_blinded_path_no_padding_for_compact_path() {
635+
// Check that for a compact blinded path, no padding is applied.
636+
let nodes = create_nodes(4);
637+
let secp_ctx = Secp256k1::new();
638+
639+
// Include some short_channel_id, so that MessageRouter uses this to create compact blinded paths.
640+
let intermediate_nodes = [
641+
MessageForwardNode { node_id: nodes[1].node_id, short_channel_id: Some(24) },
642+
MessageForwardNode { node_id: nodes[2].node_id, short_channel_id: Some(25) },
643+
];
644+
// Update the context to create a larger final receive TLVs, ensuring that
645+
// the hop sizes vary before padding.
646+
let context = MessageContext::Custom(vec![0u8; 42]);
647+
let blinded_path = BlindedMessagePath::new(
648+
&intermediate_nodes,
649+
nodes[3].node_id,
650+
context,
651+
&*nodes[3].entropy_source,
652+
&secp_ctx,
653+
)
654+
.unwrap();
655+
656+
assert!(!is_padded(&blinded_path.blinded_hops(), MESSAGE_PADDING_ROUND_OFF));
657+
}
658+
599659
#[test]
600660
fn we_are_intro_node() {
601661
// If we are sending straight to a blinded path and we are the introduction node, we need to

0 commit comments

Comments
 (0)