X-Git-Url: http://git.bitcoin.ninja/index.cgi?a=blobdiff_plain;f=lightning%2Fsrc%2Futil%2Fser_macros.rs;h=0aefaf383062b3d8ddcafbeb1465242ccf802e95;hb=50a39b96479c9930abbb600f764449d9527026fc;hp=2ed3683f43fe6938d2fec9118d5f2c2bcb45bda7;hpb=3a33693b1e279221f517b33af6bbdf38cc1330a9;p=rust-lightning diff --git a/lightning/src/util/ser_macros.rs b/lightning/src/util/ser_macros.rs index 2ed3683f..0aefaf38 100644 --- a/lightning/src/util/ser_macros.rs +++ b/lightning/src/util/ser_macros.rs @@ -39,6 +39,9 @@ macro_rules! _encode_tlv { field.write($stream)?; } }; + ($stream: expr, $type: expr, $field: expr, ignorable) => { + $crate::_encode_tlv!($stream, $type, $field, required); + }; ($stream: expr, $type: expr, $field: expr, (option, encoding: ($fieldty: ty, $encoding: ident))) => { $crate::_encode_tlv!($stream, $type, $field.map(|f| $encoding(f)), option); }; @@ -55,7 +58,8 @@ macro_rules! _check_encoded_tlv_order { ($last_type: expr, $type: expr, (static_value, $value: expr)) => { }; ($last_type: expr, $type: expr, $fieldty: tt) => { if let Some(t) = $last_type { - debug_assert!(t <= $type); + #[allow(unused_comparisons)] // Note that $type may be 0 making the following comparison always false + (debug_assert!(t < $type)) } $last_type = Some($type); }; @@ -154,6 +158,9 @@ macro_rules! _get_varint_length_prefixed_tlv_length { $len.0 += field_len; } }; + ($len: expr, $type: expr, $field: expr, ignorable) => { + $crate::_get_varint_length_prefixed_tlv_length!($len, $type, $field, required); + }; } /// See the documentation of [`write_tlv_fields`]. @@ -279,6 +286,9 @@ macro_rules! _decode_tlv { ($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)?; @@ -450,20 +460,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, $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),* @@ -500,13 +540,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. @@ -566,6 +606,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] @@ -579,6 +620,9 @@ 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, required) => { $field.0.unwrap() }; @@ -588,6 +632,7 @@ 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] @@ -607,9 +652,13 @@ macro_rules! _init_tlv_field_var { ($field: ident, option) => { let mut $field = None; }; + ($field: ident, ignorable) => { + 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] @@ -626,10 +675,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, /// ``` @@ -714,7 +763,8 @@ macro_rules! tlv_stream { )* } - #[derive(Debug, PartialEq)] + #[cfg_attr(test, derive(PartialEq))] + #[derive(Debug)] pub(super) struct $nameref<'a> { $( pub(super) $field: Option, @@ -754,6 +804,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 }; } @@ -764,6 +815,7 @@ 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 }; } @@ -794,30 +846,34 @@ 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)),* $(,)*)*) => { + ),* $(,)*; + $(($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)),*)*); + $(($tuple_variant_id, $tuple_variant_name)),*); - impl $crate::util::ser::MaybeReadable for $st { - fn read(reader: &mut R) -> Result, $crate::ln::msgs::DecodeError> { + impl $crate::util::ser::Readable for $st { + fn read(reader: &mut R) -> Result { let id: u8 = $crate::util::ser::Readable::read(reader)?; match id { $($variant_id => { @@ -827,51 +883,51 @@ macro_rules! impl_writeable_tlv_based_enum_upgradable { _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) ),* - })) + }) }; 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)),* $(,)*) => { + ),* $(,)* + $(; + $(($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)),*); + $($(($tuple_variant_id, $tuple_variant_name)),*)*); - impl $crate::util::ser::Readable for $st { - fn read(reader: &mut R) -> Result { + impl $crate::util::ser::MaybeReadable for $st { + fn read(reader: &mut R) -> Result, $crate::ln::msgs::DecodeError> { let id: u8 = $crate::util::ser::Readable::read(reader)?; match id { $($variant_id => { @@ -881,20 +937,19 @@ macro_rules! impl_writeable_tlv_based_enum { _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) ),* - }) + })) }; 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(DecodeError::UnknownRequiredFeature), } } }