Enable wumbo channels to be created
[rust-lightning] / lightning / src / util / ser_macros.rs
index 0ad9710a794b11f6e545a4a9e3ac627dc634f654..165d1f1edbacea61438ef3426828a1195336a39e 100644 (file)
@@ -115,6 +115,9 @@ macro_rules! check_tlv_order {
        ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, vec_type) => {{
                // no-op
        }};
+       ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, ignorable) => {{
+               // no-op
+       }};
 }
 
 macro_rules! check_missing_tlv {
@@ -138,6 +141,9 @@ macro_rules! check_missing_tlv {
        ($last_seen_type: expr, $type: expr, $field: ident, option) => {{
                // no-op
        }};
+       ($last_seen_type: expr, $type: expr, $field: ident, ignorable) => {{
+               // no-op
+       }};
 }
 
 macro_rules! decode_tlv {
@@ -148,11 +154,15 @@ macro_rules! decode_tlv {
                $field = ser::Readable::read(&mut $reader)?;
        }};
        ($reader: expr, $field: ident, vec_type) => {{
-               $field = Some(ser::Readable::read(&mut $reader)?);
+               let f: ::util::ser::VecReadWrapper<_> = ser::Readable::read(&mut $reader)?;
+               $field = Some(f.0);
        }};
        ($reader: expr, $field: ident, option) => {{
                $field = Some(ser::Readable::read(&mut $reader)?);
        }};
+       ($reader: expr, $field: ident, ignorable) => {{
+               $field = ser::MaybeReadable::read(&mut $reader)?;
+       }};
 }
 
 macro_rules! decode_tlv_stream {
@@ -221,103 +231,52 @@ macro_rules! decode_tlv_stream {
        } }
 }
 
-macro_rules! impl_writeable {
-       ($st:ident, $len: expr, {$($field:ident),*}) => {
+macro_rules! impl_writeable_msg {
+       ($st:ident, {$($field:ident),* $(,)*}, {$(($type: expr, $tlvfield: ident, $fieldty: tt)),* $(,)*}) => {
                impl ::util::ser::Writeable for $st {
                        fn write<W: ::util::ser::Writer>(&self, w: &mut W) -> Result<(), $crate::io::Error> {
-                               if $len != 0 {
-                                       w.size_hint($len);
-                               }
-                               #[cfg(any(test, feature = "fuzztarget"))]
-                               {
-                                       // In tests, assert that the hard-coded length matches the actual one
-                                       if $len != 0 {
-                                               let mut len_calc = ::util::ser::LengthCalculatingWriter(0);
-                                               $( self.$field.write(&mut len_calc).expect("No in-memory data may fail to serialize"); )*
-                                               assert_eq!(len_calc.0, $len);
-                                               assert_eq!(self.serialized_length(), $len);
-                                       }
-                               }
                                $( self.$field.write(w)?; )*
+                               encode_tlv_stream!(w, {$(($type, self.$tlvfield, $fieldty)),*});
                                Ok(())
                        }
-
-                       #[inline]
-                       fn serialized_length(&self) -> usize {
-                               if $len == 0 || cfg!(any(test, feature = "fuzztarget")) {
-                                       let mut len_calc = 0;
-                                       $( len_calc += self.$field.serialized_length(); )*
-                                       if $len != 0 {
-                                               // In tests, assert that the hard-coded length matches the actual one
-                                               assert_eq!(len_calc, $len);
-                                       } else {
-                                               return len_calc;
-                                       }
-                               }
-                               $len
-                       }
                }
-
                impl ::util::ser::Readable for $st {
                        fn read<R: $crate::io::Read>(r: &mut R) -> Result<Self, ::ln::msgs::DecodeError> {
+                               $(let $field = ::util::ser::Readable::read(r)?;)*
+                               $(init_tlv_field_var!($tlvfield, $fieldty);)*
+                               decode_tlv_stream!(r, {$(($type, $tlvfield, $fieldty)),*});
                                Ok(Self {
-                                       $($field: ::util::ser::Readable::read(r)?),*
+                                       $($field),*,
+                                       $($tlvfield),*
                                })
                        }
                }
        }
 }
-macro_rules! impl_writeable_len_match {
-       ($struct: ident, $cmp: tt, ($calc_len: expr), {$({$match: pat, $length: expr}),*}, {$($field:ident),*}) => {
-               impl Writeable for $struct {
-                       fn write<W: Writer>(&self, w: &mut W) -> Result<(), $crate::io::Error> {
-                               let len = match *self {
-                                       $($match => $length,)*
-                               };
-                               w.size_hint(len);
-                               #[cfg(any(test, feature = "fuzztarget"))]
-                               {
-                                       // In tests, assert that the hard-coded length matches the actual one
-                                       let mut len_calc = ::util::ser::LengthCalculatingWriter(0);
-                                       $( self.$field.write(&mut len_calc).expect("No in-memory data may fail to serialize"); )*
-                                       assert!(len_calc.0 $cmp len);
-                                       assert_eq!(len_calc.0, self.serialized_length());
-                               }
+
+macro_rules! impl_writeable {
+       ($st:ident, {$($field:ident),*}) => {
+               impl ::util::ser::Writeable for $st {
+                       fn write<W: ::util::ser::Writer>(&self, w: &mut W) -> Result<(), $crate::io::Error> {
                                $( self.$field.write(w)?; )*
                                Ok(())
                        }
 
                        #[inline]
                        fn serialized_length(&self) -> usize {
-                               if $calc_len || cfg!(any(test, feature = "fuzztarget")) {
-                                       let mut len_calc = 0;
-                                       $( len_calc += self.$field.serialized_length(); )*
-                                       if !$calc_len {
-                                               assert_eq!(len_calc, match *self {
-                                                       $($match => $length,)*
-                                               });
-                                       }
-                                       return len_calc
-                               }
-                               match *self {
-                                       $($match => $length,)*
-                               }
+                               let mut len_calc = 0;
+                               $( len_calc += self.$field.serialized_length(); )*
+                               return len_calc;
                        }
                }
 
-               impl ::util::ser::Readable for $struct {
-                       fn read<R: $crate::io::Read>(r: &mut R) -> Result<Self, DecodeError> {
+               impl ::util::ser::Readable for $st {
+                       fn read<R: $crate::io::Read>(r: &mut R) -> Result<Self, ::ln::msgs::DecodeError> {
                                Ok(Self {
-                                       $($field: Readable::read(r)?),*
+                                       $($field: ::util::ser::Readable::read(r)?),*
                                })
                        }
                }
-       };
-       ($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),* });
        }
 }
 
@@ -351,7 +310,7 @@ macro_rules! write_ver_prefix {
 /// correctly.
 macro_rules! write_tlv_fields {
        ($stream: expr, {$(($type: expr, $field: expr, $fieldty: tt)),* $(,)*}) => {
-               encode_varint_length_prefixed_tlv!($stream, {$(($type, $field, $fieldty)),*});
+               encode_varint_length_prefixed_tlv!($stream, {$(($type, $field, $fieldty)),*})
        }
 }
 
@@ -372,7 +331,7 @@ macro_rules! read_ver_prefix {
 /// 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::read($stream)?;
+               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)?;
@@ -390,7 +349,7 @@ macro_rules! init_tlv_based_struct_field {
                $field.0.unwrap()
        };
        ($field: ident, vec_type) => {
-               $field.unwrap().0
+               $field.unwrap()
        };
 }
 
@@ -402,11 +361,11 @@ macro_rules! init_tlv_field_var {
                let mut $field = ::util::ser::OptionDeserWrapper(None);
        };
        ($field: ident, vec_type) => {
-               let mut $field = Some(::util::ser::VecReadWrapper(Vec::new()));
+               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
@@ -459,17 +418,7 @@ macro_rules! impl_writeable_tlv_based {
        }
 }
 
-/// 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 {
+macro_rules! _impl_writeable_tlv_based_enum_common {
        ($st: ident, $(($variant_id: expr, $variant_name: ident) =>
                {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}
        ),* $(,)*;
@@ -493,6 +442,78 @@ macro_rules! impl_writeable_tlv_based_enum {
                                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)),* $(,)*}
+       ),* $(,)*
+       $(;
+       $(($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::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()
+                                       }),*
+                                       $($($tuple_variant_id => {
+                                               Ok(Some($st::$tuple_variant_name(Readable::read(reader)?)))
+                                       }),*)*
+                                       _ 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> {