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