Move events.rs into its own top-level module
[rust-lightning] / lightning / src / util / ser_macros.rs
index d137b0f677bcda557276701d8f7380eab9eb17cb..92a43b3fde5282fb4420d4981c1e23b3d9bd0e81 100644 (file)
@@ -39,12 +39,22 @@ macro_rules! _encode_tlv {
                        field.write($stream)?;
                }
        };
+       ($stream: expr, $type: expr, $field: expr, upgradable_required) => {
+               $crate::_encode_tlv!($stream, $type, $field, required);
+       };
+       ($stream: expr, $type: expr, $field: expr, upgradable_option) => {
+               $crate::_encode_tlv!($stream, $type, $field, option);
+       };
        ($stream: expr, $type: expr, $field: expr, (option, encoding: ($fieldty: ty, $encoding: ident))) => {
                $crate::_encode_tlv!($stream, $type, $field.map(|f| $encoding(f)), option);
        };
        ($stream: expr, $type: expr, $field: expr, (option, encoding: $fieldty: ty)) => {
                $crate::_encode_tlv!($stream, $type, $field, option);
        };
+       ($stream: expr, $type: expr, $field: expr, (option: $trait: ident $(, $read_arg: expr)?)) => {
+               // Just a read-mapped type
+               $crate::_encode_tlv!($stream, $type, $field, option);
+       };
 }
 
 /// Panics if the last seen TLV type is not numerically less than the TLV type currently being checked.
@@ -155,6 +165,15 @@ macro_rules! _get_varint_length_prefixed_tlv_length {
                        $len.0 += field_len;
                }
        };
+       ($len: expr, $type: expr, $field: expr, (option: $trait: ident $(, $read_arg: expr)?)) => {
+               $crate::_get_varint_length_prefixed_tlv_length!($len, $type, $field, option);
+       };
+       ($len: expr, $type: expr, $field: expr, upgradable_required) => {
+               $crate::_get_varint_length_prefixed_tlv_length!($len, $type, $field, required);
+       };
+       ($len: expr, $type: expr, $field: expr, upgradable_option) => {
+               $crate::_get_varint_length_prefixed_tlv_length!($len, $type, $field, option);
+       };
 }
 
 /// See the documentation of [`write_tlv_fields`].
@@ -198,13 +217,19 @@ macro_rules! _check_decoded_tlv_order {
                        return Err(DecodeError::InvalidValue);
                }
        }};
+       ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, (required: $trait: ident $(, $read_arg: expr)?)) => {{
+               $crate::_check_decoded_tlv_order!($last_seen_type, $typ, $type, $field, required);
+       }};
        ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, option) => {{
                // no-op
        }};
        ($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) => {{
+       ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, upgradable_required) => {{
+               _check_decoded_tlv_order!($last_seen_type, $typ, $type, $field, required)
+       }};
+       ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, upgradable_option) => {{
                // no-op
        }};
        ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, (option: $trait: ident $(, $read_arg: expr)?)) => {{
@@ -237,13 +262,19 @@ macro_rules! _check_missing_tlv {
                        return Err(DecodeError::InvalidValue);
                }
        }};
+       ($last_seen_type: expr, $type: expr, $field: ident, (required: $trait: ident $(, $read_arg: expr)?)) => {{
+               $crate::_check_missing_tlv!($last_seen_type, $type, $field, required);
+       }};
        ($last_seen_type: expr, $type: expr, $field: ident, vec_type) => {{
                // no-op
        }};
        ($last_seen_type: expr, $type: expr, $field: ident, option) => {{
                // no-op
        }};
-       ($last_seen_type: expr, $type: expr, $field: ident, ignorable) => {{
+       ($last_seen_type: expr, $type: expr, $field: ident, upgradable_required) => {{
+               _check_missing_tlv!($last_seen_type, $type, $field, required)
+       }};
+       ($last_seen_type: expr, $type: expr, $field: ident, upgradable_option) => {{
                // no-op
        }};
        ($last_seen_type: expr, $type: expr, $field: ident, (option: $trait: ident $(, $read_arg: expr)?)) => {{
@@ -267,6 +298,9 @@ macro_rules! _decode_tlv {
        ($reader: expr, $field: ident, required) => {{
                $field = $crate::util::ser::Readable::read(&mut $reader)?;
        }};
+       ($reader: expr, $field: ident, (required: $trait: ident $(, $read_arg: expr)?)) => {{
+               $field = $trait::read(&mut $reader $(, $read_arg)*)?;
+       }};
        ($reader: expr, $field: ident, vec_type) => {{
                let f: $crate::util::ser::WithoutLength<Vec<_>> = $crate::util::ser::Readable::read(&mut $reader)?;
                $field = Some(f.0);
@@ -274,12 +308,28 @@ macro_rules! _decode_tlv {
        ($reader: expr, $field: ident, option) => {{
                $field = Some($crate::util::ser::Readable::read(&mut $reader)?);
        }};
-       ($reader: expr, $field: ident, ignorable) => {{
+       // `upgradable_required` indicates we're reading a required TLV that may have been upgraded
+       // without backwards compat. We'll error if the field is missing, and return `Ok(None)` if the
+       // field is present but we can no longer understand it.
+       // Note that this variant can only be used within a `MaybeReadable` read.
+       ($reader: expr, $field: ident, upgradable_required) => {{
+               $field = match $crate::util::ser::MaybeReadable::read(&mut $reader)? {
+                       Some(res) => res,
+                       _ => return Ok(None)
+               };
+       }};
+       // `upgradable_option` indicates we're reading an Option-al TLV that may have been upgraded
+       // without backwards compat. $field will be None if the TLV is missing or if the field is present
+       // but we can no longer understand it.
+       ($reader: expr, $field: ident, upgradable_option) => {{
                $field = $crate::util::ser::MaybeReadable::read(&mut $reader)?;
        }};
        ($reader: expr, $field: ident, (option: $trait: ident $(, $read_arg: expr)?)) => {{
                $field = Some($trait::read(&mut $reader $(, $read_arg)*)?);
        }};
+       ($reader: expr, $field: ident, (option, encoding: ($fieldty: ty, $encoding: ident, $encoder:ty))) => {{
+               $crate::_decode_tlv!($reader, $field, (option, encoding: ($fieldty, $encoding)));
+       }};
        ($reader: expr, $field: ident, (option, encoding: ($fieldty: ty, $encoding: ident))) => {{
                $field = {
                        let field: $encoding<$fieldty> = ser::Readable::read(&mut $reader)?;
@@ -369,7 +419,6 @@ macro_rules! decode_tlv_stream_with_custom_tlv_decode {
 macro_rules! _decode_tlv_stream_range {
        ($stream: expr, $range: expr, $rewind: ident, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}
         $(, $decode_custom_tlv: expr)?) => { {
-               use core::ops::RangeBounds;
                use $crate::ln::msgs::DecodeError;
                let mut last_seen_type: Option<u64> = None;
                let mut stream_ref = $stream;
@@ -392,7 +441,7 @@ macro_rules! _decode_tlv_stream_range {
                                                }
                                        },
                                        Err(e) => return Err(e),
-                                       Ok(t) => if $range.contains(&t.0) { t } else {
+                                       Ok(t) => if core::ops::RangeBounds::contains(&$range, &t.0) { t } else {
                                                drop(tracking_reader);
 
                                                // Assumes the type id is minimally encoded, which is enforced on read.
@@ -451,20 +500,50 @@ macro_rules! _decode_tlv_stream_range {
        } }
 }
 
+/// Implements [`Readable`]/[`Writeable`] for a message struct that may include non-TLV and
+/// TLV-encoded parts.
+///
+/// This is useful to implement a [`CustomMessageReader`].
+///
+/// Currently `$fieldty` may only be `option`, i.e., `$tlvfield` is optional field.
+///
+/// For example,
+/// ```
+/// # use lightning::impl_writeable_msg;
+/// struct MyCustomMessage {
+///    pub field_1: u32,
+///    pub field_2: bool,
+///    pub field_3: String,
+///    pub tlv_optional_integer: Option<u32>,
+/// }
+///
+/// impl_writeable_msg!(MyCustomMessage, {
+///    field_1,
+///    field_2,
+///    field_3
+/// }, {
+///    (1, tlv_optional_integer, option),
+/// });
+/// ```
+///
+/// [`Readable`]: crate::util::ser::Readable
+/// [`Writeable`]: crate::util::ser::Writeable
+/// [`CustomMessageReader`]: crate::ln::wire::CustomMessageReader
+#[macro_export]
 macro_rules! impl_writeable_msg {
        ($st:ident, {$($field:ident),* $(,)*}, {$(($type: expr, $tlvfield: ident, $fieldty: tt)),* $(,)*}) => {
                impl $crate::util::ser::Writeable for $st {
                        fn write<W: $crate::util::ser::Writer>(&self, w: &mut W) -> Result<(), $crate::io::Error> {
                                $( self.$field.write(w)?; )*
-                               encode_tlv_stream!(w, {$(($type, self.$tlvfield, $fieldty)),*});
+                               $crate::encode_tlv_stream!(w, {$(($type, self.$tlvfield, $fieldty)),*});
                                Ok(())
                        }
                }
                impl $crate::util::ser::Readable for $st {
                        fn read<R: $crate::io::Read>(r: &mut R) -> Result<Self, $crate::ln::msgs::DecodeError> {
                                $(let $field = $crate::util::ser::Readable::read(r)?;)*
-                               $(_init_tlv_field_var!($tlvfield, $fieldty);)*
-                               decode_tlv_stream!(r, {$(($type, $tlvfield, $fieldty)),*});
+                               $($crate::_init_tlv_field_var!($tlvfield, $fieldty);)*
+                               $crate::decode_tlv_stream!(r, {$(($type, $tlvfield, $fieldty)),*});
                                Ok(Self {
                                        $($field),*,
                                        $($tlvfield),*
@@ -501,13 +580,13 @@ macro_rules! impl_writeable {
 }
 
 /// 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.
+/// 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`].
+/// 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.
@@ -567,6 +646,7 @@ macro_rules! read_tlv_fields {
 }
 
 /// Initializes the struct fields.
+///
 /// This is exported for use by other exported macros, do not use directly.
 #[doc(hidden)]
 #[macro_export]
@@ -580,6 +660,15 @@ macro_rules! _init_tlv_based_struct_field {
        ($field: ident, option) => {
                $field
        };
+       ($field: ident, (option: $trait: ident $(, $read_arg: expr)?)) => {
+               $crate::_init_tlv_based_struct_field!($field, option)
+       };
+       ($field: ident, upgradable_required) => {
+               $field.0.unwrap()
+       };
+       ($field: ident, upgradable_option) => {
+               $field
+       };
        ($field: ident, required) => {
                $field.0.unwrap()
        };
@@ -589,18 +678,22 @@ macro_rules! _init_tlv_based_struct_field {
 }
 
 /// Initializes the variable we are going to read the TLV into.
+///
 /// This is exported for use by other exported macros, do not use directly.
 #[doc(hidden)]
 #[macro_export]
 macro_rules! _init_tlv_field_var {
        ($field: ident, (default_value, $default: expr)) => {
-               let mut $field = $crate::util::ser::OptionDeserWrapper(None);
+               let mut $field = $crate::util::ser::RequiredWrapper(None);
        };
        ($field: ident, (static_value, $value: expr)) => {
                let $field;
        };
        ($field: ident, required) => {
-               let mut $field = $crate::util::ser::OptionDeserWrapper(None);
+               let mut $field = $crate::util::ser::RequiredWrapper(None);
+       };
+       ($field: ident, (required: $trait: ident $(, $read_arg: expr)?)) => {
+               $crate::_init_tlv_field_var!($field, required);
        };
        ($field: ident, vec_type) => {
                let mut $field = Some(Vec::new());
@@ -608,9 +701,19 @@ macro_rules! _init_tlv_field_var {
        ($field: ident, option) => {
                let mut $field = None;
        };
+       ($field: ident, (option: $trait: ident $(, $read_arg: expr)?)) => {
+               $crate::_init_tlv_field_var!($field, option);
+       };
+       ($field: ident, upgradable_required) => {
+               let mut $field = $crate::util::ser::UpgradableRequired(None);
+       };
+       ($field: ident, upgradable_option) => {
+               let mut $field = None;
+       };
 }
 
 /// Equivalent to running [`_init_tlv_field_var`] then [`read_tlv_fields`].
+///
 /// This is exported for use by other exported macros, do not use directly.
 #[doc(hidden)]
 #[macro_export]
@@ -627,10 +730,10 @@ macro_rules! _init_and_read_tlv_fields {
 }
 
 /// 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 `required`, then `$field` is a required field that is not an [`Option`] nor a [`Vec`].
 /// If `$fieldty` is `(default_value, $default)`, then `$field` will be set to `$default` if not present.
 /// 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.
+/// If `$fieldty` is `vec_type`, then `$field` is a [`Vec`], which needs to have its individual elements serialized.
 ///
 /// For example,
 /// ```
@@ -715,7 +818,8 @@ macro_rules! tlv_stream {
                        )*
                }
 
-               #[derive(Debug, PartialEq)]
+               #[cfg_attr(test, derive(PartialEq))]
+               #[derive(Debug)]
                pub(super) struct $nameref<'a> {
                        $(
                                pub(super) $field: Option<tlv_record_ref_type!($fieldty)>,
@@ -755,6 +859,7 @@ macro_rules! tlv_stream {
 
 macro_rules! tlv_record_type {
        (($type:ty, $wrapper:ident)) => { $type };
+       (($type:ty, $wrapper:ident, $encoder:ty)) => { $type };
        ($type:ty) => { $type };
 }
 
@@ -765,9 +870,12 @@ macro_rules! tlv_record_ref_type {
        ((u32, $wrapper: ident)) => { u32 };
        ((u64, $wrapper: ident)) => { u64 };
        (($type:ty, $wrapper:ident)) => { &'a $type };
+       (($type:ty, $wrapper:ident, $encoder:ty)) => { $encoder };
        ($type:ty) => { &'a $type };
 }
 
+#[doc(hidden)]
+#[macro_export]
 macro_rules! _impl_writeable_tlv_based_enum_common {
        ($st: ident, $(($variant_id: expr, $variant_name: ident) =>
                {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}
@@ -779,7 +887,7 @@ macro_rules! _impl_writeable_tlv_based_enum_common {
                                        $($st::$variant_name { $(ref $field),* } => {
                                                let id: u8 = $variant_id;
                                                id.write(writer)?;
-                                               write_tlv_fields!(writer, {
+                                               $crate::write_tlv_fields!(writer, {
                                                        $(($type, *$field, $fieldty)),*
                                                });
                                        }),*
@@ -795,107 +903,110 @@ macro_rules! _impl_writeable_tlv_based_enum_common {
        }
 }
 
-/// 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(`[`DecodeError::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.
+/// Implement [`Readable`] and [`Writeable`] for an enum, with struct variants stored as TLVs and tuple
+/// variants stored directly.
+/// The format is, for example
+/// ```ignore
+/// 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`].
 ///
-/// [`MaybeReadable`]: crate::util::ser::MaybeReadable
+/// [`Readable`]: crate::util::ser::Readable
 /// [`Writeable`]: crate::util::ser::Writeable
 /// [`DecodeError::UnknownRequiredFeature`]: crate::ln::msgs::DecodeError::UnknownRequiredFeature
-/// [`Readable`]: crate::util::ser::Readable
-macro_rules! impl_writeable_tlv_based_enum_upgradable {
+#[macro_export]
+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,
+       ),* $(,)*;
+       $(($tuple_variant_id: expr, $tuple_variant_name: ident)),*  $(,)*) => {
+               $crate::_impl_writeable_tlv_based_enum_common!($st,
                        $(($variant_id, $variant_name) => {$(($type, $field, $fieldty)),*}),*;
-                       $($(($tuple_variant_id, $tuple_variant_name)),*)*);
+                       $(($tuple_variant_id, $tuple_variant_name)),*);
 
-               impl $crate::util::ser::MaybeReadable for $st {
-                       fn read<R: $crate::io::Read>(reader: &mut R) -> Result<Option<Self>, $crate::ln::msgs::DecodeError> {
+               impl $crate::util::ser::Readable for $st {
+                       fn read<R: $crate::io::Read>(reader: &mut R) -> Result<Self, $crate::ln::msgs::DecodeError> {
                                let id: u8 = $crate::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_and_read_tlv_fields!(reader, {
+                                                       $crate::_init_and_read_tlv_fields!(reader, {
                                                                $(($type, $field, $fieldty)),*
                                                        });
-                                                       Ok(Some($st::$variant_name {
+                                                       Ok($st::$variant_name {
                                                                $(
-                                                                       $field: _init_tlv_based_struct_field!($field, $fieldty)
+                                                                       $field: $crate::_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),
+                                       $($tuple_variant_id => {
+                                               Ok($st::$tuple_variant_name(Readable::read(reader)?))
+                                       }),*
+                                       _ => {
+                                               Err($crate::ln::msgs::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`].
+/// Implement [`MaybeReadable`] and [`Writeable`] for an enum, with struct variants stored as TLVs and
+/// tuple variants stored directly.
 ///
-/// [`Readable`]: crate::util::ser::Readable
+/// This is largely identical to [`impl_writeable_tlv_based_enum`], except that odd variants will
+/// return `Ok(None)` instead of `Err(`[`DecodeError::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.
+///
+/// [`MaybeReadable`]: crate::util::ser::MaybeReadable
 /// [`Writeable`]: crate::util::ser::Writeable
 /// [`DecodeError::UnknownRequiredFeature`]: crate::ln::msgs::DecodeError::UnknownRequiredFeature
-macro_rules! impl_writeable_tlv_based_enum {
+/// [`Readable`]: crate::util::ser::Readable
+#[macro_export]
+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,
+       ),* $(,)*
+       $(;
+       $(($tuple_variant_id: expr, $tuple_variant_name: ident)),*  $(,)*)*) => {
+               $crate::_impl_writeable_tlv_based_enum_common!($st,
                        $(($variant_id, $variant_name) => {$(($type, $field, $fieldty)),*}),*;
-                       $(($tuple_variant_id, $tuple_variant_name)),*);
+                       $($(($tuple_variant_id, $tuple_variant_name)),*)*);
 
-               impl $crate::util::ser::Readable for $st {
-                       fn read<R: $crate::io::Read>(reader: &mut R) -> Result<Self, $crate::ln::msgs::DecodeError> {
+               impl $crate::util::ser::MaybeReadable for $st {
+                       fn read<R: $crate::io::Read>(reader: &mut R) -> Result<Option<Self>, $crate::ln::msgs::DecodeError> {
                                let id: u8 = $crate::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_and_read_tlv_fields!(reader, {
+                                                       $crate::_init_and_read_tlv_fields!(reader, {
                                                                $(($type, $field, $fieldty)),*
                                                        });
-                                                       Ok($st::$variant_name {
+                                                       Ok(Some($st::$variant_name {
                                                                $(
-                                                                       $field: _init_tlv_based_struct_field!($field, $fieldty)
+                                                                       $field: $crate::_init_tlv_based_struct_field!($field, $fieldty)
                                                                ),*
-                                                       })
+                                                       }))
                                                };
                                                f()
                                        }),*
-                                       $($tuple_variant_id => {
-                                               Ok($st::$tuple_variant_name(Readable::read(reader)?))
-                                       }),*
-                                       _ => {
-                                               Err($crate::ln::msgs::DecodeError::UnknownRequiredFeature)
-                                       },
+                                       $($($tuple_variant_id => {
+                                               Ok(Some($st::$tuple_variant_name(Readable::read(reader)?)))
+                                       }),*)*
+                                       _ if id % 2 == 1 => Ok(None),
+                                       _ => Err($crate::ln::msgs::DecodeError::UnknownRequiredFeature),
                                }
                        }
                }
@@ -975,6 +1086,47 @@ mod tests {
                        (0xdeadbeef1badbeef, 0x1bad1dea, Some(0x01020304)));
        }
 
+       #[derive(Debug, PartialEq)]
+       struct TestUpgradable {
+               a: u32,
+               b: u32,
+               c: Option<u32>,
+       }
+
+       fn upgradable_tlv_reader(s: &[u8]) -> Result<Option<TestUpgradable>, DecodeError> {
+               let mut s = Cursor::new(s);
+               let mut a = 0;
+               let mut b = 0;
+               let mut c: Option<u32> = None;
+               decode_tlv_stream!(&mut s, {(2, a, upgradable_required), (3, b, upgradable_required), (4, c, upgradable_option)});
+               Ok(Some(TestUpgradable { a, b, c, }))
+       }
+
+       #[test]
+       fn upgradable_tlv_simple_good_cases() {
+               assert_eq!(upgradable_tlv_reader(&::hex::decode(
+                       concat!("0204deadbeef", "03041bad1dea", "0404deadbeef")
+               ).unwrap()[..]).unwrap(),
+               Some(TestUpgradable { a: 0xdeadbeef, b: 0x1bad1dea, c: Some(0xdeadbeef) }));
+
+               assert_eq!(upgradable_tlv_reader(&::hex::decode(
+                       concat!("0204deadbeef", "03041bad1dea")
+               ).unwrap()[..]).unwrap(),
+               Some(TestUpgradable { a: 0xdeadbeef, b: 0x1bad1dea, c: None}));
+       }
+
+       #[test]
+       fn missing_required_upgradable() {
+               if let Err(DecodeError::InvalidValue) = upgradable_tlv_reader(&::hex::decode(
+                       concat!("0100", "0204deadbeef")
+                       ).unwrap()[..]) {
+               } else { panic!(); }
+               if let Err(DecodeError::InvalidValue) = upgradable_tlv_reader(&::hex::decode(
+                       concat!("0100", "03041bad1dea")
+               ).unwrap()[..]) {
+               } else { panic!(); }
+       }
+
        // BOLT TLV test cases
        fn tlv_reader_n1(s: &[u8]) -> Result<(Option<HighZeroBytesDroppedBigSize<u64>>, Option<u64>, Option<(PublicKey, u64, u64)>, Option<u16>), DecodeError> {
                let mut s = Cursor::new(s);