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