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