Skip to content

Commit cf43002

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 c9f6a35 commit cf43002

File tree

2 files changed

+131
-2
lines changed

2 files changed

+131
-2
lines changed

lightning/src/util/ser.rs

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

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

lightning/src/util/ser_macros.rs

Lines changed: 97 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,109 @@ 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 below, 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: $reqfield.0.unwrap()),*,
299+
$($vecfield: $vecfield.unwrap().0),*
300+
})
301+
};
302+
({$($reqfield: ident),*}, {$($field: ident),*}, {}) => {
303+
Ok(Self {
304+
$($reqfield: $reqfield.0.unwrap()),*,
305+
$($field),*
306+
})
307+
};
308+
({$($reqfield: ident),*}, {$($field: ident),*}, {$($vecfield: ident),*}) => {
309+
Ok(Self {
310+
$($reqfield: $reqfield.0.unwrap()),*,
311+
$($field),*,
312+
$($vecfield: $vecfield.unwrap().0),*
313+
})
314+
}
315+
}
316+
317+
// If we don't have any optional types below, but do have some vec types, we end up calling
318+
// `write_tlv_field!($stream, {..}, {, (vec_ty, vec_val)})`, which is obviously broken.
319+
// Instead, for write and read we match the missing values and skip the extra comma.
320+
macro_rules! _write_tlv_fields {
321+
($stream: expr, {$(($type: expr, $field: expr)),* $(,)*}, {}, {$(($optional_type: expr, $optional_field: expr)),* $(,)*}) => {
322+
write_tlv_fields!($stream, {$(($type, $field)),*} , {$(($optional_type, $optional_field)),*});
323+
};
324+
($stream: expr, {$(($type: expr, $field: expr)),* $(,)*}, {$(($optional_type: expr, $optional_field: expr)),* $(,)*}, {$(($optional_type_2: expr, $optional_field_2: expr)),* $(,)*}) => {
325+
write_tlv_fields!($stream, {$(($type, $field)),*} , {$(($optional_type, $optional_field)),*, $(($optional_type_2, $optional_field_2)),*});
326+
}
327+
}
328+
macro_rules! _read_tlv_fields {
329+
($stream: expr, {$(($reqtype: expr, $reqfield: ident)),* $(,)*}, {}, {$(($type: expr, $field: ident)),* $(,)*}) => {
330+
read_tlv_fields!($stream, {$(($reqtype, $reqfield)),*}, {$(($type, $field)),*});
331+
};
332+
($stream: expr, {$(($reqtype: expr, $reqfield: ident)),* $(,)*}, {$(($type: expr, $field: ident)),* $(,)*}, {$(($type_2: expr, $field_2: ident)),* $(,)*}) => {
333+
read_tlv_fields!($stream, {$(($reqtype, $reqfield)),*}, {$(($type, $field)),*, $(($type_2, $field_2)),*});
334+
}
335+
}
336+
337+
/// Implements Readable/Writeable for a struct storing it as a set of TLVs
338+
/// First block includes all the required fields including a dummy value which is used during
339+
/// deserialization but which will never be exposed to other code.
340+
/// The second block includes optional fields.
341+
/// The third block includes any Vecs which need to have their individual elements serialized.
342+
macro_rules! impl_writeable_tlv_based {
343+
($st: ident, {$(($reqtype: expr, $reqfield: ident)),* $(,)*}, {$(($type: expr, $field: ident)),* $(,)*}, {$(($vectype: expr, $vecfield: ident)),* $(,)*}) => {
344+
impl ::util::ser::Writeable for $st {
345+
fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
346+
_write_tlv_fields!(writer, {
347+
$(($reqtype, self.$reqfield)),*
348+
}, {
349+
$(($type, self.$field)),*
350+
}, {
351+
$(($vectype, Some(::util::ser::VecWriteWrapper(&self.$vecfield)))),*
352+
});
353+
Ok(())
354+
}
355+
}
356+
357+
impl ::util::ser::Readable for $st {
358+
fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, ::ln::msgs::DecodeError> {
359+
$(
360+
let mut $reqfield = ::util::ser::OptionDeserWrapper(None);
361+
)*
362+
$(
363+
let mut $field = None;
364+
)*
365+
$(
366+
let mut $vecfield = Some(::util::ser::VecReadWrapper(Vec::new()));
367+
)*
368+
_read_tlv_fields!(reader, {
369+
$(($reqtype, $reqfield)),*
370+
}, {
371+
$(($type, $field)),*
372+
}, {
373+
$(($vectype, $vecfield)),*
374+
});
375+
_init_tlv_based_struct!({$($reqfield),*}, {$($field),*}, {$($vecfield),*})
376+
}
377+
}
378+
}
379+
}
380+
286381
#[cfg(test)]
287382
mod tests {
288383
use std::io::{Cursor, Read};

0 commit comments

Comments
 (0)