Introduce `init_and_read_tlv_fields` macro
[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 macro_rules! encode_tlv {
11         ($stream: expr, $type: expr, $field: expr, (default_value, $default: expr)) => {
12                 encode_tlv!($stream, $type, $field, required)
13         };
14         ($stream: expr, $type: expr, $field: expr, required) => {
15                 BigSize($type).write($stream)?;
16                 BigSize($field.serialized_length() as u64).write($stream)?;
17                 $field.write($stream)?;
18         };
19         ($stream: expr, $type: expr, $field: expr, vec_type) => {
20                 encode_tlv!($stream, $type, $crate::util::ser::VecWriteWrapper(&$field), required);
21         };
22         ($stream: expr, $optional_type: expr, $optional_field: expr, option) => {
23                 if let Some(ref field) = $optional_field {
24                         BigSize($optional_type).write($stream)?;
25                         BigSize(field.serialized_length() as u64).write($stream)?;
26                         field.write($stream)?;
27                 }
28         };
29 }
30
31 macro_rules! encode_tlv_stream {
32         ($stream: expr, {$(($type: expr, $field: expr, $fieldty: tt)),* $(,)*}) => { {
33                 #[allow(unused_imports)]
34                 use $crate::{
35                         ln::msgs::DecodeError,
36                         util::ser,
37                         util::ser::BigSize,
38                 };
39
40                 $(
41                         encode_tlv!($stream, $type, $field, $fieldty);
42                 )*
43
44                 #[allow(unused_mut, unused_variables, unused_assignments)]
45                 #[cfg(debug_assertions)]
46                 {
47                         let mut last_seen: Option<u64> = None;
48                         $(
49                                 if let Some(t) = last_seen {
50                                         debug_assert!(t <= $type);
51                                 }
52                                 last_seen = Some($type);
53                         )*
54                 }
55         } }
56 }
57
58 macro_rules! get_varint_length_prefixed_tlv_length {
59         ($len: expr, $type: expr, $field: expr, (default_value, $default: expr)) => {
60                 get_varint_length_prefixed_tlv_length!($len, $type, $field, required)
61         };
62         ($len: expr, $type: expr, $field: expr, required) => {
63                 BigSize($type).write(&mut $len).expect("No in-memory data may fail to serialize");
64                 let field_len = $field.serialized_length();
65                 BigSize(field_len as u64).write(&mut $len).expect("No in-memory data may fail to serialize");
66                 $len.0 += field_len;
67         };
68         ($len: expr, $type: expr, $field: expr, vec_type) => {
69                 get_varint_length_prefixed_tlv_length!($len, $type, $crate::util::ser::VecWriteWrapper(&$field), required);
70         };
71         ($len: expr, $optional_type: expr, $optional_field: expr, option) => {
72                 if let Some(ref field) = $optional_field {
73                         BigSize($optional_type).write(&mut $len).expect("No in-memory data may fail to serialize");
74                         let field_len = field.serialized_length();
75                         BigSize(field_len as u64).write(&mut $len).expect("No in-memory data may fail to serialize");
76                         $len.0 += field_len;
77                 }
78         };
79 }
80
81 macro_rules! encode_varint_length_prefixed_tlv {
82         ($stream: expr, {$(($type: expr, $field: expr, $fieldty: tt)),*}) => { {
83                 use $crate::util::ser::BigSize;
84                 let len = {
85                         #[allow(unused_mut)]
86                         let mut len = $crate::util::ser::LengthCalculatingWriter(0);
87                         $(
88                                 get_varint_length_prefixed_tlv_length!(len, $type, $field, $fieldty);
89                         )*
90                         len.0
91                 };
92                 BigSize(len as u64).write($stream)?;
93                 encode_tlv_stream!($stream, { $(($type, $field, $fieldty)),* });
94         } }
95 }
96
97 macro_rules! check_tlv_order {
98         ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, (default_value, $default: expr)) => {{
99                 #[allow(unused_comparisons)] // Note that $type may be 0 making the second comparison always true
100                 let invalid_order = ($last_seen_type.is_none() || $last_seen_type.unwrap() < $type) && $typ.0 > $type;
101                 if invalid_order {
102                         $field = $default.into();
103                 }
104         }};
105         ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, required) => {{
106                 #[allow(unused_comparisons)] // Note that $type may be 0 making the second comparison always true
107                 let invalid_order = ($last_seen_type.is_none() || $last_seen_type.unwrap() < $type) && $typ.0 > $type;
108                 if invalid_order {
109                         return Err(DecodeError::InvalidValue);
110                 }
111         }};
112         ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, option) => {{
113                 // no-op
114         }};
115         ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, vec_type) => {{
116                 // no-op
117         }};
118         ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, ignorable) => {{
119                 // no-op
120         }};
121         ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, (option: $trait: ident $(, $read_arg: expr)?)) => {{
122                 // no-op
123         }};
124 }
125
126 macro_rules! check_missing_tlv {
127         ($last_seen_type: expr, $type: expr, $field: ident, (default_value, $default: expr)) => {{
128                 #[allow(unused_comparisons)] // Note that $type may be 0 making the second comparison always true
129                 let missing_req_type = $last_seen_type.is_none() || $last_seen_type.unwrap() < $type;
130                 if missing_req_type {
131                         $field = $default.into();
132                 }
133         }};
134         ($last_seen_type: expr, $type: expr, $field: ident, required) => {{
135                 #[allow(unused_comparisons)] // Note that $type may be 0 making the second comparison always true
136                 let missing_req_type = $last_seen_type.is_none() || $last_seen_type.unwrap() < $type;
137                 if missing_req_type {
138                         return Err(DecodeError::InvalidValue);
139                 }
140         }};
141         ($last_seen_type: expr, $type: expr, $field: ident, vec_type) => {{
142                 // no-op
143         }};
144         ($last_seen_type: expr, $type: expr, $field: ident, option) => {{
145                 // no-op
146         }};
147         ($last_seen_type: expr, $type: expr, $field: ident, ignorable) => {{
148                 // no-op
149         }};
150         ($last_seen_type: expr, $type: expr, $field: ident, (option: $trait: ident $(, $read_arg: expr)?)) => {{
151                 // no-op
152         }};
153 }
154
155 macro_rules! decode_tlv {
156         ($reader: expr, $field: ident, (default_value, $default: expr)) => {{
157                 decode_tlv!($reader, $field, required)
158         }};
159         ($reader: expr, $field: ident, required) => {{
160                 $field = $crate::util::ser::Readable::read(&mut $reader)?;
161         }};
162         ($reader: expr, $field: ident, vec_type) => {{
163                 let f: $crate::util::ser::VecReadWrapper<_> = $crate::util::ser::Readable::read(&mut $reader)?;
164                 $field = Some(f.0);
165         }};
166         ($reader: expr, $field: ident, option) => {{
167                 $field = Some($crate::util::ser::Readable::read(&mut $reader)?);
168         }};
169         ($reader: expr, $field: ident, ignorable) => {{
170                 $field = $crate::util::ser::MaybeReadable::read(&mut $reader)?;
171         }};
172         ($reader: expr, $field: ident, (option: $trait: ident $(, $read_arg: expr)?)) => {{
173                 $field = Some($trait::read(&mut $reader $(, $read_arg)*)?);
174         }};
175 }
176
177 // `$decode_custom_tlv` is a closure that may be optionally provided to handle custom message types.
178 // If it is provided, it will be called with the custom type and the `FixedLengthReader` containing
179 // the message contents. It should return `Ok(true)` if the custom message is successfully parsed,
180 // `Ok(false)` if the message type is unknown, and `Err(DecodeError)` if parsing fails.
181 macro_rules! decode_tlv_stream {
182         ($stream: expr, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}
183          $(, $decode_custom_tlv: expr)?) => { {
184                 use $crate::ln::msgs::DecodeError;
185                 let mut last_seen_type: Option<u64> = None;
186                 let mut stream_ref = $stream;
187                 'tlv_read: loop {
188                         use $crate::util::ser;
189
190                         // First decode the type of this TLV:
191                         let typ: ser::BigSize = {
192                                 // We track whether any bytes were read during the consensus_decode call to
193                                 // determine whether we should break or return ShortRead if we get an
194                                 // UnexpectedEof. This should in every case be largely cosmetic, but its nice to
195                                 // pass the TLV test vectors exactly, which requre this distinction.
196                                 let mut tracking_reader = ser::ReadTrackingReader::new(&mut stream_ref);
197                                 match $crate::util::ser::Readable::read(&mut tracking_reader) {
198                                         Err(DecodeError::ShortRead) => {
199                                                 if !tracking_reader.have_read {
200                                                         break 'tlv_read;
201                                                 } else {
202                                                         return Err(DecodeError::ShortRead);
203                                                 }
204                                         },
205                                         Err(e) => return Err(e),
206                                         Ok(t) => t,
207                                 }
208                         };
209
210                         // Types must be unique and monotonically increasing:
211                         match last_seen_type {
212                                 Some(t) if typ.0 <= t => {
213                                         return Err(DecodeError::InvalidValue);
214                                 },
215                                 _ => {},
216                         }
217                         // As we read types, make sure we hit every required type:
218                         $({
219                                 check_tlv_order!(last_seen_type, typ, $type, $field, $fieldty);
220                         })*
221                         last_seen_type = Some(typ.0);
222
223                         // Finally, read the length and value itself:
224                         let length: ser::BigSize = $crate::util::ser::Readable::read(&mut stream_ref)?;
225                         let mut s = ser::FixedLengthReader::new(&mut stream_ref, length.0);
226                         match typ.0 {
227                                 $($type => {
228                                         decode_tlv!(s, $field, $fieldty);
229                                         if s.bytes_remain() {
230                                                 s.eat_remaining()?; // Return ShortRead if there's actually not enough bytes
231                                                 return Err(DecodeError::InvalidValue);
232                                         }
233                                 },)*
234                                 t => {
235                                         $(
236                                                 if $decode_custom_tlv(t, &mut s)? {
237                                                         // If a custom TLV was successfully read (i.e. decode_custom_tlv returns true),
238                                                         // continue to the next TLV read.
239                                                         s.eat_remaining()?;
240                                                         continue 'tlv_read;
241                                                 }
242                                         )?
243                                         if t % 2 == 0 {
244                                                 return Err(DecodeError::UnknownRequiredFeature);
245                                         }
246                                 }
247                         }
248                         s.eat_remaining()?;
249                 }
250                 // Make sure we got to each required type after we've read every TLV:
251                 $({
252                         check_missing_tlv!(last_seen_type, $type, $field, $fieldty);
253                 })*
254         } }
255 }
256
257 macro_rules! impl_writeable_msg {
258         ($st:ident, {$($field:ident),* $(,)*}, {$(($type: expr, $tlvfield: ident, $fieldty: tt)),* $(,)*}) => {
259                 impl $crate::util::ser::Writeable for $st {
260                         fn write<W: $crate::util::ser::Writer>(&self, w: &mut W) -> Result<(), $crate::io::Error> {
261                                 $( self.$field.write(w)?; )*
262                                 encode_tlv_stream!(w, {$(($type, self.$tlvfield, $fieldty)),*});
263                                 Ok(())
264                         }
265                 }
266                 impl $crate::util::ser::Readable for $st {
267                         fn read<R: $crate::io::Read>(r: &mut R) -> Result<Self, $crate::ln::msgs::DecodeError> {
268                                 $(let $field = $crate::util::ser::Readable::read(r)?;)*
269                                 $(init_tlv_field_var!($tlvfield, $fieldty);)*
270                                 decode_tlv_stream!(r, {$(($type, $tlvfield, $fieldty)),*});
271                                 Ok(Self {
272                                         $($field),*,
273                                         $($tlvfield),*
274                                 })
275                         }
276                 }
277         }
278 }
279
280 macro_rules! impl_writeable {
281         ($st:ident, {$($field:ident),*}) => {
282                 impl $crate::util::ser::Writeable for $st {
283                         fn write<W: $crate::util::ser::Writer>(&self, w: &mut W) -> Result<(), $crate::io::Error> {
284                                 $( self.$field.write(w)?; )*
285                                 Ok(())
286                         }
287
288                         #[inline]
289                         fn serialized_length(&self) -> usize {
290                                 let mut len_calc = 0;
291                                 $( len_calc += self.$field.serialized_length(); )*
292                                 return len_calc;
293                         }
294                 }
295
296                 impl $crate::util::ser::Readable for $st {
297                         fn read<R: $crate::io::Read>(r: &mut R) -> Result<Self, $crate::ln::msgs::DecodeError> {
298                                 Ok(Self {
299                                         $($field: $crate::util::ser::Readable::read(r)?),*
300                                 })
301                         }
302                 }
303         }
304 }
305
306 /// Write out two bytes to indicate the version of an object.
307 /// $this_version represents a unique version of a type. Incremented whenever the type's
308 ///               serialization format has changed or has a new interpretation. Used by a type's
309 ///               reader to determine how to interpret fields or if it can understand a serialized
310 ///               object.
311 /// $min_version_that_can_read_this is the minimum reader version which can understand this
312 ///                                 serialized object. Previous versions will simply err with a
313 ///                                 DecodeError::UnknownVersion.
314 ///
315 /// Updates to either $this_version or $min_version_that_can_read_this should be included in
316 /// release notes.
317 ///
318 /// Both version fields can be specific to this type of object.
319 macro_rules! write_ver_prefix {
320         ($stream: expr, $this_version: expr, $min_version_that_can_read_this: expr) => {
321                 $stream.write_all(&[$this_version; 1])?;
322                 $stream.write_all(&[$min_version_that_can_read_this; 1])?;
323         }
324 }
325
326 /// Writes out a suffix to an object which contains potentially backwards-compatible, optional
327 /// fields which old nodes can happily ignore.
328 ///
329 /// It is written out in TLV format and, as with all TLV fields, unknown even fields cause a
330 /// DecodeError::UnknownRequiredFeature error, with unknown odd fields ignored.
331 ///
332 /// This is the preferred method of adding new fields that old nodes can ignore and still function
333 /// correctly.
334 macro_rules! write_tlv_fields {
335         ($stream: expr, {$(($type: expr, $field: expr, $fieldty: tt)),* $(,)*}) => {
336                 encode_varint_length_prefixed_tlv!($stream, {$(($type, $field, $fieldty)),*})
337         }
338 }
339
340 /// Reads a prefix added by write_ver_prefix!(), above. Takes the current version of the
341 /// serialization logic for this object. This is compared against the
342 /// $min_version_that_can_read_this added by write_ver_prefix!().
343 macro_rules! read_ver_prefix {
344         ($stream: expr, $this_version: expr) => { {
345                 let ver: u8 = Readable::read($stream)?;
346                 let min_ver: u8 = Readable::read($stream)?;
347                 if min_ver > $this_version {
348                         return Err(DecodeError::UnknownVersion);
349                 }
350                 ver
351         } }
352 }
353
354 /// Reads a suffix added by write_tlv_fields.
355 macro_rules! read_tlv_fields {
356         ($stream: expr, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}) => { {
357                 let tlv_len: $crate::util::ser::BigSize = $crate::util::ser::Readable::read($stream)?;
358                 let mut rd = $crate::util::ser::FixedLengthReader::new($stream, tlv_len.0);
359                 decode_tlv_stream!(&mut rd, {$(($type, $field, $fieldty)),*});
360                 rd.eat_remaining().map_err(|_| $crate::ln::msgs::DecodeError::ShortRead)?;
361         } }
362 }
363
364 macro_rules! init_tlv_based_struct_field {
365         ($field: ident, (default_value, $default: expr)) => {
366                 $field.0.unwrap()
367         };
368         ($field: ident, option) => {
369                 $field
370         };
371         ($field: ident, required) => {
372                 $field.0.unwrap()
373         };
374         ($field: ident, vec_type) => {
375                 $field.unwrap()
376         };
377 }
378
379 macro_rules! init_tlv_field_var {
380         ($field: ident, (default_value, $default: expr)) => {
381                 let mut $field = $crate::util::ser::OptionDeserWrapper(None);
382         };
383         ($field: ident, required) => {
384                 let mut $field = $crate::util::ser::OptionDeserWrapper(None);
385         };
386         ($field: ident, vec_type) => {
387                 let mut $field = Some(Vec::new());
388         };
389         ($field: ident, option) => {
390                 let mut $field = None;
391         };
392 }
393
394 macro_rules! init_and_read_tlv_fields {
395         ($reader: ident, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}) => {
396                 $(
397                         init_tlv_field_var!($field, $fieldty);
398                 )*
399
400                 read_tlv_fields!($reader, {
401                         $(($type, $field, $fieldty)),*
402                 });
403         }
404 }
405
406 /// Implements Readable/Writeable for a struct storing it as a set of TLVs
407 /// If $fieldty is `required`, then $field is a required field that is not an Option nor a Vec.
408 /// If $fieldty is `option`, then $field is optional field.
409 /// if $fieldty is `vec_type`, then $field is a Vec, which needs to have its individual elements
410 /// serialized.
411 macro_rules! impl_writeable_tlv_based {
412         ($st: ident, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}) => {
413                 impl $crate::util::ser::Writeable for $st {
414                         fn write<W: $crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), $crate::io::Error> {
415                                 write_tlv_fields!(writer, {
416                                         $(($type, self.$field, $fieldty)),*
417                                 });
418                                 Ok(())
419                         }
420
421                         #[inline]
422                         fn serialized_length(&self) -> usize {
423                                 use $crate::util::ser::BigSize;
424                                 let len = {
425                                         #[allow(unused_mut)]
426                                         let mut len = $crate::util::ser::LengthCalculatingWriter(0);
427                                         $(
428                                                 get_varint_length_prefixed_tlv_length!(len, $type, self.$field, $fieldty);
429                                         )*
430                                         len.0
431                                 };
432                                 let mut len_calc = $crate::util::ser::LengthCalculatingWriter(0);
433                                 BigSize(len as u64).write(&mut len_calc).expect("No in-memory data may fail to serialize");
434                                 len + len_calc.0
435                         }
436                 }
437
438                 impl $crate::util::ser::Readable for $st {
439                         fn read<R: $crate::io::Read>(reader: &mut R) -> Result<Self, $crate::ln::msgs::DecodeError> {
440                                 init_and_read_tlv_fields!(reader, {
441                                         $(($type, $field, $fieldty)),*
442                                 });
443                                 Ok(Self {
444                                         $(
445                                                 $field: init_tlv_based_struct_field!($field, $fieldty)
446                                         ),*
447                                 })
448                         }
449                 }
450         }
451 }
452
453 macro_rules! _impl_writeable_tlv_based_enum_common {
454         ($st: ident, $(($variant_id: expr, $variant_name: ident) =>
455                 {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}
456         ),* $(,)*;
457         $(($tuple_variant_id: expr, $tuple_variant_name: ident)),*  $(,)*) => {
458                 impl $crate::util::ser::Writeable for $st {
459                         fn write<W: $crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), $crate::io::Error> {
460                                 match self {
461                                         $($st::$variant_name { $(ref $field),* } => {
462                                                 let id: u8 = $variant_id;
463                                                 id.write(writer)?;
464                                                 write_tlv_fields!(writer, {
465                                                         $(($type, $field, $fieldty)),*
466                                                 });
467                                         }),*
468                                         $($st::$tuple_variant_name (ref field) => {
469                                                 let id: u8 = $tuple_variant_id;
470                                                 id.write(writer)?;
471                                                 field.write(writer)?;
472                                         }),*
473                                 }
474                                 Ok(())
475                         }
476                 }
477         }
478 }
479
480 /// Implement MaybeReadable and Writeable for an enum, with struct variants stored as TLVs and
481 /// tuple variants stored directly.
482 ///
483 /// This is largely identical to `impl_writeable_tlv_based_enum`, except that odd variants will
484 /// return `Ok(None)` instead of `Err(UnknownRequiredFeature)`. It should generally be preferred
485 /// when `MaybeReadable` is practical instead of just `Readable` as it provides an upgrade path for
486 /// new variants to be added which are simply ignored by existing clients.
487 macro_rules! impl_writeable_tlv_based_enum_upgradable {
488         ($st: ident, $(($variant_id: expr, $variant_name: ident) =>
489                 {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}
490         ),* $(,)*
491         $(;
492         $(($tuple_variant_id: expr, $tuple_variant_name: ident)),*  $(,)*)*) => {
493                 _impl_writeable_tlv_based_enum_common!($st,
494                         $(($variant_id, $variant_name) => {$(($type, $field, $fieldty)),*}),*;
495                         $($(($tuple_variant_id, $tuple_variant_name)),*)*);
496
497                 impl $crate::util::ser::MaybeReadable for $st {
498                         fn read<R: $crate::io::Read>(reader: &mut R) -> Result<Option<Self>, $crate::ln::msgs::DecodeError> {
499                                 let id: u8 = $crate::util::ser::Readable::read(reader)?;
500                                 match id {
501                                         $($variant_id => {
502                                                 // Because read_tlv_fields creates a labeled loop, we cannot call it twice
503                                                 // in the same function body. Instead, we define a closure and call it.
504                                                 let f = || {
505                                                         init_and_read_tlv_fields!(reader, {
506                                                                 $(($type, $field, $fieldty)),*
507                                                         });
508                                                         Ok(Some($st::$variant_name {
509                                                                 $(
510                                                                         $field: init_tlv_based_struct_field!($field, $fieldty)
511                                                                 ),*
512                                                         }))
513                                                 };
514                                                 f()
515                                         }),*
516                                         $($($tuple_variant_id => {
517                                                 Ok(Some($st::$tuple_variant_name(Readable::read(reader)?)))
518                                         }),*)*
519                                         _ if id % 2 == 1 => Ok(None),
520                                         _ => Err(DecodeError::UnknownRequiredFeature),
521                                 }
522                         }
523                 }
524
525         }
526 }
527
528 /// Implement Readable and Writeable for an enum, with struct variants stored as TLVs and tuple
529 /// variants stored directly.
530 /// The format is, for example
531 /// impl_writeable_tlv_based_enum!(EnumName,
532 ///   (0, StructVariantA) => {(0, required_variant_field, required), (1, optional_variant_field, option)},
533 ///   (1, StructVariantB) => {(0, variant_field_a, required), (1, variant_field_b, required), (2, variant_vec_field, vec_type)};
534 ///   (2, TupleVariantA), (3, TupleVariantB),
535 /// );
536 /// The type is written as a single byte, followed by any variant data.
537 /// Attempts to read an unknown type byte result in DecodeError::UnknownRequiredFeature.
538 macro_rules! impl_writeable_tlv_based_enum {
539         ($st: ident, $(($variant_id: expr, $variant_name: ident) =>
540                 {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}
541         ),* $(,)*;
542         $(($tuple_variant_id: expr, $tuple_variant_name: ident)),*  $(,)*) => {
543                 _impl_writeable_tlv_based_enum_common!($st,
544                         $(($variant_id, $variant_name) => {$(($type, $field, $fieldty)),*}),*;
545                         $(($tuple_variant_id, $tuple_variant_name)),*);
546
547                 impl $crate::util::ser::Readable for $st {
548                         fn read<R: $crate::io::Read>(reader: &mut R) -> Result<Self, $crate::ln::msgs::DecodeError> {
549                                 let id: u8 = $crate::util::ser::Readable::read(reader)?;
550                                 match id {
551                                         $($variant_id => {
552                                                 // Because read_tlv_fields creates a labeled loop, we cannot call it twice
553                                                 // in the same function body. Instead, we define a closure and call it.
554                                                 let f = || {
555                                                         init_and_read_tlv_fields!(reader, {
556                                                                 $(($type, $field, $fieldty)),*
557                                                         });
558                                                         Ok($st::$variant_name {
559                                                                 $(
560                                                                         $field: init_tlv_based_struct_field!($field, $fieldty)
561                                                                 ),*
562                                                         })
563                                                 };
564                                                 f()
565                                         }),*
566                                         $($tuple_variant_id => {
567                                                 Ok($st::$tuple_variant_name(Readable::read(reader)?))
568                                         }),*
569                                         _ => {
570                                                 Err(DecodeError::UnknownRequiredFeature)
571                                         },
572                                 }
573                         }
574                 }
575         }
576 }
577
578 #[cfg(test)]
579 mod tests {
580         use crate::io::{self, Cursor};
581         use crate::prelude::*;
582         use crate::ln::msgs::DecodeError;
583         use crate::util::ser::{Writeable, HighZeroBytesDroppedBigSize, VecWriter};
584         use bitcoin::secp256k1::PublicKey;
585
586         // The BOLT TLV test cases don't include any tests which use our "required-value" logic since
587         // the encoding layer in the BOLTs has no such concept, though it makes our macros easier to
588         // work with so they're baked into the decoder. Thus, we have a few additional tests below
589         fn tlv_reader(s: &[u8]) -> Result<(u64, u32, Option<u32>), DecodeError> {
590                 let mut s = Cursor::new(s);
591                 let mut a: u64 = 0;
592                 let mut b: u32 = 0;
593                 let mut c: Option<u32> = None;
594                 decode_tlv_stream!(&mut s, {(2, a, required), (3, b, required), (4, c, option)});
595                 Ok((a, b, c))
596         }
597
598         #[test]
599         fn tlv_v_short_read() {
600                 // We only expect a u32 for type 3 (which we are given), but the L says its 8 bytes.
601                 if let Err(DecodeError::ShortRead) = tlv_reader(&::hex::decode(
602                                 concat!("0100", "0208deadbeef1badbeef", "0308deadbeef")
603                                 ).unwrap()[..]) {
604                 } else { panic!(); }
605         }
606
607         #[test]
608         fn tlv_types_out_of_order() {
609                 if let Err(DecodeError::InvalidValue) = tlv_reader(&::hex::decode(
610                                 concat!("0100", "0304deadbeef", "0208deadbeef1badbeef")
611                                 ).unwrap()[..]) {
612                 } else { panic!(); }
613                 // ...even if its some field we don't understand
614                 if let Err(DecodeError::InvalidValue) = tlv_reader(&::hex::decode(
615                                 concat!("0208deadbeef1badbeef", "0100", "0304deadbeef")
616                                 ).unwrap()[..]) {
617                 } else { panic!(); }
618         }
619
620         #[test]
621         fn tlv_req_type_missing_or_extra() {
622                 // It's also bad if they included even fields we don't understand
623                 if let Err(DecodeError::UnknownRequiredFeature) = tlv_reader(&::hex::decode(
624                                 concat!("0100", "0208deadbeef1badbeef", "0304deadbeef", "0600")
625                                 ).unwrap()[..]) {
626                 } else { panic!(); }
627                 // ... or if they're missing fields we need
628                 if let Err(DecodeError::InvalidValue) = tlv_reader(&::hex::decode(
629                                 concat!("0100", "0208deadbeef1badbeef")
630                                 ).unwrap()[..]) {
631                 } else { panic!(); }
632                 // ... even if that field is even
633                 if let Err(DecodeError::InvalidValue) = tlv_reader(&::hex::decode(
634                                 concat!("0304deadbeef", "0500")
635                                 ).unwrap()[..]) {
636                 } else { panic!(); }
637         }
638
639         #[test]
640         fn tlv_simple_good_cases() {
641                 assert_eq!(tlv_reader(&::hex::decode(
642                                 concat!("0208deadbeef1badbeef", "03041bad1dea")
643                                 ).unwrap()[..]).unwrap(),
644                         (0xdeadbeef1badbeef, 0x1bad1dea, None));
645                 assert_eq!(tlv_reader(&::hex::decode(
646                                 concat!("0208deadbeef1badbeef", "03041bad1dea", "040401020304")
647                                 ).unwrap()[..]).unwrap(),
648                         (0xdeadbeef1badbeef, 0x1bad1dea, Some(0x01020304)));
649         }
650
651         // BOLT TLV test cases
652         fn tlv_reader_n1(s: &[u8]) -> Result<(Option<HighZeroBytesDroppedBigSize<u64>>, Option<u64>, Option<(PublicKey, u64, u64)>, Option<u16>), DecodeError> {
653                 let mut s = Cursor::new(s);
654                 let mut tlv1: Option<HighZeroBytesDroppedBigSize<u64>> = None;
655                 let mut tlv2: Option<u64> = None;
656                 let mut tlv3: Option<(PublicKey, u64, u64)> = None;
657                 let mut tlv4: Option<u16> = None;
658                 decode_tlv_stream!(&mut s, {(1, tlv1, option), (2, tlv2, option), (3, tlv3, option), (254, tlv4, option)});
659                 Ok((tlv1, tlv2, tlv3, tlv4))
660         }
661
662         #[test]
663         fn bolt_tlv_bogus_stream() {
664                 macro_rules! do_test {
665                         ($stream: expr, $reason: ident) => {
666                                 if let Err(DecodeError::$reason) = tlv_reader_n1(&::hex::decode($stream).unwrap()[..]) {
667                                 } else { panic!(); }
668                         }
669                 }
670
671                 // TLVs from the BOLT test cases which should not decode as either n1 or n2
672                 do_test!(concat!("fd01"), ShortRead);
673                 do_test!(concat!("fd0001", "00"), InvalidValue);
674                 do_test!(concat!("fd0101"), ShortRead);
675                 do_test!(concat!("0f", "fd"), ShortRead);
676                 do_test!(concat!("0f", "fd26"), ShortRead);
677                 do_test!(concat!("0f", "fd2602"), ShortRead);
678                 do_test!(concat!("0f", "fd0001", "00"), InvalidValue);
679                 do_test!(concat!("0f", "fd0201", "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), ShortRead);
680
681                 do_test!(concat!("12", "00"), UnknownRequiredFeature);
682                 do_test!(concat!("fd0102", "00"), UnknownRequiredFeature);
683                 do_test!(concat!("fe01000002", "00"), UnknownRequiredFeature);
684                 do_test!(concat!("ff0100000000000002", "00"), UnknownRequiredFeature);
685         }
686
687         #[test]
688         fn bolt_tlv_bogus_n1_stream() {
689                 macro_rules! do_test {
690                         ($stream: expr, $reason: ident) => {
691                                 if let Err(DecodeError::$reason) = tlv_reader_n1(&::hex::decode($stream).unwrap()[..]) {
692                                 } else { panic!(); }
693                         }
694                 }
695
696                 // TLVs from the BOLT test cases which should not decode as n1
697                 do_test!(concat!("01", "09", "ffffffffffffffffff"), InvalidValue);
698                 do_test!(concat!("01", "01", "00"), InvalidValue);
699                 do_test!(concat!("01", "02", "0001"), InvalidValue);
700                 do_test!(concat!("01", "03", "000100"), InvalidValue);
701                 do_test!(concat!("01", "04", "00010000"), InvalidValue);
702                 do_test!(concat!("01", "05", "0001000000"), InvalidValue);
703                 do_test!(concat!("01", "06", "000100000000"), InvalidValue);
704                 do_test!(concat!("01", "07", "00010000000000"), InvalidValue);
705                 do_test!(concat!("01", "08", "0001000000000000"), InvalidValue);
706                 do_test!(concat!("02", "07", "01010101010101"), ShortRead);
707                 do_test!(concat!("02", "09", "010101010101010101"), InvalidValue);
708                 do_test!(concat!("03", "21", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb"), ShortRead);
709                 do_test!(concat!("03", "29", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb0000000000000001"), ShortRead);
710                 do_test!(concat!("03", "30", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb000000000000000100000000000001"), ShortRead);
711                 do_test!(concat!("03", "31", "043da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb00000000000000010000000000000002"), InvalidValue);
712                 do_test!(concat!("03", "32", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb0000000000000001000000000000000001"), InvalidValue);
713                 do_test!(concat!("fd00fe", "00"), ShortRead);
714                 do_test!(concat!("fd00fe", "01", "01"), ShortRead);
715                 do_test!(concat!("fd00fe", "03", "010101"), InvalidValue);
716                 do_test!(concat!("00", "00"), UnknownRequiredFeature);
717
718                 do_test!(concat!("02", "08", "0000000000000226", "01", "01", "2a"), InvalidValue);
719                 do_test!(concat!("02", "08", "0000000000000231", "02", "08", "0000000000000451"), InvalidValue);
720                 do_test!(concat!("1f", "00", "0f", "01", "2a"), InvalidValue);
721                 do_test!(concat!("1f", "00", "1f", "01", "2a"), InvalidValue);
722
723                 // The last BOLT test modified to not require creating a new decoder for one trivial test.
724                 do_test!(concat!("ffffffffffffffffff", "00", "01", "00"), InvalidValue);
725         }
726
727         #[test]
728         fn bolt_tlv_valid_n1_stream() {
729                 macro_rules! do_test {
730                         ($stream: expr, $tlv1: expr, $tlv2: expr, $tlv3: expr, $tlv4: expr) => {
731                                 if let Ok((tlv1, tlv2, tlv3, tlv4)) = tlv_reader_n1(&::hex::decode($stream).unwrap()[..]) {
732                                         assert_eq!(tlv1.map(|v| v.0), $tlv1);
733                                         assert_eq!(tlv2, $tlv2);
734                                         assert_eq!(tlv3, $tlv3);
735                                         assert_eq!(tlv4, $tlv4);
736                                 } else { panic!(); }
737                         }
738                 }
739
740                 do_test!(concat!(""), None, None, None, None);
741                 do_test!(concat!("21", "00"), None, None, None, None);
742                 do_test!(concat!("fd0201", "00"), None, None, None, None);
743                 do_test!(concat!("fd00fd", "00"), None, None, None, None);
744                 do_test!(concat!("fd00ff", "00"), None, None, None, None);
745                 do_test!(concat!("fe02000001", "00"), None, None, None, None);
746                 do_test!(concat!("ff0200000000000001", "00"), None, None, None, None);
747
748                 do_test!(concat!("01", "00"), Some(0), None, None, None);
749                 do_test!(concat!("01", "01", "01"), Some(1), None, None, None);
750                 do_test!(concat!("01", "02", "0100"), Some(256), None, None, None);
751                 do_test!(concat!("01", "03", "010000"), Some(65536), None, None, None);
752                 do_test!(concat!("01", "04", "01000000"), Some(16777216), None, None, None);
753                 do_test!(concat!("01", "05", "0100000000"), Some(4294967296), None, None, None);
754                 do_test!(concat!("01", "06", "010000000000"), Some(1099511627776), None, None, None);
755                 do_test!(concat!("01", "07", "01000000000000"), Some(281474976710656), None, None, None);
756                 do_test!(concat!("01", "08", "0100000000000000"), Some(72057594037927936), None, None, None);
757                 do_test!(concat!("02", "08", "0000000000000226"), None, Some((0 << 30) | (0 << 5) | (550 << 0)), None, None);
758                 do_test!(concat!("03", "31", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb00000000000000010000000000000002"),
759                         None, None, Some((
760                                 PublicKey::from_slice(&::hex::decode("023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb").unwrap()[..]).unwrap(), 1, 2)),
761                         None);
762                 do_test!(concat!("fd00fe", "02", "0226"), None, None, None, Some(550));
763         }
764
765         fn do_simple_test_tlv_write() -> Result<(), io::Error> {
766                 let mut stream = VecWriter(Vec::new());
767
768                 stream.0.clear();
769                 encode_varint_length_prefixed_tlv!(&mut stream, {(1, 1u8, required), (42, None::<u64>, option)});
770                 assert_eq!(stream.0, ::hex::decode("03010101").unwrap());
771
772                 stream.0.clear();
773                 encode_varint_length_prefixed_tlv!(&mut stream, {(1, Some(1u8), option)});
774                 assert_eq!(stream.0, ::hex::decode("03010101").unwrap());
775
776                 stream.0.clear();
777                 encode_varint_length_prefixed_tlv!(&mut stream, {(4, 0xabcdu16, required), (42, None::<u64>, option)});
778                 assert_eq!(stream.0, ::hex::decode("040402abcd").unwrap());
779
780                 stream.0.clear();
781                 encode_varint_length_prefixed_tlv!(&mut stream, {(42, None::<u64>, option), (0xff, 0xabcdu16, required)});
782                 assert_eq!(stream.0, ::hex::decode("06fd00ff02abcd").unwrap());
783
784                 stream.0.clear();
785                 encode_varint_length_prefixed_tlv!(&mut stream, {(0, 1u64, required), (42, None::<u64>, option), (0xff, HighZeroBytesDroppedBigSize(0u64), required)});
786                 assert_eq!(stream.0, ::hex::decode("0e00080000000000000001fd00ff00").unwrap());
787
788                 stream.0.clear();
789                 encode_varint_length_prefixed_tlv!(&mut stream, {(0, Some(1u64), option), (0xff, HighZeroBytesDroppedBigSize(0u64), required)});
790                 assert_eq!(stream.0, ::hex::decode("0e00080000000000000001fd00ff00").unwrap());
791
792                 Ok(())
793         }
794
795         #[test]
796         fn simple_test_tlv_write() {
797                 do_simple_test_tlv_write().unwrap();
798         }
799 }