+ ($struct: ident, $cmp: tt, {$({$match: pat, $length: expr}),*}, {$($field:ident),*}) => {
+ impl_writeable_len_match!($struct, $cmp, (true), { $({ $match, $length }),* }, { $($field),* });
+ };
+ ($struct: ident, {$({$match: pat, $length: expr}),*}, {$($field:ident),*}) => {
+ impl_writeable_len_match!($struct, ==, (false), { $({ $match, $length }),* }, { $($field),* });
+ }
+}
+
+/// Write out two bytes to indicate the version of an object.
+/// $this_version represents a unique version of a type. Incremented whenever the type's
+/// serialization format has changed or has a new interpretation. Used by a type's
+/// reader to determine how to interpret fields or if it can understand a serialized
+/// object.
+/// $min_version_that_can_read_this is the minimum reader version which can understand this
+/// serialized object. Previous versions will simply err with a
+/// DecodeError::UnknownVersion.
+///
+/// Updates to either $this_version or $min_version_that_can_read_this should be included in
+/// release notes.
+///
+/// Both version fields can be specific to this type of object.
+macro_rules! write_ver_prefix {
+ ($stream: expr, $this_version: expr, $min_version_that_can_read_this: expr) => {
+ $stream.write_all(&[$this_version; 1])?;
+ $stream.write_all(&[$min_version_that_can_read_this; 1])?;
+ }
+}
+
+/// Writes out a suffix to an object which contains potentially backwards-compatible, optional
+/// fields which old nodes can happily ignore.
+///
+/// It is written out in TLV format and, as with all TLV fields, unknown even fields cause a
+/// DecodeError::UnknownRequiredFeature error, with unknown odd fields ignored.
+///
+/// This is the preferred method of adding new fields that old nodes can ignore and still function
+/// correctly.
+macro_rules! write_tlv_fields {
+ ($stream: expr, {$(($type: expr, $field: expr, $fieldty: tt)),* $(,)*}) => {
+ encode_varint_length_prefixed_tlv!($stream, {$(($type, $field, $fieldty)),*});
+ }
+}
+
+/// Reads a prefix added by write_ver_prefix!(), above. Takes the current version of the
+/// serialization logic for this object. This is compared against the
+/// $min_version_that_can_read_this added by write_ver_prefix!().
+macro_rules! read_ver_prefix {
+ ($stream: expr, $this_version: expr) => { {
+ let ver: u8 = Readable::read($stream)?;
+ let min_ver: u8 = Readable::read($stream)?;
+ if min_ver > $this_version {
+ return Err(DecodeError::UnknownVersion);
+ }
+ ver
+ } }
+}
+
+/// Reads a suffix added by write_tlv_fields.
+macro_rules! read_tlv_fields {
+ ($stream: expr, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}) => { {
+ let tlv_len: ::util::ser::BigSize = ::util::ser::Readable::read($stream)?;
+ let mut rd = ::util::ser::FixedLengthReader::new($stream, tlv_len.0);
+ decode_tlv_stream!(&mut rd, {$(($type, $field, $fieldty)),*});
+ rd.eat_remaining().map_err(|_| ::ln::msgs::DecodeError::ShortRead)?;
+ } }
+}
+
+macro_rules! init_tlv_based_struct_field {
+ ($field: ident, (default_value, $default: expr)) => {
+ $field
+ };
+ ($field: ident, option) => {
+ $field
+ };
+ ($field: ident, required) => {
+ $field.0.unwrap()
+ };
+ ($field: ident, vec_type) => {
+ $field.unwrap()
+ };
+}
+
+macro_rules! init_tlv_field_var {
+ ($field: ident, (default_value, $default: expr)) => {
+ let mut $field = $default;
+ };
+ ($field: ident, required) => {
+ let mut $field = ::util::ser::OptionDeserWrapper(None);
+ };
+ ($field: ident, vec_type) => {
+ let mut $field = Some(Vec::new());
+ };
+ ($field: ident, option) => {
+ let mut $field = None;
+ };
+}
+
+/// Implements Readable/Writeable for a struct storing it as a set of TLVs
+/// If $fieldty is `required`, then $field is a required field that is not an Option nor a Vec.
+/// If $fieldty is `option`, then $field is optional field.
+/// if $fieldty is `vec_type`, then $field is a Vec, which needs to have its individual elements
+/// serialized.
+macro_rules! impl_writeable_tlv_based {
+ ($st: ident, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}) => {
+ impl ::util::ser::Writeable for $st {
+ fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), $crate::io::Error> {
+ write_tlv_fields!(writer, {
+ $(($type, self.$field, $fieldty)),*
+ });
+ Ok(())
+ }
+
+ #[inline]
+ fn serialized_length(&self) -> usize {
+ use util::ser::BigSize;
+ let len = {
+ #[allow(unused_mut)]
+ let mut len = ::util::ser::LengthCalculatingWriter(0);
+ $(
+ get_varint_length_prefixed_tlv_length!(len, $type, self.$field, $fieldty);
+ )*
+ len.0
+ };
+ let mut len_calc = ::util::ser::LengthCalculatingWriter(0);
+ BigSize(len as u64).write(&mut len_calc).expect("No in-memory data may fail to serialize");
+ len + len_calc.0
+ }
+ }
+
+ impl ::util::ser::Readable for $st {
+ fn read<R: $crate::io::Read>(reader: &mut R) -> Result<Self, ::ln::msgs::DecodeError> {
+ $(
+ init_tlv_field_var!($field, $fieldty);
+ )*
+ read_tlv_fields!(reader, {
+ $(($type, $field, $fieldty)),*
+ });
+ Ok(Self {
+ $(
+ $field: init_tlv_based_struct_field!($field, $fieldty)
+ ),*
+ })
+ }
+ }
+ }
+}
+
+macro_rules! _impl_writeable_tlv_based_enum_common {
+ ($st: ident, $(($variant_id: expr, $variant_name: ident) =>
+ {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}
+ ),* $(,)*;
+ $(($tuple_variant_id: expr, $tuple_variant_name: ident)),* $(,)*) => {
+ impl ::util::ser::Writeable for $st {
+ fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), $crate::io::Error> {
+ match self {
+ $($st::$variant_name { $(ref $field),* } => {
+ let id: u8 = $variant_id;
+ id.write(writer)?;
+ write_tlv_fields!(writer, {
+ $(($type, $field, $fieldty)),*
+ });
+ }),*
+ $($st::$tuple_variant_name (ref field) => {
+ let id: u8 = $tuple_variant_id;
+ id.write(writer)?;
+ field.write(writer)?;
+ }),*
+ }
+ Ok(())
+ }
+ }
+ }
+}
+
+/// Implement MaybeReadable and Writeable for an enum, with struct variants stored as TLVs and
+/// tuple variants stored directly.
+///
+/// This is largely identical to `impl_writeable_tlv_based_enum`, except that odd variants will
+/// return `Ok(None)` instead of `Err(UnknownRequiredFeature)`. It should generally be preferred
+/// when `MaybeReadable` is practical instead of just `Readable` as it provides an upgrade path for
+/// new variants to be added which are simply ignored by existing clients.
+macro_rules! impl_writeable_tlv_based_enum_upgradable {
+ ($st: ident, $(($variant_id: expr, $variant_name: ident) =>
+ {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}
+ ),* $(,)*) => {
+ _impl_writeable_tlv_based_enum_common!($st,
+ $(($variant_id, $variant_name) => {$(($type, $field, $fieldty)),*}),*; );
+
+ impl ::util::ser::MaybeReadable for $st {
+ fn read<R: $crate::io::Read>(reader: &mut R) -> Result<Option<Self>, ::ln::msgs::DecodeError> {
+ let id: u8 = ::util::ser::Readable::read(reader)?;
+ match id {
+ $($variant_id => {
+ // Because read_tlv_fields creates a labeled loop, we cannot call it twice
+ // in the same function body. Instead, we define a closure and call it.
+ let f = || {
+ $(
+ init_tlv_field_var!($field, $fieldty);
+ )*
+ read_tlv_fields!(reader, {
+ $(($type, $field, $fieldty)),*
+ });
+ Ok(Some($st::$variant_name {
+ $(
+ $field: init_tlv_based_struct_field!($field, $fieldty)
+ ),*
+ }))
+ };
+ f()
+ }),*
+ _ if id % 2 == 1 => Ok(None),
+ _ => Err(DecodeError::UnknownRequiredFeature),
+ }
+ }
+ }
+
+ }
+}
+
+/// Implement Readable and Writeable for an enum, with struct variants stored as TLVs and tuple
+/// variants stored directly.
+/// The format is, for example
+/// impl_writeable_tlv_based_enum!(EnumName,
+/// (0, StructVariantA) => {(0, required_variant_field, required), (1, optional_variant_field, option)},
+/// (1, StructVariantB) => {(0, variant_field_a, required), (1, variant_field_b, required), (2, variant_vec_field, vec_type)};
+/// (2, TupleVariantA), (3, TupleVariantB),
+/// );
+/// The type is written as a single byte, followed by any variant data.
+/// Attempts to read an unknown type byte result in DecodeError::UnknownRequiredFeature.
+macro_rules! impl_writeable_tlv_based_enum {
+ ($st: ident, $(($variant_id: expr, $variant_name: ident) =>
+ {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}
+ ),* $(,)*;
+ $(($tuple_variant_id: expr, $tuple_variant_name: ident)),* $(,)*) => {
+ _impl_writeable_tlv_based_enum_common!($st,
+ $(($variant_id, $variant_name) => {$(($type, $field, $fieldty)),*}),*;
+ $(($tuple_variant_id, $tuple_variant_name)),*);
+
+ impl ::util::ser::Readable for $st {
+ fn read<R: $crate::io::Read>(reader: &mut R) -> Result<Self, ::ln::msgs::DecodeError> {
+ let id: u8 = ::util::ser::Readable::read(reader)?;
+ match id {
+ $($variant_id => {
+ // Because read_tlv_fields creates a labeled loop, we cannot call it twice
+ // in the same function body. Instead, we define a closure and call it.
+ let f = || {
+ $(
+ init_tlv_field_var!($field, $fieldty);
+ )*
+ read_tlv_fields!(reader, {
+ $(($type, $field, $fieldty)),*
+ });
+ Ok($st::$variant_name {
+ $(
+ $field: init_tlv_based_struct_field!($field, $fieldty)
+ ),*
+ })
+ };
+ f()
+ }),*
+ $($tuple_variant_id => {
+ Ok($st::$tuple_variant_name(Readable::read(reader)?))
+ }),*
+ _ => {
+ Err(DecodeError::UnknownRequiredFeature)
+ },
+ }
+ }
+ }