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