Skip to content

Commit b385a40

Browse files
committed
Use TLV instead of explicit length for VecReadWrapper termination
VecReadWrapper is only used in TLVs so there is no need to prepend a length before writing/reading the objects - we can instead simply read until we reach the end of the TLV stream.
1 parent ccc8284 commit b385a40

File tree

2 files changed

+12
-9
lines changed

2 files changed

+12
-9
lines changed

lightning/src/ln/msgs.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ use ln::{PaymentPreimage, PaymentHash, PaymentSecret};
4646
pub(crate) const MAX_VALUE_MSAT: u64 = 21_000_000_0000_0000_000;
4747

4848
/// An error in decoding a message or struct.
49-
#[derive(Clone, Debug)]
49+
#[derive(Clone, Debug, PartialEq)]
5050
pub enum DecodeError {
5151
/// A version byte specified something we don't know how to handle.
5252
/// Includes unknown realm byte in an OnionHopData packet

lightning/src/util/ser.rs

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -249,28 +249,31 @@ impl<T: Readable> Readable for OptionDeserWrapper<T> {
249249
}
250250
}
251251

252-
const MAX_ALLOC_SIZE: u64 = 64*1024;
253-
252+
/// Wrapper to write each element of a Vec with no length prefix
254253
pub(crate) struct VecWriteWrapper<'a, T: Writeable>(pub &'a Vec<T>);
255254
impl<'a, T: Writeable> Writeable for VecWriteWrapper<'a, T> {
256255
#[inline]
257256
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
258-
(self.0.len() as u64).write(writer)?;
259257
for ref v in self.0.iter() {
260258
v.write(writer)?;
261259
}
262260
Ok(())
263261
}
264262
}
263+
264+
/// Wrapper to read elements from a given stream until it reaches the end of the stream.
265265
pub(crate) struct VecReadWrapper<T: Readable>(pub Vec<T>);
266266
impl<T: Readable> Readable for VecReadWrapper<T> {
267267
#[inline]
268-
fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
269-
let count: u64 = Readable::read(reader)?;
270-
let mut values = Vec::with_capacity(cmp::min(count, MAX_ALLOC_SIZE / (core::mem::size_of::<T>() as u64)) as usize);
271-
for _ in 0..count {
272-
match Readable::read(reader) {
268+
fn read<R: Read>(mut reader: &mut R) -> Result<Self, DecodeError> {
269+
let mut values = Vec::new();
270+
loop {
271+
let mut track_read = ReadTrackingReader::new(&mut reader);
272+
match Readable::read(&mut track_read) {
273273
Ok(v) => { values.push(v); },
274+
// If we failed to read any bytes at all, we reached the end of our TLV
275+
// stream and have simply exhausted all entries.
276+
Err(ref e) if e == &DecodeError::ShortRead && !track_read.have_read => break,
274277
Err(e) => return Err(e),
275278
}
276279
}

0 commit comments

Comments
 (0)