Skip to content

Commit 0e30c91

Browse files
committed
Add a macro which implements Readable/Writeable using TLVs only
This also includes a `VecWriteWrapper` and `VecReadWrapper` which implements serialization for any `Readable`/`Writeable` type that is in a Vec. We do this instead of implementing `Readable`/`Writeable` directly as there isn't always a univerally-defined way to serialize a Vec and this makes things more explicit. Finally, this tweaks existing macros (and in the new macros) to support a trailing `,` after a list, eg `write_tlv_fields!(stream, {(0, a),}, {});` whereas previously the trailing `,` after the `(0, a)` would be a compile-error.
1 parent bc290aa commit 0e30c91

File tree

2 files changed

+101
-2
lines changed

2 files changed

+101
-2
lines changed

lightning/src/util/ser.rs

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -222,6 +222,33 @@ pub trait MaybeReadable
222222
fn read<R: Read>(reader: &mut R) -> Result<Option<Self>, DecodeError>;
223223
}
224224

225+
const MAX_ALLOC_SIZE: u64 = 64*1024;
226+
227+
pub(crate) struct VecWriteWrapper<'a, T: Writeable>(pub &'a Vec<T>);
228+
impl<'a, T: Writeable> Writeable for VecWriteWrapper<'a, T> {
229+
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
230+
(self.0.len() as u64).write(writer)?;
231+
for ref v in self.0.iter() {
232+
v.write(writer)?;
233+
}
234+
Ok(())
235+
}
236+
}
237+
pub(crate) struct VecReadWrapper<T: Readable>(pub Vec<T>);
238+
impl<T: Readable> Readable for VecReadWrapper<T> {
239+
fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
240+
let count: u64 = Readable::read(reader)?;
241+
let mut values = Vec::with_capacity(cmp::min(count, MAX_ALLOC_SIZE / (::std::mem::size_of::<T>() as u64)) as usize);
242+
for _ in 0..count {
243+
match Readable::read(reader) {
244+
Ok(v) => { values.push(v); },
245+
Err(e) => return Err(e),
246+
}
247+
}
248+
Ok(Self(values))
249+
}
250+
}
251+
225252
pub(crate) struct U48(pub u64);
226253
impl Writeable for U48 {
227254
#[inline]

lightning/src/util/ser_macros.rs

Lines changed: 74 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -254,7 +254,7 @@ macro_rules! write_ver_prefix {
254254
/// This is the preferred method of adding new fields that old nodes can ignore and still function
255255
/// correctly.
256256
macro_rules! write_tlv_fields {
257-
($stream: expr, {$(($type: expr, $field: expr)),*}, {$(($optional_type: expr, $optional_field: expr)),*}) => {
257+
($stream: expr, {$(($type: expr, $field: expr)),* $(,)?}, {$(($optional_type: expr, $optional_field: expr)),* $(,)?}) => {
258258
encode_varint_length_prefixed_tlv!($stream, {$(($type, $field)),*} , {$(($optional_type, $optional_field)),*});
259259
}
260260
}
@@ -275,14 +275,86 @@ macro_rules! read_ver_prefix {
275275

276276
/// Reads a suffix added by write_tlv_fields.
277277
macro_rules! read_tlv_fields {
278-
($stream: expr, {$(($reqtype: expr, $reqfield: ident)),*}, {$(($type: expr, $field: ident)),*}) => { {
278+
($stream: expr, {$(($reqtype: expr, $reqfield: ident)),* $(,)?}, {$(($type: expr, $field: ident)),* $(,)?}) => { {
279279
let tlv_len = ::util::ser::BigSize::read($stream)?;
280280
let mut rd = ::util::ser::FixedLengthReader::new($stream, tlv_len.0);
281281
decode_tlv!(&mut rd, {$(($reqtype, $reqfield)),*}, {$(($type, $field)),*});
282282
rd.eat_remaining().map_err(|_| DecodeError::ShortRead)?;
283283
} }
284284
}
285285

286+
// If we naively create a struct in impl_writeable_tlv_based blow, we may end up returning
287+
// `Self { ,,vecfield: vecfield }` which is obviously incorrect. Instead, we have to match here to
288+
// detect at least one empty field set and skip the potentially-extra comma.
289+
macro_rules! _init_tlv_based_struct {
290+
({}, {$($field: ident),*}, {$($vecfield: ident),*}) => {
291+
Ok(Self {
292+
$($field),*,
293+
$($vecfield: $vecfield.unwrap().0),*
294+
})
295+
};
296+
({$($reqfield: ident),*}, {}, {$($vecfield: ident),*}) => {
297+
Ok(Self {
298+
$($reqfield),*,
299+
$($vecfield: $vecfield.unwrap().0),*
300+
})
301+
};
302+
({$($reqfield: ident),*}, {$($field: ident),*}, {}) => {
303+
Ok(Self {
304+
$($reqfield),*,
305+
$($field),*
306+
})
307+
};
308+
({$($reqfield: ident),*}, {$($field: ident),*}, {$($vecfield: ident),*}) => {
309+
Ok(Self {
310+
$($reqfield),*,
311+
$($field),*,
312+
$($vecfield: $vecfield.unwrap().0),*
313+
})
314+
}
315+
}
316+
317+
/// Implements Readable/Writeable for a struct storing it as a set of TLVs
318+
/// First block includes all the required fields including a dummy value which is used during
319+
/// deserialization but which will never be exposed to other code.
320+
/// The second block includes optional fields.
321+
macro_rules! impl_writeable_tlv_based {
322+
($st: ident, {$(($reqtype: expr, $reqfield: ident, $reqdefault: expr)),* $(,)?}, {$(($type: expr, $field: ident)),* $(,)?}, {$(($vectype: expr, $vecfield: ident)),* $(,)?}) => {
323+
impl ::util::ser::Writeable for $st {
324+
fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
325+
write_tlv_fields!(writer, {
326+
$(($reqtype, self.$reqfield)),*
327+
}, {
328+
$(($type, self.$field)),*,
329+
$(($vectype, Some(::util::ser::VecWriteWrapper(&self.$vecfield)))),*
330+
});
331+
Ok(())
332+
}
333+
}
334+
335+
impl ::util::ser::Readable for $st {
336+
fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, ::ln::msgs::DecodeError> {
337+
$(
338+
let mut $reqfield = $reqdefault;
339+
)*
340+
$(
341+
let mut $field = None;
342+
)*
343+
$(
344+
let mut $vecfield = Some(::util::ser::VecReadWrapper(Vec::new()));
345+
)*
346+
read_tlv_fields!(reader, {
347+
$(($reqtype, $reqfield)),*
348+
}, {
349+
$(($type, $field)),*,
350+
$(($vectype, $vecfield)),*
351+
});
352+
_init_tlv_based_struct!({$($reqfield),*}, {$($field),*}, {$($vecfield),*})
353+
}
354+
}
355+
}
356+
}
357+
286358
#[cfg(test)]
287359
mod tests {
288360
use std::io::{Cursor, Read};

0 commit comments

Comments
 (0)