X-Git-Url: http://git.bitcoin.ninja/index.cgi?a=blobdiff_plain;f=lightning%2Fsrc%2Futil%2Fser_macros.rs;h=247fdf60074dc4ff0bad148bef3c89ae374f26d6;hb=2e33acbd9c5ebd605829859a982822df6e0f1723;hp=373a64e3e0e935d8a63b499041ac1f47064fbc76;hpb=ca5b10884ef0bb754cc5f1c1c346eabad82e5296;p=rust-lightning diff --git a/lightning/src/util/ser_macros.rs b/lightning/src/util/ser_macros.rs index 373a64e3..247fdf60 100644 --- a/lightning/src/util/ser_macros.rs +++ b/lightning/src/util/ser_macros.rs @@ -13,6 +13,21 @@ //! [`Readable`]: crate::util::ser::Readable //! [`Writeable`]: crate::util::ser::Writeable +// There are quite a few TLV serialization "types" which behave differently. We currently only +// publicly document the `optional` and `required` types, not supporting anything else publicly and +// changing them at will. +// +// Some of the other types include: +// * (default_value, $default) - reads optionally, reading $default if no TLV is present +// * (static_value, $value) - ignores any TLVs, always using $value +// * required_vec - reads into a Vec without a length prefix, failing if no TLV is present. +// * optional_vec - reads into an Option without a length prefix, continuing if no TLV is +// present. Writes from a Vec directly, only if any elements are present. Note +// that the struct deserialization macros return a Vec, not an Option. +// * upgradable_option - reads via MaybeReadable. +// * upgradable_required - reads via MaybeReadable, requiring a TLV be present but may return None +// if MaybeReadable::read() returns None. + /// Implements serialization for a single TLV record. /// This is exported for use by other exported macros, do not use directly. #[doc(hidden)] @@ -29,7 +44,7 @@ macro_rules! _encode_tlv { BigSize($field.serialized_length() as u64).write($stream)?; $field.write($stream)?; }; - ($stream: expr, $type: expr, $field: expr, vec_type) => { + ($stream: expr, $type: expr, $field: expr, required_vec) => { $crate::_encode_tlv!($stream, $type, $crate::util::ser::WithoutLength(&$field), required); }; ($stream: expr, $optional_type: expr, $optional_field: expr, option) => { @@ -39,15 +54,27 @@ macro_rules! _encode_tlv { field.write($stream)?; } }; - ($stream: expr, $type: expr, $field: expr, ignorable) => { + ($stream: expr, $type: expr, $field: expr, optional_vec) => { + if !$field.is_empty() { + $crate::_encode_tlv!($stream, $type, $field, required_vec); + } + }; + ($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. @@ -105,7 +132,20 @@ macro_rules! _check_encoded_tlv_order { /// [`Writer`]: crate::util::ser::Writer #[macro_export] macro_rules! encode_tlv_stream { + ($stream: expr, {$(($type: expr, $field: expr, $fieldty: tt)),* $(,)*}) => { + $crate::_encode_tlv_stream!($stream, {$(($type, $field, $fieldty)),*}) + } +} + +/// Implementation of [`encode_tlv_stream`]. +/// This is exported for use by other exported macros, do not use directly. +#[doc(hidden)] +#[macro_export] +macro_rules! _encode_tlv_stream { ($stream: expr, {$(($type: expr, $field: expr, $fieldty: tt)),* $(,)*}) => { { + $crate::_encode_tlv_stream!($stream, { $(($type, $field, $fieldty)),* }, &[]) + } }; + ($stream: expr, {$(($type: expr, $field: expr, $fieldty: tt)),* $(,)*}, $extra_tlvs: expr) => { { #[allow(unused_imports)] use $crate::{ ln::msgs::DecodeError, @@ -117,6 +157,10 @@ macro_rules! encode_tlv_stream { $( $crate::_encode_tlv!($stream, $type, $field, $fieldty); )* + for tlv in $extra_tlvs { + let (typ, value): &(u64, Vec) = tlv; + $crate::_encode_tlv!($stream, *typ, *value, required_vec); + } #[allow(unused_mut, unused_variables, unused_assignments)] #[cfg(debug_assertions)] @@ -125,8 +169,12 @@ macro_rules! encode_tlv_stream { $( $crate::_check_encoded_tlv_order!(last_seen, $type, $fieldty); )* + for tlv in $extra_tlvs { + let (typ, _): &(u64, Vec) = tlv; + $crate::_check_encoded_tlv_order!(last_seen, *typ, required_vec); + } } - } } + } }; } /// Adds the length of the serialized field to a [`LengthCalculatingWriter`]. @@ -147,7 +195,7 @@ macro_rules! _get_varint_length_prefixed_tlv_length { BigSize(field_len as u64).write(&mut $len).expect("No in-memory data may fail to serialize"); $len.0 += field_len; }; - ($len: expr, $type: expr, $field: expr, vec_type) => { + ($len: expr, $type: expr, $field: expr, required_vec) => { $crate::_get_varint_length_prefixed_tlv_length!($len, $type, $crate::util::ser::WithoutLength(&$field), required); }; ($len: expr, $optional_type: expr, $optional_field: expr, option) => { @@ -158,9 +206,23 @@ macro_rules! _get_varint_length_prefixed_tlv_length { $len.0 += field_len; } }; - ($len: expr, $type: expr, $field: expr, ignorable) => { + ($len: expr, $type: expr, $field: expr, optional_vec) => { + if !$field.is_empty() { + $crate::_get_varint_length_prefixed_tlv_length!($len, $type, $field, required_vec); + } + }; + ($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, (option, encoding: ($fieldty: ty, $encoding: ident))) => { + $crate::_get_varint_length_prefixed_tlv_length!($len, $type, $field.map(|f| $encoding(f)), 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`]. @@ -169,18 +231,27 @@ macro_rules! _get_varint_length_prefixed_tlv_length { #[macro_export] macro_rules! _encode_varint_length_prefixed_tlv { ($stream: expr, {$(($type: expr, $field: expr, $fieldty: tt)),*}) => { { + $crate::_encode_varint_length_prefixed_tlv!($stream, {$(($type, $field, $fieldty)),*}, &[]) + } }; + ($stream: expr, {$(($type: expr, $field: expr, $fieldty: tt)),*}, $extra_tlvs: expr) => { { + extern crate alloc; use $crate::util::ser::BigSize; + use alloc::vec::Vec; let len = { #[allow(unused_mut)] let mut len = $crate::util::ser::LengthCalculatingWriter(0); $( $crate::_get_varint_length_prefixed_tlv_length!(len, $type, $field, $fieldty); )* + for tlv in $extra_tlvs { + let (typ, value): &(u64, Vec) = tlv; + $crate::_get_varint_length_prefixed_tlv_length!(len, *typ, *value, required_vec); + } len.0 }; BigSize(len as u64).write($stream)?; - $crate::encode_tlv_stream!($stream, { $(($type, $field, $fieldty)),* }); - } } + $crate::_encode_tlv_stream!($stream, { $(($type, $field, $fieldty)),* }, $extra_tlvs); + } }; } /// Errors if there are missing required TLV types between the last seen type and the type currently being processed. @@ -204,13 +275,22 @@ 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) => {{ + ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, required_vec) => {{ + $crate::_check_decoded_tlv_order!($last_seen_type, $typ, $type, $field, required); + }}; + ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, optional_vec) => {{ // 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)?)) => {{ @@ -243,13 +323,22 @@ macro_rules! _check_missing_tlv { return Err(DecodeError::InvalidValue); } }}; - ($last_seen_type: expr, $type: expr, $field: ident, vec_type) => {{ - // no-op + ($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, required_vec) => {{ + $crate::_check_missing_tlv!($last_seen_type, $type, $field, required); }}; ($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, optional_vec) => {{ + // no-op + }}; + ($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)?)) => {{ @@ -273,14 +362,34 @@ macro_rules! _decode_tlv { ($reader: expr, $field: ident, required) => {{ $field = $crate::util::ser::Readable::read(&mut $reader)?; }}; - ($reader: expr, $field: ident, vec_type) => {{ + ($reader: expr, $field: ident, (required: $trait: ident $(, $read_arg: expr)?)) => {{ + $field = $trait::read(&mut $reader $(, $read_arg)*)?; + }}; + ($reader: expr, $field: ident, required_vec) => {{ let f: $crate::util::ser::WithoutLength> = $crate::util::ser::Readable::read(&mut $reader)?; - $field = Some(f.0); + $field = f.0; }}; ($reader: expr, $field: ident, option) => {{ $field = Some($crate::util::ser::Readable::read(&mut $reader)?); }}; - ($reader: expr, $field: ident, ignorable) => {{ + ($reader: expr, $field: ident, optional_vec) => {{ + let f: $crate::util::ser::WithoutLength> = $crate::util::ser::Readable::read(&mut $reader)?; + $field = Some(f.0); + }}; + // `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)?)) => {{ @@ -378,7 +487,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 = None; let mut stream_ref = $stream; @@ -401,7 +509,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. @@ -460,20 +568,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, +/// } +/// +/// 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(&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.as_ref(), $fieldty)),*}); Ok(()) } } impl $crate::util::ser::Readable for $st { fn read(r: &mut R) -> Result { $(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),* @@ -590,13 +728,22 @@ macro_rules! _init_tlv_based_struct_field { ($field: ident, option) => { $field }; - ($field: ident, ignorable) => { - if $field.is_none() { return Ok(None); } else { $field.unwrap() } + ($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() }; - ($field: ident, vec_type) => { + ($field: ident, required_vec) => { + $field + }; + ($field: ident, optional_vec) => { $field.unwrap() }; } @@ -608,31 +755,49 @@ macro_rules! _init_tlv_based_struct_field { #[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, vec_type) => { - let mut $field = Some(Vec::new()); + ($field: ident, (required: $trait: ident $(, $read_arg: expr)?)) => { + $crate::_init_tlv_field_var!($field, required); + }; + ($field: ident, required_vec) => { + let mut $field = Vec::new(); }; ($field: ident, option) => { let mut $field = None; }; - ($field: ident, ignorable) => { + ($field: ident, optional_vec) => { + let mut $field = Some(Vec::new()); + }; + ($field: ident, (option, encoding: ($fieldty: ty, $encoding: ident))) => { + $crate::_init_tlv_field_var!($field, option); + }; + ($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`]. /// +/// If any unused values are read, their type MUST be specified or else `rustc` will read them as an +/// `i64`. +/// /// This is exported for use by other exported macros, do not use directly. #[doc(hidden)] #[macro_export] -macro_rules! _init_and_read_tlv_fields { +macro_rules! _init_and_read_len_prefixed_tlv_fields { ($reader: ident, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}) => { $( $crate::_init_tlv_field_var!($field, $fieldty); @@ -644,11 +809,28 @@ macro_rules! _init_and_read_tlv_fields { } } +/// Equivalent to running [`_init_tlv_field_var`] then [`decode_tlv_stream`]. +/// +/// If any unused values are read, their type MUST be specified or else `rustc` will read them as an +/// `i64`. +macro_rules! _init_and_read_tlv_stream { + ($reader: ident, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}) => { + $( + $crate::_init_tlv_field_var!($field, $fieldty); + )* + + $crate::decode_tlv_stream!($reader, { + $(($type, $field, $fieldty)),* + }); + } +} + /// 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 `optional_vec`, then `$field` is a [`Vec`], which needs to have its individual elements serialized. +/// Note that for `optional_vec` no bytes are written if the vec is empty /// /// For example, /// ``` @@ -664,7 +846,7 @@ macro_rules! _init_and_read_tlv_fields { /// (0, tlv_integer, required), /// (1, tlv_default_integer, (default_value, 7)), /// (2, tlv_optional_integer, option), -/// (3, tlv_vec_type_integer, vec_type), +/// (3, tlv_vec_type_integer, optional_vec), /// }); /// ``` /// @@ -700,7 +882,7 @@ macro_rules! impl_writeable_tlv_based { impl $crate::util::ser::Readable for $st { fn read(reader: &mut R) -> Result { - $crate::_init_and_read_tlv_fields!(reader, { + $crate::_init_and_read_len_prefixed_tlv_fields!(reader, { $(($type, $field, $fieldty)),* }); Ok(Self { @@ -789,6 +971,8 @@ macro_rules! tlv_record_ref_type { ($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)),* $(,)*} @@ -800,7 +984,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)),* }); }),* @@ -822,7 +1006,7 @@ macro_rules! _impl_writeable_tlv_based_enum_common { /// ```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)}; +/// (1, StructVariantB) => {(0, variant_field_a, required), (1, variant_field_b, required), (2, variant_vec_field, optional_vec)}; /// (2, TupleVariantA), (3, TupleVariantB), /// ); /// ``` @@ -838,7 +1022,7 @@ macro_rules! impl_writeable_tlv_based_enum { {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*} ),* $(,)*; $(($tuple_variant_id: expr, $tuple_variant_name: ident)),* $(,)*) => { - _impl_writeable_tlv_based_enum_common!($st, + $crate::_impl_writeable_tlv_based_enum_common!($st, $(($variant_id, $variant_name) => {$(($type, $field, $fieldty)),*}),*; $(($tuple_variant_id, $tuple_variant_name)),*); @@ -850,19 +1034,19 @@ macro_rules! impl_writeable_tlv_based_enum { // 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_len_prefixed_tlv_fields!(reader, { $(($type, $field, $fieldty)),* }); 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($st::$tuple_variant_name(Readable::read(reader)?)) + Ok($st::$tuple_variant_name($crate::util::ser::Readable::read(reader)?)) }),* _ => { Err($crate::ln::msgs::DecodeError::UnknownRequiredFeature) @@ -892,7 +1076,7 @@ macro_rules! impl_writeable_tlv_based_enum_upgradable { ),* $(,)* $(; $(($tuple_variant_id: expr, $tuple_variant_name: ident)),* $(,)*)*) => { - _impl_writeable_tlv_based_enum_common!($st, + $crate::_impl_writeable_tlv_based_enum_common!($st, $(($variant_id, $variant_name) => {$(($type, $field, $fieldty)),*}),*; $($(($tuple_variant_id, $tuple_variant_name)),*)*); @@ -904,12 +1088,12 @@ macro_rules! impl_writeable_tlv_based_enum_upgradable { // 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_len_prefixed_tlv_fields!(reader, { $(($type, $field, $fieldty)),* }); Ok(Some($st::$variant_name { $( - $field: _init_tlv_based_struct_field!($field, $fieldty) + $field: $crate::_init_tlv_based_struct_field!($field, $fieldty) ),* })) }; @@ -919,7 +1103,7 @@ macro_rules! impl_writeable_tlv_based_enum_upgradable { Ok(Some($st::$tuple_variant_name(Readable::read(reader)?))) }),*)* _ if id % 2 == 1 => Ok(None), - _ => Err(DecodeError::UnknownRequiredFeature), + _ => Err($crate::ln::msgs::DecodeError::UnknownRequiredFeature), } } } @@ -999,6 +1183,47 @@ mod tests { (0xdeadbeef1badbeef, 0x1bad1dea, Some(0x01020304))); } + #[derive(Debug, PartialEq)] + struct TestUpgradable { + a: u32, + b: u32, + c: Option, + } + + fn upgradable_tlv_reader(s: &[u8]) -> Result, DecodeError> { + let mut s = Cursor::new(s); + let mut a = 0; + let mut b = 0; + let mut c: Option = 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>, Option, Option<(PublicKey, u64, u64)>, Option), DecodeError> { let mut s = Cursor::new(s);