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