d1e152feb09b11ecf96b701387f63c86234f9fb7
[rust-lightning] / lightning / src / util / ser_macros.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! Some macros that implement [`Readable`]/[`Writeable`] traits for lightning messages.
11 //! They also handle serialization and deserialization of TLVs.
12 //!
13 //! [`Readable`]: crate::util::ser::Readable
14 //! [`Writeable`]: crate::util::ser::Writeable
15
16 // There are quite a few TLV serialization "types" which behave differently. We currently only
17 // publicly document the `optional` and `required` types, not supporting anything else publicly and
18 // changing them at will.
19 //
20 // Some of the other types include:
21 //  * (default_value, $default) - reads optionally, reading $default if no TLV is present
22 //  * (static_value, $value) - ignores any TLVs, always using $value
23 //  * required_vec - reads into a Vec without a length prefix, failing if no TLV is present.
24 //  * optional_vec - reads into an Option<Vec> without a length prefix, continuing if no TLV is
25 //                   present. Writes from a Vec directly, only if any elements are present. Note
26 //                   that the struct deserialization macros return a Vec, not an Option.
27 //  * upgradable_option - reads via MaybeReadable.
28 //  * upgradable_required - reads via MaybeReadable, requiring a TLV be present but may return None
29 //                          if MaybeReadable::read() returns None.
30
31 /// Implements serialization for a single TLV record.
32 /// This is exported for use by other exported macros, do not use directly.
33 #[doc(hidden)]
34 #[macro_export]
35 macro_rules! _encode_tlv {
36         ($stream: expr, $type: expr, $field: expr, (default_value, $default: expr)) => {
37                 $crate::_encode_tlv!($stream, $type, $field, required)
38         };
39         ($stream: expr, $type: expr, $field: expr, (static_value, $value: expr)) => {
40                 let _ = &$field; // Ensure we "use" the $field
41         };
42         ($stream: expr, $type: expr, $field: expr, required) => {
43                 BigSize($type).write($stream)?;
44                 BigSize($field.serialized_length() as u64).write($stream)?;
45                 $field.write($stream)?;
46         };
47         ($stream: expr, $type: expr, $field: expr, required_vec) => {
48                 $crate::_encode_tlv!($stream, $type, $crate::util::ser::WithoutLength(&$field), required);
49         };
50         ($stream: expr, $optional_type: expr, $optional_field: expr, option) => {
51                 if let Some(ref field) = $optional_field {
52                         BigSize($optional_type).write($stream)?;
53                         BigSize(field.serialized_length() as u64).write($stream)?;
54                         field.write($stream)?;
55                 }
56         };
57         ($stream: expr, $type: expr, $field: expr, optional_vec) => {
58                 if !$field.is_empty() {
59                         $crate::_encode_tlv!($stream, $type, $field, required_vec);
60                 }
61         };
62         ($stream: expr, $type: expr, $field: expr, upgradable_required) => {
63                 $crate::_encode_tlv!($stream, $type, $field, required);
64         };
65         ($stream: expr, $type: expr, $field: expr, upgradable_option) => {
66                 $crate::_encode_tlv!($stream, $type, $field, option);
67         };
68         ($stream: expr, $type: expr, $field: expr, (option, encoding: ($fieldty: ty, $encoding: ident))) => {
69                 $crate::_encode_tlv!($stream, $type, $field.map(|f| $encoding(f)), option);
70         };
71         ($stream: expr, $type: expr, $field: expr, (option, encoding: $fieldty: ty)) => {
72                 $crate::_encode_tlv!($stream, $type, $field, option);
73         };
74         ($stream: expr, $type: expr, $field: expr, (option: $trait: ident $(, $read_arg: expr)?)) => {
75                 // Just a read-mapped type
76                 $crate::_encode_tlv!($stream, $type, $field, option);
77         };
78 }
79
80 /// Panics if the last seen TLV type is not numerically less than the TLV type currently being checked.
81 /// This is exported for use by other exported macros, do not use directly.
82 #[doc(hidden)]
83 #[macro_export]
84 macro_rules! _check_encoded_tlv_order {
85         ($last_type: expr, $type: expr, (static_value, $value: expr)) => { };
86         ($last_type: expr, $type: expr, $fieldty: tt) => {
87                 if let Some(t) = $last_type {
88                         #[allow(unused_comparisons)] // Note that $type may be 0 making the following comparison always false
89                         (debug_assert!(t < $type))
90                 }
91                 $last_type = Some($type);
92         };
93 }
94
95 /// Implements the TLVs serialization part in a [`Writeable`] implementation of a struct.
96 ///
97 /// This should be called inside a method which returns `Result<_, `[`io::Error`]`>`, such as
98 /// [`Writeable::write`]. It will only return an `Err` if the stream `Err`s or [`Writeable::write`]
99 /// on one of the fields `Err`s.
100 ///
101 /// `$stream` must be a `&mut `[`Writer`] which will receive the bytes for each TLV in the stream.
102 ///
103 /// Fields MUST be sorted in `$type`-order.
104 ///
105 /// Note that the lightning TLV requirements require that a single type not appear more than once,
106 /// that TLVs are sorted in type-ascending order, and that any even types be understood by the
107 /// decoder.
108 ///
109 /// Any `option` fields which have a value of `None` will not be serialized at all.
110 ///
111 /// For example,
112 /// ```
113 /// # use lightning::encode_tlv_stream;
114 /// # fn write<W: lightning::util::ser::Writer> (stream: &mut W) -> Result<(), lightning::io::Error> {
115 /// let mut required_value = 0u64;
116 /// let mut optional_value: Option<u64> = None;
117 /// encode_tlv_stream!(stream, {
118 ///     (0, required_value, required),
119 ///     (1, Some(42u64), option),
120 ///     (2, optional_value, option),
121 /// });
122 /// // At this point `required_value` has been written as a TLV of type 0, `42u64` has been written
123 /// // as a TLV of type 1 (indicating the reader may ignore it if it is not understood), and *no*
124 /// // TLV is written with type 2.
125 /// # Ok(())
126 /// # }
127 /// ```
128 ///
129 /// [`Writeable`]: crate::util::ser::Writeable
130 /// [`io::Error`]: crate::io::Error
131 /// [`Writeable::write`]: crate::util::ser::Writeable::write
132 /// [`Writer`]: crate::util::ser::Writer
133 #[macro_export]
134 macro_rules! encode_tlv_stream {
135         ($stream: expr, {$(($type: expr, $field: expr, $fieldty: tt)),* $(,)*}) => {
136                 $crate::_encode_tlv_stream!($stream, {$(($type, $field, $fieldty)),*})
137         }
138 }
139
140 /// Implementation of [`encode_tlv_stream`].
141 /// This is exported for use by other exported macros, do not use directly.
142 #[doc(hidden)]
143 #[macro_export]
144 macro_rules! _encode_tlv_stream {
145         ($stream: expr, {$(($type: expr, $field: expr, $fieldty: tt)),* $(,)*}) => { {
146                 $crate::_encode_tlv_stream!($stream, { $(($type, $field, $fieldty)),* }, &[])
147         } };
148         ($stream: expr, {$(($type: expr, $field: expr, $fieldty: tt)),* $(,)*}, $extra_tlvs: expr) => { {
149                 #[allow(unused_imports)]
150                 use $crate::{
151                         ln::msgs::DecodeError,
152                         util::ser,
153                         util::ser::BigSize,
154                         util::ser::Writeable,
155                 };
156
157                 $(
158                         $crate::_encode_tlv!($stream, $type, $field, $fieldty);
159                 )*
160                 for tlv in $extra_tlvs {
161                         let (typ, value): &(u64, Vec<u8>) = tlv;
162                         $crate::_encode_tlv!($stream, *typ, *value, required_vec);
163                 }
164
165                 #[allow(unused_mut, unused_variables, unused_assignments)]
166                 #[cfg(debug_assertions)]
167                 {
168                         let mut last_seen: Option<u64> = None;
169                         $(
170                                 $crate::_check_encoded_tlv_order!(last_seen, $type, $fieldty);
171                         )*
172                         for tlv in $extra_tlvs {
173                                 let (typ, _): &(u64, Vec<u8>) = tlv;
174                                 $crate::_check_encoded_tlv_order!(last_seen, *typ, required_vec);
175                         }
176                 }
177         } };
178 }
179
180 /// Adds the length of the serialized field to a [`LengthCalculatingWriter`].
181 /// This is exported for use by other exported macros, do not use directly.
182 ///
183 /// [`LengthCalculatingWriter`]: crate::util::ser::LengthCalculatingWriter
184 #[doc(hidden)]
185 #[macro_export]
186 macro_rules! _get_varint_length_prefixed_tlv_length {
187         ($len: expr, $type: expr, $field: expr, (default_value, $default: expr)) => {
188                 $crate::_get_varint_length_prefixed_tlv_length!($len, $type, $field, required)
189         };
190         ($len: expr, $type: expr, $field: expr, (static_value, $value: expr)) => {
191         };
192         ($len: expr, $type: expr, $field: expr, required) => {
193                 BigSize($type).write(&mut $len).expect("No in-memory data may fail to serialize");
194                 let field_len = $field.serialized_length();
195                 BigSize(field_len as u64).write(&mut $len).expect("No in-memory data may fail to serialize");
196                 $len.0 += field_len;
197         };
198         ($len: expr, $type: expr, $field: expr, required_vec) => {
199                 $crate::_get_varint_length_prefixed_tlv_length!($len, $type, $crate::util::ser::WithoutLength(&$field), required);
200         };
201         ($len: expr, $optional_type: expr, $optional_field: expr, option) => {
202                 if let Some(ref field) = $optional_field {
203                         BigSize($optional_type).write(&mut $len).expect("No in-memory data may fail to serialize");
204                         let field_len = field.serialized_length();
205                         BigSize(field_len as u64).write(&mut $len).expect("No in-memory data may fail to serialize");
206                         $len.0 += field_len;
207                 }
208         };
209         ($len: expr, $type: expr, $field: expr, optional_vec) => {
210                 if !$field.is_empty() {
211                         $crate::_get_varint_length_prefixed_tlv_length!($len, $type, $field, required_vec);
212                 }
213         };
214         ($len: expr, $type: expr, $field: expr, (option: $trait: ident $(, $read_arg: expr)?)) => {
215                 $crate::_get_varint_length_prefixed_tlv_length!($len, $type, $field, option);
216         };
217         ($len: expr, $type: expr, $field: expr, (option, encoding: ($fieldty: ty, $encoding: ident))) => {
218                 $crate::_get_varint_length_prefixed_tlv_length!($len, $type, $field.map(|f| $encoding(f)), option);
219         };
220         ($len: expr, $type: expr, $field: expr, upgradable_required) => {
221                 $crate::_get_varint_length_prefixed_tlv_length!($len, $type, $field, required);
222         };
223         ($len: expr, $type: expr, $field: expr, upgradable_option) => {
224                 $crate::_get_varint_length_prefixed_tlv_length!($len, $type, $field, option);
225         };
226 }
227
228 /// See the documentation of [`write_tlv_fields`].
229 /// This is exported for use by other exported macros, do not use directly.
230 #[doc(hidden)]
231 #[macro_export]
232 macro_rules! _encode_varint_length_prefixed_tlv {
233         ($stream: expr, {$(($type: expr, $field: expr, $fieldty: tt)),*}) => { {
234                 $crate::_encode_varint_length_prefixed_tlv!($stream, {$(($type, $field, $fieldty)),*}, &[])
235         } };
236         ($stream: expr, {$(($type: expr, $field: expr, $fieldty: tt)),*}, $extra_tlvs: expr) => { {
237                 extern crate alloc;
238                 use $crate::util::ser::BigSize;
239                 use alloc::vec::Vec;
240                 let len = {
241                         #[allow(unused_mut)]
242                         let mut len = $crate::util::ser::LengthCalculatingWriter(0);
243                         $(
244                                 $crate::_get_varint_length_prefixed_tlv_length!(len, $type, $field, $fieldty);
245                         )*
246                         for tlv in $extra_tlvs {
247                                 let (typ, value): &(u64, Vec<u8>) = tlv;
248                                 $crate::_get_varint_length_prefixed_tlv_length!(len, *typ, *value, required_vec);
249                         }
250                         len.0
251                 };
252                 BigSize(len as u64).write($stream)?;
253                 $crate::_encode_tlv_stream!($stream, { $(($type, $field, $fieldty)),* }, $extra_tlvs);
254         } };
255 }
256
257 /// Errors if there are missing required TLV types between the last seen type and the type currently being processed.
258 /// This is exported for use by other exported macros, do not use directly.
259 #[doc(hidden)]
260 #[macro_export]
261 macro_rules! _check_decoded_tlv_order {
262         ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, (default_value, $default: expr)) => {{
263                 #[allow(unused_comparisons)] // Note that $type may be 0 making the second comparison always false
264                 let invalid_order = ($last_seen_type.is_none() || $last_seen_type.unwrap() < $type) && $typ.0 > $type;
265                 if invalid_order {
266                         $field = $default.into();
267                 }
268         }};
269         ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, (static_value, $value: expr)) => {
270         };
271         ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, required) => {{
272                 #[allow(unused_comparisons)] // Note that $type may be 0 making the second comparison always false
273                 let invalid_order = ($last_seen_type.is_none() || $last_seen_type.unwrap() < $type) && $typ.0 > $type;
274                 if invalid_order {
275                         return Err(DecodeError::InvalidValue);
276                 }
277         }};
278         ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, (required: $trait: ident $(, $read_arg: expr)?)) => {{
279                 $crate::_check_decoded_tlv_order!($last_seen_type, $typ, $type, $field, required);
280         }};
281         ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, option) => {{
282                 // no-op
283         }};
284         ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, required_vec) => {{
285                 $crate::_check_decoded_tlv_order!($last_seen_type, $typ, $type, $field, required);
286         }};
287         ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, optional_vec) => {{
288                 // no-op
289         }};
290         ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, upgradable_required) => {{
291                 _check_decoded_tlv_order!($last_seen_type, $typ, $type, $field, required)
292         }};
293         ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, upgradable_option) => {{
294                 // no-op
295         }};
296         ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, (option: $trait: ident $(, $read_arg: expr)?)) => {{
297                 // no-op
298         }};
299         ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, (option, encoding: $encoding: tt)) => {{
300                 // no-op
301         }};
302 }
303
304 /// Errors if there are missing required TLV types after the last seen type.
305 /// This is exported for use by other exported macros, do not use directly.
306 #[doc(hidden)]
307 #[macro_export]
308 macro_rules! _check_missing_tlv {
309         ($last_seen_type: expr, $type: expr, $field: ident, (default_value, $default: expr)) => {{
310                 #[allow(unused_comparisons)] // Note that $type may be 0 making the second comparison always false
311                 let missing_req_type = $last_seen_type.is_none() || $last_seen_type.unwrap() < $type;
312                 if missing_req_type {
313                         $field = $default.into();
314                 }
315         }};
316         ($last_seen_type: expr, $type: expr, $field: expr, (static_value, $value: expr)) => {
317                 $field = $value;
318         };
319         ($last_seen_type: expr, $type: expr, $field: ident, required) => {{
320                 #[allow(unused_comparisons)] // Note that $type may be 0 making the second comparison always false
321                 let missing_req_type = $last_seen_type.is_none() || $last_seen_type.unwrap() < $type;
322                 if missing_req_type {
323                         return Err(DecodeError::InvalidValue);
324                 }
325         }};
326         ($last_seen_type: expr, $type: expr, $field: ident, (required: $trait: ident $(, $read_arg: expr)?)) => {{
327                 $crate::_check_missing_tlv!($last_seen_type, $type, $field, required);
328         }};
329         ($last_seen_type: expr, $type: expr, $field: ident, required_vec) => {{
330                 $crate::_check_missing_tlv!($last_seen_type, $type, $field, required);
331         }};
332         ($last_seen_type: expr, $type: expr, $field: ident, option) => {{
333                 // no-op
334         }};
335         ($last_seen_type: expr, $type: expr, $field: ident, optional_vec) => {{
336                 // no-op
337         }};
338         ($last_seen_type: expr, $type: expr, $field: ident, upgradable_required) => {{
339                 _check_missing_tlv!($last_seen_type, $type, $field, required)
340         }};
341         ($last_seen_type: expr, $type: expr, $field: ident, upgradable_option) => {{
342                 // no-op
343         }};
344         ($last_seen_type: expr, $type: expr, $field: ident, (option: $trait: ident $(, $read_arg: expr)?)) => {{
345                 // no-op
346         }};
347         ($last_seen_type: expr, $type: expr, $field: ident, (option, encoding: $encoding: tt)) => {{
348                 // no-op
349         }};
350 }
351
352 /// Implements deserialization for a single TLV record.
353 /// This is exported for use by other exported macros, do not use directly.
354 #[doc(hidden)]
355 #[macro_export]
356 macro_rules! _decode_tlv {
357         ($outer_reader: expr, $reader: expr, $field: ident, (default_value, $default: expr)) => {{
358                 $crate::_decode_tlv!($outer_reader, $reader, $field, required)
359         }};
360         ($outer_reader: expr, $reader: expr, $field: ident, (static_value, $value: expr)) => {{
361         }};
362         ($outer_reader: expr, $reader: expr, $field: ident, required) => {{
363                 $field = $crate::util::ser::Readable::read(&mut $reader)?;
364         }};
365         ($outer_reader: expr, $reader: expr, $field: ident, (required: $trait: ident $(, $read_arg: expr)?)) => {{
366                 $field = $trait::read(&mut $reader $(, $read_arg)*)?;
367         }};
368         ($outer_reader: expr, $reader: expr, $field: ident, required_vec) => {{
369                 let f: $crate::util::ser::WithoutLength<Vec<_>> = $crate::util::ser::Readable::read(&mut $reader)?;
370                 $field = f.0;
371         }};
372         ($outer_reader: expr, $reader: expr, $field: ident, option) => {{
373                 $field = Some($crate::util::ser::Readable::read(&mut $reader)?);
374         }};
375         ($outer_reader: expr, $reader: expr, $field: ident, optional_vec) => {{
376                 let f: $crate::util::ser::WithoutLength<Vec<_>> = $crate::util::ser::Readable::read(&mut $reader)?;
377                 $field = Some(f.0);
378         }};
379         // `upgradable_required` indicates we're reading a required TLV that may have been upgraded
380         // without backwards compat. We'll error if the field is missing, and return `Ok(None)` if the
381         // field is present but we can no longer understand it.
382         // Note that this variant can only be used within a `MaybeReadable` read.
383         ($outer_reader: expr, $reader: expr, $field: ident, upgradable_required) => {{
384                 $field = match $crate::util::ser::MaybeReadable::read(&mut $reader)? {
385                         Some(res) => res,
386                         None => {
387                                 // If we successfully read a value but we don't know how to parse it, we give up
388                                 // and immediately return `None`. However, we need to make sure we read the correct
389                                 // number of bytes for this TLV stream, which is implicitly the end of the stream.
390                                 // Thus, we consume everything left in the `$outer_reader` here, ensuring that if
391                                 // we're being read as a part of another TLV stream we don't spuriously fail to
392                                 // deserialize the outer object due to a TLV length mismatch.
393                                 $crate::io_extras::copy($outer_reader, &mut $crate::io_extras::sink()).unwrap();
394                                 return Ok(None)
395                         },
396                 };
397         }};
398         // `upgradable_option` indicates we're reading an Option-al TLV that may have been upgraded
399         // without backwards compat. $field will be None if the TLV is missing or if the field is present
400         // but we can no longer understand it.
401         ($outer_reader: expr, $reader: expr, $field: ident, upgradable_option) => {{
402                 $field = $crate::util::ser::MaybeReadable::read(&mut $reader)?;
403         }};
404         ($outer_reader: expr, $reader: expr, $field: ident, (option: $trait: ident $(, $read_arg: expr)?)) => {{
405                 $field = Some($trait::read(&mut $reader $(, $read_arg)*)?);
406         }};
407         ($outer_reader: expr, $reader: expr, $field: ident, (option, encoding: ($fieldty: ty, $encoding: ident, $encoder:ty))) => {{
408                 $crate::_decode_tlv!($outer_reader, $reader, $field, (option, encoding: ($fieldty, $encoding)));
409         }};
410         ($outer_reader: expr, $reader: expr, $field: ident, (option, encoding: ($fieldty: ty, $encoding: ident))) => {{
411                 $field = {
412                         let field: $encoding<$fieldty> = ser::Readable::read(&mut $reader)?;
413                         Some(field.0)
414                 };
415         }};
416         ($outer_reader: expr, $reader: expr, $field: ident, (option, encoding: $fieldty: ty)) => {{
417                 $crate::_decode_tlv!($outer_reader, $reader, $field, option);
418         }};
419 }
420
421 /// Checks if `$val` matches `$type`.
422 /// This is exported for use by other exported macros, do not use directly.
423 #[doc(hidden)]
424 #[macro_export]
425 macro_rules! _decode_tlv_stream_match_check {
426         ($val: ident, $type: expr, (static_value, $value: expr)) => { false };
427         ($val: ident, $type: expr, $fieldty: tt) => { $val == $type }
428 }
429
430 /// Implements the TLVs deserialization part in a [`Readable`] implementation of a struct.
431 ///
432 /// This should be called inside a method which returns `Result<_, `[`DecodeError`]`>`, such as
433 /// [`Readable::read`]. It will either return an `Err` or ensure all `required` fields have been
434 /// read and optionally read `optional` fields.
435 ///
436 /// `$stream` must be a [`Read`] and will be fully consumed, reading until no more bytes remain
437 /// (i.e. it returns [`DecodeError::ShortRead`]).
438 ///
439 /// Fields MUST be sorted in `$type`-order.
440 ///
441 /// Note that the lightning TLV requirements require that a single type not appear more than once,
442 /// that TLVs are sorted in type-ascending order, and that any even types be understood by the
443 /// decoder.
444 ///
445 /// For example,
446 /// ```
447 /// # use lightning::decode_tlv_stream;
448 /// # fn read<R: lightning::io::Read> (stream: R) -> Result<(), lightning::ln::msgs::DecodeError> {
449 /// let mut required_value = 0u64;
450 /// let mut optional_value: Option<u64> = None;
451 /// decode_tlv_stream!(stream, {
452 ///     (0, required_value, required),
453 ///     (2, optional_value, option),
454 /// });
455 /// // At this point, `required_value` has been overwritten with the TLV with type 0.
456 /// // `optional_value` may have been overwritten, setting it to `Some` if a TLV with type 2 was
457 /// // present.
458 /// # Ok(())
459 /// # }
460 /// ```
461 ///
462 /// [`Readable`]: crate::util::ser::Readable
463 /// [`DecodeError`]: crate::ln::msgs::DecodeError
464 /// [`Readable::read`]: crate::util::ser::Readable::read
465 /// [`Read`]: crate::io::Read
466 /// [`DecodeError::ShortRead`]: crate::ln::msgs::DecodeError::ShortRead
467 #[macro_export]
468 macro_rules! decode_tlv_stream {
469         ($stream: expr, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}) => {
470                 let rewind = |_, _| { unreachable!() };
471                 $crate::_decode_tlv_stream_range!($stream, .., rewind, {$(($type, $field, $fieldty)),*});
472         }
473 }
474
475 /// Similar to [`decode_tlv_stream`] with a custom TLV decoding capabilities.
476 ///
477 /// `$decode_custom_tlv` is a closure that may be optionally provided to handle custom message types.
478 /// If it is provided, it will be called with the custom type and the [`FixedLengthReader`] containing
479 /// the message contents. It should return `Ok(true)` if the custom message is successfully parsed,
480 /// `Ok(false)` if the message type is unknown, and `Err(`[`DecodeError`]`)` if parsing fails.
481 ///
482 /// [`FixedLengthReader`]: crate::util::ser::FixedLengthReader
483 /// [`DecodeError`]: crate::ln::msgs::DecodeError
484 macro_rules! decode_tlv_stream_with_custom_tlv_decode {
485         ($stream: expr, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}
486          $(, $decode_custom_tlv: expr)?) => { {
487                 let rewind = |_, _| { unreachable!() };
488                 _decode_tlv_stream_range!(
489                         $stream, .., rewind, {$(($type, $field, $fieldty)),*} $(, $decode_custom_tlv)?
490                 );
491         } }
492 }
493
494 #[doc(hidden)]
495 #[macro_export]
496 macro_rules! _decode_tlv_stream_range {
497         ($stream: expr, $range: expr, $rewind: ident, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}
498          $(, $decode_custom_tlv: expr)?) => { {
499                 use $crate::ln::msgs::DecodeError;
500                 let mut last_seen_type: Option<u64> = None;
501                 let mut stream_ref = $stream;
502                 'tlv_read: loop {
503                         use $crate::util::ser;
504
505                         // First decode the type of this TLV:
506                         let typ: ser::BigSize = {
507                                 // We track whether any bytes were read during the consensus_decode call to
508                                 // determine whether we should break or return ShortRead if we get an
509                                 // UnexpectedEof. This should in every case be largely cosmetic, but its nice to
510                                 // pass the TLV test vectors exactly, which require this distinction.
511                                 let mut tracking_reader = ser::ReadTrackingReader::new(&mut stream_ref);
512                                 match <$crate::util::ser::BigSize as $crate::util::ser::Readable>::read(&mut tracking_reader) {
513                                         Err(DecodeError::ShortRead) => {
514                                                 if !tracking_reader.have_read {
515                                                         break 'tlv_read;
516                                                 } else {
517                                                         return Err(DecodeError::ShortRead);
518                                                 }
519                                         },
520                                         Err(e) => return Err(e),
521                                         Ok(t) => if core::ops::RangeBounds::contains(&$range, &t.0) { t } else {
522                                                 drop(tracking_reader);
523
524                                                 // Assumes the type id is minimally encoded, which is enforced on read.
525                                                 use $crate::util::ser::Writeable;
526                                                 let bytes_read = t.serialized_length();
527                                                 $rewind(stream_ref, bytes_read);
528                                                 break 'tlv_read;
529                                         },
530                                 }
531                         };
532
533                         // Types must be unique and monotonically increasing:
534                         match last_seen_type {
535                                 Some(t) if typ.0 <= t => {
536                                         return Err(DecodeError::InvalidValue);
537                                 },
538                                 _ => {},
539                         }
540                         // As we read types, make sure we hit every required type between `last_seen_type` and `typ`:
541                         $({
542                                 $crate::_check_decoded_tlv_order!(last_seen_type, typ, $type, $field, $fieldty);
543                         })*
544                         last_seen_type = Some(typ.0);
545
546                         // Finally, read the length and value itself:
547                         let length: ser::BigSize = $crate::util::ser::Readable::read(&mut stream_ref)?;
548                         let mut s = ser::FixedLengthReader::new(&mut stream_ref, length.0);
549                         match typ.0 {
550                                 $(_t if $crate::_decode_tlv_stream_match_check!(_t, $type, $fieldty) => {
551                                         $crate::_decode_tlv!($stream, s, $field, $fieldty);
552                                         if s.bytes_remain() {
553                                                 s.eat_remaining()?; // Return ShortRead if there's actually not enough bytes
554                                                 return Err(DecodeError::InvalidValue);
555                                         }
556                                 },)*
557                                 t => {
558                                         $(
559                                                 if $decode_custom_tlv(t, &mut s)? {
560                                                         // If a custom TLV was successfully read (i.e. decode_custom_tlv returns true),
561                                                         // continue to the next TLV read.
562                                                         s.eat_remaining()?;
563                                                         continue 'tlv_read;
564                                                 }
565                                         )?
566                                         if t % 2 == 0 {
567                                                 return Err(DecodeError::UnknownRequiredFeature);
568                                         }
569                                 }
570                         }
571                         s.eat_remaining()?;
572                 }
573                 // Make sure we got to each required type after we've read every TLV:
574                 $({
575                         $crate::_check_missing_tlv!(last_seen_type, $type, $field, $fieldty);
576                 })*
577         } }
578 }
579
580 /// Implements [`Readable`]/[`Writeable`] for a message struct that may include non-TLV and
581 /// TLV-encoded parts.
582 ///
583 /// This is useful to implement a [`CustomMessageReader`].
584 ///
585 /// Currently `$fieldty` may only be `option`, i.e., `$tlvfield` is optional field.
586 ///
587 /// For example,
588 /// ```
589 /// # use lightning::impl_writeable_msg;
590 /// struct MyCustomMessage {
591 ///     pub field_1: u32,
592 ///     pub field_2: bool,
593 ///     pub field_3: String,
594 ///     pub tlv_optional_integer: Option<u32>,
595 /// }
596 ///
597 /// impl_writeable_msg!(MyCustomMessage, {
598 ///     field_1,
599 ///     field_2,
600 ///     field_3
601 /// }, {
602 ///     (1, tlv_optional_integer, option),
603 /// });
604 /// ```
605 ///
606 /// [`Readable`]: crate::util::ser::Readable
607 /// [`Writeable`]: crate::util::ser::Writeable
608 /// [`CustomMessageReader`]: crate::ln::wire::CustomMessageReader
609 #[macro_export]
610 macro_rules! impl_writeable_msg {
611         ($st:ident, {$($field:ident),* $(,)*}, {$(($type: expr, $tlvfield: ident, $fieldty: tt)),* $(,)*}) => {
612                 impl $crate::util::ser::Writeable for $st {
613                         fn write<W: $crate::util::ser::Writer>(&self, w: &mut W) -> Result<(), $crate::io::Error> {
614                                 $( self.$field.write(w)?; )*
615                                 $crate::encode_tlv_stream!(w, {$(($type, self.$tlvfield.as_ref(), $fieldty)),*});
616                                 Ok(())
617                         }
618                 }
619                 impl $crate::util::ser::Readable for $st {
620                         fn read<R: $crate::io::Read>(r: &mut R) -> Result<Self, $crate::ln::msgs::DecodeError> {
621                                 $(let $field = $crate::util::ser::Readable::read(r)?;)*
622                                 $($crate::_init_tlv_field_var!($tlvfield, $fieldty);)*
623                                 $crate::decode_tlv_stream!(r, {$(($type, $tlvfield, $fieldty)),*});
624                                 Ok(Self {
625                                         $($field),*,
626                                         $($tlvfield),*
627                                 })
628                         }
629                 }
630         }
631 }
632
633 macro_rules! impl_writeable {
634         ($st:ident, {$($field:ident),*}) => {
635                 impl $crate::util::ser::Writeable for $st {
636                         fn write<W: $crate::util::ser::Writer>(&self, w: &mut W) -> Result<(), $crate::io::Error> {
637                                 $( self.$field.write(w)?; )*
638                                 Ok(())
639                         }
640
641                         #[inline]
642                         fn serialized_length(&self) -> usize {
643                                 let mut len_calc = 0;
644                                 $( len_calc += self.$field.serialized_length(); )*
645                                 return len_calc;
646                         }
647                 }
648
649                 impl $crate::util::ser::Readable for $st {
650                         fn read<R: $crate::io::Read>(r: &mut R) -> Result<Self, $crate::ln::msgs::DecodeError> {
651                                 Ok(Self {
652                                         $($field: $crate::util::ser::Readable::read(r)?),*
653                                 })
654                         }
655                 }
656         }
657 }
658
659 /// Write out two bytes to indicate the version of an object.
660 ///
661 /// $this_version represents a unique version of a type. Incremented whenever the type's
662 /// serialization format has changed or has a new interpretation. Used by a type's reader to
663 /// determine how to interpret fields or if it can understand a serialized object.
664 ///
665 /// $min_version_that_can_read_this is the minimum reader version which can understand this
666 /// serialized object. Previous versions will simply err with a [`DecodeError::UnknownVersion`].
667 ///
668 /// Updates to either `$this_version` or `$min_version_that_can_read_this` should be included in
669 /// release notes.
670 ///
671 /// Both version fields can be specific to this type of object.
672 ///
673 /// [`DecodeError::UnknownVersion`]: crate::ln::msgs::DecodeError::UnknownVersion
674 macro_rules! write_ver_prefix {
675         ($stream: expr, $this_version: expr, $min_version_that_can_read_this: expr) => {
676                 $stream.write_all(&[$this_version; 1])?;
677                 $stream.write_all(&[$min_version_that_can_read_this; 1])?;
678         }
679 }
680
681 /// Writes out a suffix to an object as a length-prefixed TLV stream which contains potentially
682 /// backwards-compatible, optional fields which old nodes can happily ignore.
683 ///
684 /// It is written out in TLV format and, as with all TLV fields, unknown even fields cause a
685 /// [`DecodeError::UnknownRequiredFeature`] error, with unknown odd fields ignored.
686 ///
687 /// This is the preferred method of adding new fields that old nodes can ignore and still function
688 /// correctly.
689 ///
690 /// [`DecodeError::UnknownRequiredFeature`]: crate::ln::msgs::DecodeError::UnknownRequiredFeature
691 #[macro_export]
692 macro_rules! write_tlv_fields {
693         ($stream: expr, {$(($type: expr, $field: expr, $fieldty: tt)),* $(,)*}) => {
694                 $crate::_encode_varint_length_prefixed_tlv!($stream, {$(($type, $field, $fieldty)),*})
695         }
696 }
697
698 /// Reads a prefix added by [`write_ver_prefix`], above. Takes the current version of the
699 /// serialization logic for this object. This is compared against the
700 /// `$min_version_that_can_read_this` added by [`write_ver_prefix`].
701 macro_rules! read_ver_prefix {
702         ($stream: expr, $this_version: expr) => { {
703                 let ver: u8 = Readable::read($stream)?;
704                 let min_ver: u8 = Readable::read($stream)?;
705                 if min_ver > $this_version {
706                         return Err(DecodeError::UnknownVersion);
707                 }
708                 ver
709         } }
710 }
711
712 /// Reads a suffix added by [`write_tlv_fields`].
713 ///
714 /// [`write_tlv_fields`]: crate::write_tlv_fields
715 #[macro_export]
716 macro_rules! read_tlv_fields {
717         ($stream: expr, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}) => { {
718                 let tlv_len: $crate::util::ser::BigSize = $crate::util::ser::Readable::read($stream)?;
719                 let mut rd = $crate::util::ser::FixedLengthReader::new($stream, tlv_len.0);
720                 $crate::decode_tlv_stream!(&mut rd, {$(($type, $field, $fieldty)),*});
721                 rd.eat_remaining().map_err(|_| $crate::ln::msgs::DecodeError::ShortRead)?;
722         } }
723 }
724
725 /// Initializes the struct fields.
726 ///
727 /// This is exported for use by other exported macros, do not use directly.
728 #[doc(hidden)]
729 #[macro_export]
730 macro_rules! _init_tlv_based_struct_field {
731         ($field: ident, (default_value, $default: expr)) => {
732                 $field.0.unwrap()
733         };
734         ($field: ident, (static_value, $value: expr)) => {
735                 $field
736         };
737         ($field: ident, option) => {
738                 $field
739         };
740         ($field: ident, (option: $trait: ident $(, $read_arg: expr)?)) => {
741                 $crate::_init_tlv_based_struct_field!($field, option)
742         };
743         ($field: ident, upgradable_required) => {
744                 $field.0.unwrap()
745         };
746         ($field: ident, upgradable_option) => {
747                 $field
748         };
749         ($field: ident, required) => {
750                 $field.0.unwrap()
751         };
752         ($field: ident, required_vec) => {
753                 $field
754         };
755         ($field: ident, optional_vec) => {
756                 $field.unwrap()
757         };
758 }
759
760 /// Initializes the variable we are going to read the TLV into.
761 ///
762 /// This is exported for use by other exported macros, do not use directly.
763 #[doc(hidden)]
764 #[macro_export]
765 macro_rules! _init_tlv_field_var {
766         ($field: ident, (default_value, $default: expr)) => {
767                 let mut $field = $crate::util::ser::RequiredWrapper(None);
768         };
769         ($field: ident, (static_value, $value: expr)) => {
770                 let $field;
771         };
772         ($field: ident, required) => {
773                 let mut $field = $crate::util::ser::RequiredWrapper(None);
774         };
775         ($field: ident, (required: $trait: ident $(, $read_arg: expr)?)) => {
776                 $crate::_init_tlv_field_var!($field, required);
777         };
778         ($field: ident, required_vec) => {
779                 let mut $field = Vec::new();
780         };
781         ($field: ident, option) => {
782                 let mut $field = None;
783         };
784         ($field: ident, optional_vec) => {
785                 let mut $field = Some(Vec::new());
786         };
787         ($field: ident, (option, encoding: ($fieldty: ty, $encoding: ident))) => {
788                 $crate::_init_tlv_field_var!($field, option);
789         };
790         ($field: ident, (option: $trait: ident $(, $read_arg: expr)?)) => {
791                 $crate::_init_tlv_field_var!($field, option);
792         };
793         ($field: ident, upgradable_required) => {
794                 let mut $field = $crate::util::ser::UpgradableRequired(None);
795         };
796         ($field: ident, upgradable_option) => {
797                 let mut $field = None;
798         };
799 }
800
801 /// Equivalent to running [`_init_tlv_field_var`] then [`read_tlv_fields`].
802 ///
803 /// If any unused values are read, their type MUST be specified or else `rustc` will read them as an
804 /// `i64`.
805 ///
806 /// This is exported for use by other exported macros, do not use directly.
807 #[doc(hidden)]
808 #[macro_export]
809 macro_rules! _init_and_read_len_prefixed_tlv_fields {
810         ($reader: ident, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}) => {
811                 $(
812                         $crate::_init_tlv_field_var!($field, $fieldty);
813                 )*
814
815                 $crate::read_tlv_fields!($reader, {
816                         $(($type, $field, $fieldty)),*
817                 });
818         }
819 }
820
821 /// Equivalent to running [`_init_tlv_field_var`] then [`decode_tlv_stream`].
822 ///
823 /// If any unused values are read, their type MUST be specified or else `rustc` will read them as an
824 /// `i64`.
825 macro_rules! _init_and_read_tlv_stream {
826         ($reader: ident, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}) => {
827                 $(
828                         $crate::_init_tlv_field_var!($field, $fieldty);
829                 )*
830
831                 $crate::decode_tlv_stream!($reader, {
832                         $(($type, $field, $fieldty)),*
833                 });
834         }
835 }
836
837 /// Implements [`Readable`]/[`Writeable`] for a struct storing it as a set of TLVs
838 /// If `$fieldty` is `required`, then `$field` is a required field that is not an [`Option`] nor a [`Vec`].
839 /// If `$fieldty` is `(default_value, $default)`, then `$field` will be set to `$default` if not present.
840 /// If `$fieldty` is `option`, then `$field` is optional field.
841 /// If `$fieldty` is `optional_vec`, then `$field` is a [`Vec`], which needs to have its individual elements serialized.
842 ///    Note that for `optional_vec` no bytes are written if the vec is empty
843 ///
844 /// For example,
845 /// ```
846 /// # use lightning::impl_writeable_tlv_based;
847 /// struct LightningMessage {
848 ///     tlv_integer: u32,
849 ///     tlv_default_integer: u32,
850 ///     tlv_optional_integer: Option<u32>,
851 ///     tlv_vec_type_integer: Vec<u32>,
852 /// }
853 ///
854 /// impl_writeable_tlv_based!(LightningMessage, {
855 ///     (0, tlv_integer, required),
856 ///     (1, tlv_default_integer, (default_value, 7)),
857 ///     (2, tlv_optional_integer, option),
858 ///     (3, tlv_vec_type_integer, optional_vec),
859 /// });
860 /// ```
861 ///
862 /// [`Readable`]: crate::util::ser::Readable
863 /// [`Writeable`]: crate::util::ser::Writeable
864 #[macro_export]
865 macro_rules! impl_writeable_tlv_based {
866         ($st: ident, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}) => {
867                 impl $crate::util::ser::Writeable for $st {
868                         fn write<W: $crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), $crate::io::Error> {
869                                 $crate::write_tlv_fields!(writer, {
870                                         $(($type, self.$field, $fieldty)),*
871                                 });
872                                 Ok(())
873                         }
874
875                         #[inline]
876                         fn serialized_length(&self) -> usize {
877                                 use $crate::util::ser::BigSize;
878                                 let len = {
879                                         #[allow(unused_mut)]
880                                         let mut len = $crate::util::ser::LengthCalculatingWriter(0);
881                                         $(
882                                                 $crate::_get_varint_length_prefixed_tlv_length!(len, $type, self.$field, $fieldty);
883                                         )*
884                                         len.0
885                                 };
886                                 let mut len_calc = $crate::util::ser::LengthCalculatingWriter(0);
887                                 BigSize(len as u64).write(&mut len_calc).expect("No in-memory data may fail to serialize");
888                                 len + len_calc.0
889                         }
890                 }
891
892                 impl $crate::util::ser::Readable for $st {
893                         fn read<R: $crate::io::Read>(reader: &mut R) -> Result<Self, $crate::ln::msgs::DecodeError> {
894                                 $crate::_init_and_read_len_prefixed_tlv_fields!(reader, {
895                                         $(($type, $field, $fieldty)),*
896                                 });
897                                 Ok(Self {
898                                         $(
899                                                 $field: $crate::_init_tlv_based_struct_field!($field, $fieldty)
900                                         ),*
901                                 })
902                         }
903                 }
904         }
905 }
906
907 /// Defines a struct for a TLV stream and a similar struct using references for non-primitive types,
908 /// implementing [`Readable`] for the former and [`Writeable`] for the latter. Useful as an
909 /// intermediary format when reading or writing a type encoded as a TLV stream. Note that each field
910 /// representing a TLV record has its type wrapped with an [`Option`]. A tuple consisting of a type
911 /// and a serialization wrapper may be given in place of a type when custom serialization is
912 /// required.
913 ///
914 /// [`Readable`]: crate::util::ser::Readable
915 /// [`Writeable`]: crate::util::ser::Writeable
916 macro_rules! tlv_stream {
917         ($name:ident, $nameref:ident, $range:expr, {
918                 $(($type:expr, $field:ident : $fieldty:tt)),* $(,)*
919         }) => {
920                 #[derive(Debug)]
921                 pub(super) struct $name {
922                         $(
923                                 pub(super) $field: Option<tlv_record_type!($fieldty)>,
924                         )*
925                 }
926
927                 #[cfg_attr(test, derive(PartialEq))]
928                 #[derive(Debug)]
929                 pub(crate) struct $nameref<'a> {
930                         $(
931                                 pub(super) $field: Option<tlv_record_ref_type!($fieldty)>,
932                         )*
933                 }
934
935                 impl<'a> $crate::util::ser::Writeable for $nameref<'a> {
936                         fn write<W: $crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), $crate::io::Error> {
937                                 encode_tlv_stream!(writer, {
938                                         $(($type, self.$field, (option, encoding: $fieldty))),*
939                                 });
940                                 Ok(())
941                         }
942                 }
943
944                 impl $crate::util::ser::SeekReadable for $name {
945                         fn read<R: $crate::io::Read + $crate::io::Seek>(reader: &mut R) -> Result<Self, $crate::ln::msgs::DecodeError> {
946                                 $(
947                                         _init_tlv_field_var!($field, option);
948                                 )*
949                                 let rewind = |cursor: &mut R, offset: usize| {
950                                         cursor.seek($crate::io::SeekFrom::Current(-(offset as i64))).expect("");
951                                 };
952                                 _decode_tlv_stream_range!(reader, $range, rewind, {
953                                         $(($type, $field, (option, encoding: $fieldty))),*
954                                 });
955
956                                 Ok(Self {
957                                         $(
958                                                 $field: $field
959                                         ),*
960                                 })
961                         }
962                 }
963         }
964 }
965
966 macro_rules! tlv_record_type {
967         (($type:ty, $wrapper:ident)) => { $type };
968         (($type:ty, $wrapper:ident, $encoder:ty)) => { $type };
969         ($type:ty) => { $type };
970 }
971
972 macro_rules! tlv_record_ref_type {
973         (char) => { char };
974         (u8) => { u8 };
975         ((u16, $wrapper: ident)) => { u16 };
976         ((u32, $wrapper: ident)) => { u32 };
977         ((u64, $wrapper: ident)) => { u64 };
978         (($type:ty, $wrapper:ident)) => { &'a $type };
979         (($type:ty, $wrapper:ident, $encoder:ty)) => { $encoder };
980         ($type:ty) => { &'a $type };
981 }
982
983 #[doc(hidden)]
984 #[macro_export]
985 macro_rules! _impl_writeable_tlv_based_enum_common {
986         ($st: ident, $(($variant_id: expr, $variant_name: ident) =>
987                 {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}
988         ),* $(,)*;
989         $(($tuple_variant_id: expr, $tuple_variant_name: ident)),*  $(,)*) => {
990                 impl $crate::util::ser::Writeable for $st {
991                         fn write<W: $crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), $crate::io::Error> {
992                                 match self {
993                                         $($st::$variant_name { $(ref $field),* } => {
994                                                 let id: u8 = $variant_id;
995                                                 id.write(writer)?;
996                                                 $crate::write_tlv_fields!(writer, {
997                                                         $(($type, *$field, $fieldty)),*
998                                                 });
999                                         }),*
1000                                         $($st::$tuple_variant_name (ref field) => {
1001                                                 let id: u8 = $tuple_variant_id;
1002                                                 id.write(writer)?;
1003                                                 field.write(writer)?;
1004                                         }),*
1005                                 }
1006                                 Ok(())
1007                         }
1008                 }
1009         }
1010 }
1011
1012 /// Implement [`Readable`] and [`Writeable`] for an enum, with struct variants stored as TLVs and tuple
1013 /// variants stored directly.
1014 /// The format is, for example
1015 /// ```ignore
1016 /// impl_writeable_tlv_based_enum!(EnumName,
1017 ///   (0, StructVariantA) => {(0, required_variant_field, required), (1, optional_variant_field, option)},
1018 ///   (1, StructVariantB) => {(0, variant_field_a, required), (1, variant_field_b, required), (2, variant_vec_field, optional_vec)};
1019 ///   (2, TupleVariantA), (3, TupleVariantB),
1020 /// );
1021 /// ```
1022 /// The type is written as a single byte, followed by any variant data.
1023 /// Attempts to read an unknown type byte result in [`DecodeError::UnknownRequiredFeature`].
1024 ///
1025 /// [`Readable`]: crate::util::ser::Readable
1026 /// [`Writeable`]: crate::util::ser::Writeable
1027 /// [`DecodeError::UnknownRequiredFeature`]: crate::ln::msgs::DecodeError::UnknownRequiredFeature
1028 #[macro_export]
1029 macro_rules! impl_writeable_tlv_based_enum {
1030         ($st: ident, $(($variant_id: expr, $variant_name: ident) =>
1031                 {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}
1032         ),* $(,)*;
1033         $(($tuple_variant_id: expr, $tuple_variant_name: ident)),*  $(,)*) => {
1034                 $crate::_impl_writeable_tlv_based_enum_common!($st,
1035                         $(($variant_id, $variant_name) => {$(($type, $field, $fieldty)),*}),*;
1036                         $(($tuple_variant_id, $tuple_variant_name)),*);
1037
1038                 impl $crate::util::ser::Readable for $st {
1039                         fn read<R: $crate::io::Read>(reader: &mut R) -> Result<Self, $crate::ln::msgs::DecodeError> {
1040                                 let id: u8 = $crate::util::ser::Readable::read(reader)?;
1041                                 match id {
1042                                         $($variant_id => {
1043                                                 // Because read_tlv_fields creates a labeled loop, we cannot call it twice
1044                                                 // in the same function body. Instead, we define a closure and call it.
1045                                                 let f = || {
1046                                                         $crate::_init_and_read_len_prefixed_tlv_fields!(reader, {
1047                                                                 $(($type, $field, $fieldty)),*
1048                                                         });
1049                                                         Ok($st::$variant_name {
1050                                                                 $(
1051                                                                         $field: $crate::_init_tlv_based_struct_field!($field, $fieldty)
1052                                                                 ),*
1053                                                         })
1054                                                 };
1055                                                 f()
1056                                         }),*
1057                                         $($tuple_variant_id => {
1058                                                 Ok($st::$tuple_variant_name($crate::util::ser::Readable::read(reader)?))
1059                                         }),*
1060                                         _ => {
1061                                                 Err($crate::ln::msgs::DecodeError::UnknownRequiredFeature)
1062                                         },
1063                                 }
1064                         }
1065                 }
1066         }
1067 }
1068
1069 /// Implement [`MaybeReadable`] and [`Writeable`] for an enum, with struct variants stored as TLVs and
1070 /// tuple variants stored directly.
1071 ///
1072 /// This is largely identical to [`impl_writeable_tlv_based_enum`], except that odd variants will
1073 /// return `Ok(None)` instead of `Err(`[`DecodeError::UnknownRequiredFeature`]`)`. It should generally be preferred
1074 /// when [`MaybeReadable`] is practical instead of just [`Readable`] as it provides an upgrade path for
1075 /// new variants to be added which are simply ignored by existing clients.
1076 ///
1077 /// Note that only struct and unit variants (not tuple variants) will support downgrading, thus any
1078 /// new odd variants MUST be non-tuple (i.e. described using `$variant_id` and `$variant_name` not
1079 /// `$tuple_variant_id` and `$tuple_variant_name`).
1080 ///
1081 /// [`MaybeReadable`]: crate::util::ser::MaybeReadable
1082 /// [`Writeable`]: crate::util::ser::Writeable
1083 /// [`DecodeError::UnknownRequiredFeature`]: crate::ln::msgs::DecodeError::UnknownRequiredFeature
1084 /// [`Readable`]: crate::util::ser::Readable
1085 #[macro_export]
1086 macro_rules! impl_writeable_tlv_based_enum_upgradable {
1087         ($st: ident, $(($variant_id: expr, $variant_name: ident) =>
1088                 {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}
1089         ),* $(,)*
1090         $(;
1091         $(($tuple_variant_id: expr, $tuple_variant_name: ident)),*  $(,)*)*) => {
1092                 $crate::_impl_writeable_tlv_based_enum_common!($st,
1093                         $(($variant_id, $variant_name) => {$(($type, $field, $fieldty)),*}),*;
1094                         $($(($tuple_variant_id, $tuple_variant_name)),*)*);
1095
1096                 impl $crate::util::ser::MaybeReadable for $st {
1097                         fn read<R: $crate::io::Read>(reader: &mut R) -> Result<Option<Self>, $crate::ln::msgs::DecodeError> {
1098                                 let id: u8 = $crate::util::ser::Readable::read(reader)?;
1099                                 match id {
1100                                         $($variant_id => {
1101                                                 // Because read_tlv_fields creates a labeled loop, we cannot call it twice
1102                                                 // in the same function body. Instead, we define a closure and call it.
1103                                                 let f = || {
1104                                                         $crate::_init_and_read_len_prefixed_tlv_fields!(reader, {
1105                                                                 $(($type, $field, $fieldty)),*
1106                                                         });
1107                                                         Ok(Some($st::$variant_name {
1108                                                                 $(
1109                                                                         $field: $crate::_init_tlv_based_struct_field!($field, $fieldty)
1110                                                                 ),*
1111                                                         }))
1112                                                 };
1113                                                 f()
1114                                         }),*
1115                                         $($($tuple_variant_id => {
1116                                                 Ok(Some($st::$tuple_variant_name(Readable::read(reader)?)))
1117                                         }),*)*
1118                                         _ if id % 2 == 1 => {
1119                                                 // Assume that a $variant_id was written, not a $tuple_variant_id, and read
1120                                                 // the length prefix and discard the correct number of bytes.
1121                                                 let tlv_len: $crate::util::ser::BigSize = $crate::util::ser::Readable::read(reader)?;
1122                                                 let mut rd = $crate::util::ser::FixedLengthReader::new(reader, tlv_len.0);
1123                                                 rd.eat_remaining().map_err(|_| $crate::ln::msgs::DecodeError::ShortRead)?;
1124                                                 Ok(None)
1125                                         },
1126                                         _ => Err($crate::ln::msgs::DecodeError::UnknownRequiredFeature),
1127                                 }
1128                         }
1129                 }
1130         }
1131 }
1132
1133 #[cfg(test)]
1134 mod tests {
1135         use crate::io::{self, Cursor};
1136         use crate::prelude::*;
1137         use crate::ln::msgs::DecodeError;
1138         use crate::util::ser::{Writeable, HighZeroBytesDroppedBigSize, VecWriter};
1139         use bitcoin::hashes::hex::FromHex;
1140         use bitcoin::secp256k1::PublicKey;
1141
1142         // The BOLT TLV test cases don't include any tests which use our "required-value" logic since
1143         // the encoding layer in the BOLTs has no such concept, though it makes our macros easier to
1144         // work with so they're baked into the decoder. Thus, we have a few additional tests below
1145         fn tlv_reader(s: &[u8]) -> Result<(u64, u32, Option<u32>), DecodeError> {
1146                 let mut s = Cursor::new(s);
1147                 let mut a: u64 = 0;
1148                 let mut b: u32 = 0;
1149                 let mut c: Option<u32> = None;
1150                 decode_tlv_stream!(&mut s, {(2, a, required), (3, b, required), (4, c, option)});
1151                 Ok((a, b, c))
1152         }
1153
1154         #[test]
1155         fn tlv_v_short_read() {
1156                 // We only expect a u32 for type 3 (which we are given), but the L says its 8 bytes.
1157                 if let Err(DecodeError::ShortRead) = tlv_reader(&<Vec<u8>>::from_hex(
1158                                 concat!("0100", "0208deadbeef1badbeef", "0308deadbeef")
1159                                 ).unwrap()[..]) {
1160                 } else { panic!(); }
1161         }
1162
1163         #[test]
1164         fn tlv_types_out_of_order() {
1165                 if let Err(DecodeError::InvalidValue) = tlv_reader(&<Vec<u8>>::from_hex(
1166                                 concat!("0100", "0304deadbeef", "0208deadbeef1badbeef")
1167                                 ).unwrap()[..]) {
1168                 } else { panic!(); }
1169                 // ...even if its some field we don't understand
1170                 if let Err(DecodeError::InvalidValue) = tlv_reader(&<Vec<u8>>::from_hex(
1171                                 concat!("0208deadbeef1badbeef", "0100", "0304deadbeef")
1172                                 ).unwrap()[..]) {
1173                 } else { panic!(); }
1174         }
1175
1176         #[test]
1177         fn tlv_req_type_missing_or_extra() {
1178                 // It's also bad if they included even fields we don't understand
1179                 if let Err(DecodeError::UnknownRequiredFeature) = tlv_reader(&<Vec<u8>>::from_hex(
1180                                 concat!("0100", "0208deadbeef1badbeef", "0304deadbeef", "0600")
1181                                 ).unwrap()[..]) {
1182                 } else { panic!(); }
1183                 // ... or if they're missing fields we need
1184                 if let Err(DecodeError::InvalidValue) = tlv_reader(&<Vec<u8>>::from_hex(
1185                                 concat!("0100", "0208deadbeef1badbeef")
1186                                 ).unwrap()[..]) {
1187                 } else { panic!(); }
1188                 // ... even if that field is even
1189                 if let Err(DecodeError::InvalidValue) = tlv_reader(&<Vec<u8>>::from_hex(
1190                                 concat!("0304deadbeef", "0500")
1191                                 ).unwrap()[..]) {
1192                 } else { panic!(); }
1193         }
1194
1195         #[test]
1196         fn tlv_simple_good_cases() {
1197                 assert_eq!(tlv_reader(&<Vec<u8>>::from_hex(
1198                                 concat!("0208deadbeef1badbeef", "03041bad1dea")
1199                                 ).unwrap()[..]).unwrap(),
1200                         (0xdeadbeef1badbeef, 0x1bad1dea, None));
1201                 assert_eq!(tlv_reader(&<Vec<u8>>::from_hex(
1202                                 concat!("0208deadbeef1badbeef", "03041bad1dea", "040401020304")
1203                                 ).unwrap()[..]).unwrap(),
1204                         (0xdeadbeef1badbeef, 0x1bad1dea, Some(0x01020304)));
1205         }
1206
1207         #[derive(Debug, PartialEq)]
1208         struct TestUpgradable {
1209                 a: u32,
1210                 b: u32,
1211                 c: Option<u32>,
1212         }
1213
1214         fn upgradable_tlv_reader(s: &[u8]) -> Result<Option<TestUpgradable>, DecodeError> {
1215                 let mut s = Cursor::new(s);
1216                 let mut a = 0;
1217                 let mut b = 0;
1218                 let mut c: Option<u32> = None;
1219                 decode_tlv_stream!(&mut s, {(2, a, upgradable_required), (3, b, upgradable_required), (4, c, upgradable_option)});
1220                 Ok(Some(TestUpgradable { a, b, c, }))
1221         }
1222
1223         #[test]
1224         fn upgradable_tlv_simple_good_cases() {
1225                 assert_eq!(upgradable_tlv_reader(&<Vec<u8>>::from_hex(
1226                         concat!("0204deadbeef", "03041bad1dea", "0404deadbeef")
1227                 ).unwrap()[..]).unwrap(),
1228                 Some(TestUpgradable { a: 0xdeadbeef, b: 0x1bad1dea, c: Some(0xdeadbeef) }));
1229
1230                 assert_eq!(upgradable_tlv_reader(&<Vec<u8>>::from_hex(
1231                         concat!("0204deadbeef", "03041bad1dea")
1232                 ).unwrap()[..]).unwrap(),
1233                 Some(TestUpgradable { a: 0xdeadbeef, b: 0x1bad1dea, c: None}));
1234         }
1235
1236         #[test]
1237         fn missing_required_upgradable() {
1238                 if let Err(DecodeError::InvalidValue) = upgradable_tlv_reader(&<Vec<u8>>::from_hex(
1239                         concat!("0100", "0204deadbeef")
1240                         ).unwrap()[..]) {
1241                 } else { panic!(); }
1242                 if let Err(DecodeError::InvalidValue) = upgradable_tlv_reader(&<Vec<u8>>::from_hex(
1243                         concat!("0100", "03041bad1dea")
1244                 ).unwrap()[..]) {
1245                 } else { panic!(); }
1246         }
1247
1248         // BOLT TLV test cases
1249         fn tlv_reader_n1(s: &[u8]) -> Result<(Option<HighZeroBytesDroppedBigSize<u64>>, Option<u64>, Option<(PublicKey, u64, u64)>, Option<u16>), DecodeError> {
1250                 let mut s = Cursor::new(s);
1251                 let mut tlv1: Option<HighZeroBytesDroppedBigSize<u64>> = None;
1252                 let mut tlv2: Option<u64> = None;
1253                 let mut tlv3: Option<(PublicKey, u64, u64)> = None;
1254                 let mut tlv4: Option<u16> = None;
1255                 decode_tlv_stream!(&mut s, {(1, tlv1, option), (2, tlv2, option), (3, tlv3, option), (254, tlv4, option)});
1256                 Ok((tlv1, tlv2, tlv3, tlv4))
1257         }
1258
1259         #[test]
1260         fn bolt_tlv_bogus_stream() {
1261                 macro_rules! do_test {
1262                         ($stream: expr, $reason: ident) => {
1263                                 if let Err(DecodeError::$reason) = tlv_reader_n1(&<Vec<u8>>::from_hex($stream).unwrap()[..]) {
1264                                 } else { panic!(); }
1265                         }
1266                 }
1267
1268                 // TLVs from the BOLT test cases which should not decode as either n1 or n2
1269                 do_test!(concat!("fd01"), ShortRead);
1270                 do_test!(concat!("fd0001", "00"), InvalidValue);
1271                 do_test!(concat!("fd0101"), ShortRead);
1272                 do_test!(concat!("0f", "fd"), ShortRead);
1273                 do_test!(concat!("0f", "fd26"), ShortRead);
1274                 do_test!(concat!("0f", "fd2602"), ShortRead);
1275                 do_test!(concat!("0f", "fd0001", "00"), InvalidValue);
1276                 do_test!(concat!("0f", "fd0201", "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), ShortRead);
1277
1278                 do_test!(concat!("12", "00"), UnknownRequiredFeature);
1279                 do_test!(concat!("fd0102", "00"), UnknownRequiredFeature);
1280                 do_test!(concat!("fe01000002", "00"), UnknownRequiredFeature);
1281                 do_test!(concat!("ff0100000000000002", "00"), UnknownRequiredFeature);
1282         }
1283
1284         #[test]
1285         fn bolt_tlv_bogus_n1_stream() {
1286                 macro_rules! do_test {
1287                         ($stream: expr, $reason: ident) => {
1288                                 if let Err(DecodeError::$reason) = tlv_reader_n1(&<Vec<u8>>::from_hex($stream).unwrap()[..]) {
1289                                 } else { panic!(); }
1290                         }
1291                 }
1292
1293                 // TLVs from the BOLT test cases which should not decode as n1
1294                 do_test!(concat!("01", "09", "ffffffffffffffffff"), InvalidValue);
1295                 do_test!(concat!("01", "01", "00"), InvalidValue);
1296                 do_test!(concat!("01", "02", "0001"), InvalidValue);
1297                 do_test!(concat!("01", "03", "000100"), InvalidValue);
1298                 do_test!(concat!("01", "04", "00010000"), InvalidValue);
1299                 do_test!(concat!("01", "05", "0001000000"), InvalidValue);
1300                 do_test!(concat!("01", "06", "000100000000"), InvalidValue);
1301                 do_test!(concat!("01", "07", "00010000000000"), InvalidValue);
1302                 do_test!(concat!("01", "08", "0001000000000000"), InvalidValue);
1303                 do_test!(concat!("02", "07", "01010101010101"), ShortRead);
1304                 do_test!(concat!("02", "09", "010101010101010101"), InvalidValue);
1305                 do_test!(concat!("03", "21", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb"), ShortRead);
1306                 do_test!(concat!("03", "29", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb0000000000000001"), ShortRead);
1307                 do_test!(concat!("03", "30", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb000000000000000100000000000001"), ShortRead);
1308                 do_test!(concat!("03", "31", "043da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb00000000000000010000000000000002"), InvalidValue);
1309                 do_test!(concat!("03", "32", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb0000000000000001000000000000000001"), InvalidValue);
1310                 do_test!(concat!("fd00fe", "00"), ShortRead);
1311                 do_test!(concat!("fd00fe", "01", "01"), ShortRead);
1312                 do_test!(concat!("fd00fe", "03", "010101"), InvalidValue);
1313                 do_test!(concat!("00", "00"), UnknownRequiredFeature);
1314
1315                 do_test!(concat!("02", "08", "0000000000000226", "01", "01", "2a"), InvalidValue);
1316                 do_test!(concat!("02", "08", "0000000000000231", "02", "08", "0000000000000451"), InvalidValue);
1317                 do_test!(concat!("1f", "00", "0f", "01", "2a"), InvalidValue);
1318                 do_test!(concat!("1f", "00", "1f", "01", "2a"), InvalidValue);
1319
1320                 // The last BOLT test modified to not require creating a new decoder for one trivial test.
1321                 do_test!(concat!("ffffffffffffffffff", "00", "01", "00"), InvalidValue);
1322         }
1323
1324         #[test]
1325         fn bolt_tlv_valid_n1_stream() {
1326                 macro_rules! do_test {
1327                         ($stream: expr, $tlv1: expr, $tlv2: expr, $tlv3: expr, $tlv4: expr) => {
1328                                 if let Ok((tlv1, tlv2, tlv3, tlv4)) = tlv_reader_n1(&<Vec<u8>>::from_hex($stream).unwrap()[..]) {
1329                                         assert_eq!(tlv1.map(|v| v.0), $tlv1);
1330                                         assert_eq!(tlv2, $tlv2);
1331                                         assert_eq!(tlv3, $tlv3);
1332                                         assert_eq!(tlv4, $tlv4);
1333                                 } else { panic!(); }
1334                         }
1335                 }
1336
1337                 do_test!(concat!(""), None, None, None, None);
1338                 do_test!(concat!("21", "00"), None, None, None, None);
1339                 do_test!(concat!("fd0201", "00"), None, None, None, None);
1340                 do_test!(concat!("fd00fd", "00"), None, None, None, None);
1341                 do_test!(concat!("fd00ff", "00"), None, None, None, None);
1342                 do_test!(concat!("fe02000001", "00"), None, None, None, None);
1343                 do_test!(concat!("ff0200000000000001", "00"), None, None, None, None);
1344
1345                 do_test!(concat!("01", "00"), Some(0), None, None, None);
1346                 do_test!(concat!("01", "01", "01"), Some(1), None, None, None);
1347                 do_test!(concat!("01", "02", "0100"), Some(256), None, None, None);
1348                 do_test!(concat!("01", "03", "010000"), Some(65536), None, None, None);
1349                 do_test!(concat!("01", "04", "01000000"), Some(16777216), None, None, None);
1350                 do_test!(concat!("01", "05", "0100000000"), Some(4294967296), None, None, None);
1351                 do_test!(concat!("01", "06", "010000000000"), Some(1099511627776), None, None, None);
1352                 do_test!(concat!("01", "07", "01000000000000"), Some(281474976710656), None, None, None);
1353                 do_test!(concat!("01", "08", "0100000000000000"), Some(72057594037927936), None, None, None);
1354                 do_test!(concat!("02", "08", "0000000000000226"), None, Some((0 << 30) | (0 << 5) | (550 << 0)), None, None);
1355                 do_test!(concat!("03", "31", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb00000000000000010000000000000002"),
1356                         None, None, Some((
1357                                 PublicKey::from_slice(&<Vec<u8>>::from_hex("023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb").unwrap()[..]).unwrap(), 1, 2)),
1358                         None);
1359                 do_test!(concat!("fd00fe", "02", "0226"), None, None, None, Some(550));
1360         }
1361
1362         fn do_simple_test_tlv_write() -> Result<(), io::Error> {
1363                 let mut stream = VecWriter(Vec::new());
1364
1365                 stream.0.clear();
1366                 _encode_varint_length_prefixed_tlv!(&mut stream, {(1, 1u8, required), (42, None::<u64>, option)});
1367                 assert_eq!(stream.0, <Vec<u8>>::from_hex("03010101").unwrap());
1368
1369                 stream.0.clear();
1370                 _encode_varint_length_prefixed_tlv!(&mut stream, {(1, Some(1u8), option)});
1371                 assert_eq!(stream.0, <Vec<u8>>::from_hex("03010101").unwrap());
1372
1373                 stream.0.clear();
1374                 _encode_varint_length_prefixed_tlv!(&mut stream, {(4, 0xabcdu16, required), (42, None::<u64>, option)});
1375                 assert_eq!(stream.0, <Vec<u8>>::from_hex("040402abcd").unwrap());
1376
1377                 stream.0.clear();
1378                 _encode_varint_length_prefixed_tlv!(&mut stream, {(42, None::<u64>, option), (0xff, 0xabcdu16, required)});
1379                 assert_eq!(stream.0, <Vec<u8>>::from_hex("06fd00ff02abcd").unwrap());
1380
1381                 stream.0.clear();
1382                 _encode_varint_length_prefixed_tlv!(&mut stream, {(0, 1u64, required), (42, None::<u64>, option), (0xff, HighZeroBytesDroppedBigSize(0u64), required)});
1383                 assert_eq!(stream.0, <Vec<u8>>::from_hex("0e00080000000000000001fd00ff00").unwrap());
1384
1385                 stream.0.clear();
1386                 _encode_varint_length_prefixed_tlv!(&mut stream, {(0, Some(1u64), option), (0xff, HighZeroBytesDroppedBigSize(0u64), required)});
1387                 assert_eq!(stream.0, <Vec<u8>>::from_hex("0e00080000000000000001fd00ff00").unwrap());
1388
1389                 Ok(())
1390         }
1391
1392         #[test]
1393         fn simple_test_tlv_write() {
1394                 do_simple_test_tlv_write().unwrap();
1395         }
1396 }