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