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