Skip to content

Commit adf112c

Browse files
committed
Update Padding struct to contain padding length.
1. This allows setting the length of padding at the time of writing. 2. This will be used in the following commit to allow setting the padding for blinded message paths, and blinded payment paths.
1 parent 78c0eaa commit adf112c

File tree

1 file changed

+33
-6
lines changed

1 file changed

+33
-6
lines changed

lightning/src/blinded_path/utils.rs

Lines changed: 33 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ use crate::ln::msgs::DecodeError;
2020
use crate::ln::onion_utils;
2121
use crate::onion_message::messenger::Destination;
2222
use crate::crypto::streams::ChaChaPolyWriteAdapter;
23-
use crate::util::ser::{Readable, Writeable};
23+
use crate::util::ser::{Readable, Writeable, Writer};
2424

2525
use crate::io;
2626

@@ -135,17 +135,44 @@ fn encrypt_payload<P: Writeable>(payload: P, encrypted_tlvs_rho: [u8; 32]) -> Ve
135135
write_adapter.encode()
136136
}
137137

138-
/// Blinded path encrypted payloads may be padded to ensure they are equal length.
139-
///
140-
/// Reads padding to the end, ignoring what's read.
141-
pub(crate) struct Padding {}
138+
/// Represents optional padding for encrypted payloads.
139+
/// Padding is used to ensure payloads have a consistent length.
140+
pub(crate) struct Padding {
141+
length: usize,
142+
}
143+
144+
impl Padding {
145+
/// Creates a new [`Padding`] instance with a specified size.
146+
/// Use this method when defining the padding size before writing
147+
/// an encrypted payload.
148+
pub fn new(length: usize) -> Self {
149+
Self { length }
150+
}
151+
}
152+
142153
impl Readable for Padding {
143154
#[inline]
144155
fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
145156
loop {
146157
let mut buf = [0; 8192];
147158
if reader.read(&mut buf[..])? == 0 { break; }
148159
}
149-
Ok(Self {})
160+
Ok(Self::new(0))
161+
}
162+
}
163+
164+
impl Writeable for Padding {
165+
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
166+
const BUFFER_SIZE: usize = 1024;
167+
let buffer = [0u8; BUFFER_SIZE];
168+
169+
let mut remaining = self.length;
170+
loop {
171+
let to_write = core::cmp::min(remaining, BUFFER_SIZE);
172+
writer.write_all(&buffer[..to_write])?;
173+
remaining -= to_write;
174+
if remaining == 0 { break; }
175+
}
176+
Ok(())
150177
}
151178
}

0 commit comments

Comments
 (0)