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