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