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