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