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