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