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