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