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