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