lulz
[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)),*}, {$(($optional_type: expr, $optional_field: expr)),*}) => {
12                 encode_tlv!(::util::ser::BigSize, $stream, {$(($type, $field)),*}, {$(($optional_type, $optional_field)),*});
13         };
14         ($name_ty: path, $stream: expr, {$(($type: expr, $field: expr)),*}, {$(($optional_type: expr, $optional_field: expr)),*}) => { {
15                 #[allow(unused_imports)]
16                 use util::ser::BigSize;
17                 // Fields must be serialized in order, so we have to potentially switch between optional
18                 // fields and normal fields while serializing. Thus, we end up having to loop over the type
19                 // counts.
20                 // Sadly, while LLVM does appear smart enough to make `max_field` a constant, it appears to
21                 // refuse to unroll the loop. If we have enough entries that this is slow we can revisit
22                 // this design in the future.
23                 #[allow(unused_mut)]
24                 let mut max_field: u64 = 0;
25                 $(
26                         if $type + 1 >= max_field { max_field = $type + 1; }
27                 )*
28                 $(
29                         if $optional_type + 1 >= max_field { max_field = $optional_type + 1; }
30                 )*
31                 #[allow(unused_variables)]
32                 for i in 0..max_field {
33                         $(
34                                 if i == $type {
35                                         $name_ty($type).write($stream)?;
36                                         BigSize($field.serialized_length() as u64).write($stream)?;
37                                         $field.write($stream)?;
38                                 }
39                         )*
40                         $(
41                                 if i == $optional_type {
42                                         if let Some(ref field) = $optional_field {
43                                                 $name_ty($optional_type).write($stream)?;
44                                                 BigSize(field.serialized_length() as u64).write($stream)?;
45                                                 field.write($stream)?;
46                                         }
47                                 }
48                         )*
49                 }
50         } }
51 }
52
53 macro_rules! get_varint_length_prefixed_tlv_length {
54         ($name_ty: path, {$(($type: expr, $field: expr)),*}, {$(($optional_type: expr, $optional_field: expr)),* $(,)*}) => { {
55                 use util::ser::LengthCalculatingWriter;
56                 #[allow(unused_mut)]
57                 let mut len = LengthCalculatingWriter(0);
58                 {
59                         $(
60                                 $name_ty($type).write(&mut len).expect("No in-memory data may fail to serialize");
61                                 let field_len = $field.serialized_length();
62                                 BigSize(field_len as u64).write(&mut len).expect("No in-memory data may fail to serialize");
63                                 len.0 += field_len;
64                         )*
65                         $(
66                                 if let Some(ref field) = $optional_field {
67                                         $name_ty($optional_type).write(&mut len).expect("No in-memory data may fail to serialize");
68                                         let field_len = field.serialized_length();
69                                         BigSize(field_len as u64).write(&mut len).expect("No in-memory data may fail to serialize");
70                                         len.0 += field_len;
71                                 }
72                         )*
73                 }
74                 len.0
75         } }
76 }
77
78 macro_rules! encode_varint_length_prefixed_tlv {
79         ($stream: expr, {$(($type: expr, $field: expr)),*}, {$(($optional_type: expr, $optional_field: expr)),*}) => {
80                 encode_varint_length_prefixed_tlv!(::util::ser::BigSize, $stream, {$(($type, $field)),*}, {$(($optional_type, $optional_field)),*});
81         };
82         ($name_ty: path, $stream: expr, {$(($type: expr, $field: expr)),*}, {$(($optional_type: expr, $optional_field: expr)),*}) => { {
83                 use util::ser::BigSize;
84                 let len = get_varint_length_prefixed_tlv_length!($name_ty, { $(($type, $field)),* }, { $(($optional_type, $optional_field)),* });
85                 BigSize(len as u64).write($stream)?;
86                 encode_tlv!($stream, { $(($type, $field)),* }, { $(($optional_type, $optional_field)),* });
87         } }
88 }
89
90 macro_rules! decode_tlv {
91         ($stream: expr, {$(($reqtype: expr, $reqfield: ident)),*}, {$(($type: expr, $field: ident)),*}) => {
92                 decode_tlv!(::util::ser::BigSize, $stream, {$(($reqtype, $reqfield)),*}, {$(($type, $field)),*});
93         };
94         ($name_ty: path, $stream: expr, {$(($reqtype: expr, $reqfield: ident)),*}, {$(($type: expr, $field: ident)),*}) => { {
95                 use ln::msgs::DecodeError;
96                 #[allow(unused_imports)]
97                 use std::io::Read;
98                 #[allow(unused_imports)]
99                 use util::ser::Lulz;
100                 let mut last_seen_type = None;
101                 'tlv_read: loop {
102                         use util::ser;
103
104                         // First decode the type of this TLV:
105                         let typ: $name_ty = {
106                                 // We track whether any bytes were read during the consensus_decode call to
107                                 // determine whether we should break or return ShortRead if we get an
108                                 // UnexpectedEof. This should in every case be largely cosmetic, but its nice to
109                                 // pass the TLV test vectors exactly, which requre this distinction.
110                                 let mut tracking_reader = ser::ReadTrackingReader::new($stream);
111                                 match ser::Readable::read(&mut tracking_reader) {
112                                         Err(DecodeError::ShortRead) => {
113                                                 if !tracking_reader.have_read {
114                                                         break 'tlv_read
115                                                 } else {
116                                                         Err(DecodeError::ShortRead)?
117                                                 }
118                                         },
119                                         Err(e) => Err(e)?,
120                                         Ok(t) => t,
121                                 }
122                         };
123
124                         // Types must be unique and monotonically increasing:
125                         match last_seen_type {
126                                 Some(t) if typ.0 <= t => {
127                                         Err(DecodeError::InvalidValue)?
128                                 },
129                                 _ => {},
130                         }
131                         // As we read types, make sure we hit every required type:
132                         $({
133                                 #[allow(unused_comparisons)] // Note that $reqtype may be 0 making the second comparison always true
134                                 let invalid_order = (last_seen_type.is_none() || last_seen_type.unwrap() < $reqtype) && typ.0 > $reqtype;
135                                 if invalid_order {
136                                         Err(DecodeError::InvalidValue)?
137                                 }
138                         })*
139                         last_seen_type = Some(typ.0);
140
141                         // Finally, read the length and value itself:
142                         match typ.0 {
143                                 $($reqtype => {
144                                         match $reqfield.fixed_len_read() {
145                                                 Some(len) if len != 0 => {
146                                                         let mut v = [0u8; 9];
147                                                         let bslen = {
148                                                                 let mut w = &mut v[..];
149                                                                 ser::BigSize(len as u64).write(&mut w).unwrap();
150                                                                 9 - w.len()
151                                                         };
152                                                         assert!(bslen < 9);
153                                                         let mut r = [0; 9];
154                                                         $stream.read_exact(&mut r[0..bslen])?;
155                                                         if r[..bslen] != v[..bslen] {
156                                                                 Err(DecodeError::InvalidValue)?
157                                                         }
158                                                         $reqfield = ser::Readable::read($stream)?;
159                                                 },
160                                                 _ => {
161                                                         let length: ser::BigSize = Readable::read($stream)?;
162                                                         let mut s = ser::FixedLengthReader::new($stream, length.0);
163                                                         $reqfield = ser::Readable::read(&mut s)?;
164                                                         if s.bytes_remain() {
165                                                                 s.eat_remaining()?; // Return ShortRead if there's actually not enough bytes
166                                                                 Err(DecodeError::InvalidValue)?
167                                                         }
168                                                 }
169                                         }
170                                 },)*
171                                 $($type => {
172                                         match $field.lulz_len_read() {
173                                                 Some(len) if len != 0 => {
174                                                         let mut v = [0u8; 9];
175                                                         let bslen = {
176                                                                 let mut w = &mut v[..];
177                                                                 ser::BigSize(len as u64).write(&mut w).unwrap();
178                                                                 9 - w.len()
179                                                         };
180                                                         assert!(bslen < 9);
181                                                         let mut r = [0; 9];
182                                                         $stream.read_exact(&mut r[0..bslen])?;
183                                                         if r[..bslen] != v[..bslen] {
184                                                                 Err(DecodeError::InvalidValue)?
185                                                         }
186                                                         $field = Some(ser::Readable::read($stream)?);
187                                                 },
188                                                 _ => {
189                                                         let length: ser::BigSize = Readable::read($stream)?;
190                                                         let mut s = ser::FixedLengthReader::new($stream, length.0);
191                                                         $field = Some(ser::Readable::read(&mut s)?);
192                                                         if s.bytes_remain() {
193                                                                 s.eat_remaining()?; // Return ShortRead if there's actually not enough bytes
194                                                                 Err(DecodeError::InvalidValue)?
195                                                         }
196                                                 }
197                                         }
198                                 },)*
199                                 x if x % 2 == 0 => {
200                                         Err(DecodeError::UnknownRequiredFeature)?
201                                 },
202                                 _ => {
203                                         let length: ser::BigSize = Readable::read($stream)?;
204                                         let mut s = ser::FixedLengthReader::new($stream, length.0);
205                                         s.eat_remaining()?;
206                                 },
207                         }
208                 }
209                 // Make sure we got to each required type after we've read every TLV:
210                 $({
211                         #[allow(unused_comparisons)] // Note that $reqtype may be 0 making the second comparison always true
212                         let missing_req_type = last_seen_type.is_none() || last_seen_type.unwrap() < $reqtype;
213                         if missing_req_type {
214                                 Err(DecodeError::InvalidValue)?
215                         }
216                 })*
217         } }
218 }
219
220 macro_rules! impl_writeable {
221         ($st:ident, $len: expr, {$($field:ident),*}) => {
222                 impl ::util::ser::Writeable for $st {
223                         fn write<W: ::util::ser::Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
224                                 if $len != 0 {
225                                         w.size_hint($len);
226                                 }
227                                 #[cfg(any(test, feature = "fuzztarget"))]
228                                 {
229                                         // In tests, assert that the hard-coded length matches the actual one
230                                         if $len != 0 {
231                                                 use util::ser::LengthCalculatingWriter;
232                                                 let mut len_calc = LengthCalculatingWriter(0);
233                                                 $( self.$field.write(&mut len_calc).expect("No in-memory data may fail to serialize"); )*
234                                                 assert_eq!(len_calc.0, $len);
235                                         }
236                                 }
237                                 $( self.$field.write(w)?; )*
238                                 Ok(())
239                         }
240
241                         #[inline]
242                         fn serialized_length(&self) -> usize {
243                                 if $len == 0 || cfg!(any(test, feature = "fuzztarget")) {
244                                         let mut len_calc = 0;
245                                         $( len_calc += self.$field.serialized_length(); )*
246                                         if $len != 0 {
247                                                 // In tests, assert that the hard-coded length matches the actual one
248                                                 assert_eq!(len_calc, $len);
249                                         } else {
250                                                 return len_calc;
251                                         }
252                                 }
253                                 $len
254                         }
255                 }
256
257                 impl ::util::ser::Readable for $st {
258                         fn read<R: ::std::io::Read>(r: &mut R) -> Result<Self, ::ln::msgs::DecodeError> {
259                                 Ok(Self {
260                                         $($field: ::util::ser::Readable::read(r)?),*
261                                 })
262                         }
263                         const FIXED_LEN: Option<usize> = Some($len);
264                 }
265         }
266 }
267 macro_rules! impl_writeable_len_match {
268         ($struct: ident, $cmp: tt, ($calc_len: expr), {$({$match: pat, $length: expr}),*}, {$($field:ident),*}) => {
269                 impl Writeable for $struct {
270                         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
271                                 let len = match *self {
272                                         $($match => $length,)*
273                                 };
274                                 w.size_hint(len);
275                                 #[cfg(any(test, feature = "fuzztarget"))]
276                                 {
277                                         // In tests, assert that the hard-coded length matches the actual one
278                                         use util::ser::LengthCalculatingWriter;
279                                         let mut len_calc = LengthCalculatingWriter(0);
280                                         $( self.$field.write(&mut len_calc).expect("No in-memory data may fail to serialize"); )*
281                                         assert!(len_calc.0 $cmp len);
282                                 }
283                                 $( self.$field.write(w)?; )*
284                                 Ok(())
285                         }
286
287                         #[inline]
288                         fn serialized_length(&self) -> usize {
289                                 if $calc_len || cfg!(any(test, feature = "fuzztarget")) {
290                                         let mut len_calc = 0;
291                                         $( len_calc += self.$field.serialized_length(); )*
292                                         if !$calc_len {
293                                                 assert_eq!(len_calc, match *self {
294                                                         $($match => $length,)*
295                                                 });
296                                         }
297                                         return len_calc
298                                 }
299                                 match *self {
300                                         $($match => $length,)*
301                                 }
302                         }
303                 }
304
305                 impl ::util::ser::Readable for $struct {
306                         fn read<R: ::std::io::Read>(r: &mut R) -> Result<Self, DecodeError> {
307                                 Ok(Self {
308                                         $($field: Readable::read(r)?),*
309                                 })
310                         }
311                 }
312         };
313         ($struct: ident, $cmp: tt, {$({$match: pat, $length: expr}),*}, {$($field:ident),*}) => {
314                 impl_writeable_len_match!($struct, $cmp, (true), { $({ $match, $length }),* }, { $($field),* });
315         };
316         ($struct: ident, {$({$match: pat, $length: expr}),*}, {$($field:ident),*}) => {
317                 impl_writeable_len_match!($struct, ==, (false), { $({ $match, $length }),* }, { $($field),* });
318         }
319 }
320
321 /// Write out two bytes to indicate the version of an object.
322 /// $this_version represents a unique version of a type. Incremented whenever the type's
323 ///               serialization format has changed or has a new interpretation. Used by a type's
324 ///               reader to determine how to interpret fields or if it can understand a serialized
325 ///               object.
326 /// $min_version_that_can_read_this is the minimum reader version which can understand this
327 ///                                 serialized object. Previous versions will simply err with a
328 ///                                 DecodeError::UnknownVersion.
329 ///
330 /// Updates to either $this_version or $min_version_that_can_read_this should be included in
331 /// release notes.
332 ///
333 /// Both version fields can be specific to this type of object.
334 macro_rules! write_ver_prefix {
335         ($stream: expr, $this_version: expr, $min_version_that_can_read_this: expr) => {
336                 $stream.write_all(&[$this_version; 1])?;
337                 $stream.write_all(&[$min_version_that_can_read_this; 1])?;
338         }
339 }
340
341 /// Writes out a suffix to an object which contains potentially backwards-compatible, optional
342 /// fields which old nodes can happily ignore.
343 ///
344 /// It is written out in TLV format and, as with all TLV fields, unknown even fields cause a
345 /// DecodeError::UnknownRequiredFeature error, with unknown odd fields ignored.
346 ///
347 /// This is the preferred method of adding new fields that old nodes can ignore and still function
348 /// correctly.
349 macro_rules! write_tlv_fields {
350         ($stream: expr, {$(($type: expr, $field: expr)),* $(,)*}, {$(($optional_type: expr, $optional_field: expr)),* $(,)*}) => {
351                 encode_varint_length_prefixed_tlv!(::util::ser::U8Wrapper, $stream, {$(($type, $field)),*} , {$(($optional_type, $optional_field)),*});
352         }
353 }
354
355 /// Reads a prefix added by write_ver_prefix!(), above. Takes the current version of the
356 /// serialization logic for this object. This is compared against the
357 /// $min_version_that_can_read_this added by write_ver_prefix!().
358 macro_rules! read_ver_prefix {
359         ($stream: expr, $this_version: expr) => { {
360                 let ver: u8 = Readable::read($stream)?;
361                 let min_ver: u8 = Readable::read($stream)?;
362                 if min_ver > $this_version {
363                         return Err(DecodeError::UnknownVersion);
364                 }
365                 ver
366         } }
367 }
368
369 /// Reads a suffix added by write_tlv_fields.
370 macro_rules! read_tlv_fields {
371         ($stream: expr, {$(($reqtype: expr, $reqfield: ident)),* $(,)*}, {$(($type: expr, $field: ident)),* $(,)*}) => { {
372                 let tlv_len = ::util::ser::BigSize::read($stream)?;
373                 let mut rd = ::util::ser::FixedLengthReader::new($stream, tlv_len.0);
374                 decode_tlv!(::util::ser::U8Wrapper, &mut rd, {$(($reqtype, $reqfield)),*}, {$(($type, $field)),*});
375                 rd.eat_remaining().map_err(|_| DecodeError::ShortRead)?;
376         } }
377 }
378
379 // If we naively create a struct in impl_writeable_tlv_based below, we may end up returning
380 // `Self { ,,vecfield: vecfield }` which is obviously incorrect. Instead, we have to match here to
381 // detect at least one empty field set and skip the potentially-extra comma.
382 macro_rules! _init_tlv_based_struct {
383         ({}, {$($field: ident),*}, {$($vecfield: ident),*}) => {
384                 Ok(Self {
385                         $($field),*,
386                         $($vecfield: $vecfield.unwrap().0),*
387                 })
388         };
389         ({$($reqfield: ident),*}, {}, {$($vecfield: ident),*}) => {
390                 Ok(Self {
391                         $($reqfield: $reqfield.0.unwrap()),*,
392                         $($vecfield: $vecfield.unwrap().0),*
393                 })
394         };
395         ({$($reqfield: ident),*}, {$($field: ident),*}, {}) => {
396                 Ok(Self {
397                         $($reqfield: $reqfield.0.unwrap()),*,
398                         $($field),*
399                 })
400         };
401         ({$($reqfield: ident),*}, {$($field: ident),*}, {$($vecfield: ident),*}) => {
402                 Ok(Self {
403                         $($reqfield: $reqfield.0.unwrap()),*,
404                         $($field),*,
405                         $($vecfield: $vecfield.unwrap().0),*
406                 })
407         }
408 }
409
410 // If we don't have any optional types below, but do have some vec types, we end up calling
411 // `write_tlv_field!($stream, {..}, {, (vec_ty, vec_val)})`, which is obviously broken.
412 // Instead, for write and read we match the missing values and skip the extra comma.
413 macro_rules! _write_tlv_fields {
414         ($stream: expr, {$(($type: expr, $field: expr)),* $(,)*}, {}, {$(($optional_type: expr, $optional_field: expr)),* $(,)*}) => {
415                 write_tlv_fields!($stream, {$(($type, $field)),*} , {$(($optional_type, $optional_field)),*});
416         };
417         ($stream: expr, {$(($type: expr, $field: expr)),* $(,)*}, {$(($optional_type: expr, $optional_field: expr)),* $(,)*}, {$(($optional_type_2: expr, $optional_field_2: expr)),* $(,)*}) => {
418                 write_tlv_fields!($stream, {$(($type, $field)),*} , {$(($optional_type, $optional_field)),*, $(($optional_type_2, $optional_field_2)),*});
419         }
420 }
421 macro_rules! _get_tlv_len {
422         ({$(($type: expr, $field: expr)),* $(,)*}, {}, {$(($optional_type: expr, $optional_field: expr)),* $(,)*}) => {
423                 get_varint_length_prefixed_tlv_length!(::util::ser::U8Wrapper, {$(($type, $field)),*} , {$(($optional_type, $optional_field)),*})
424         };
425         ({$(($type: expr, $field: expr)),* $(,)*}, {$(($optional_type: expr, $optional_field: expr)),* $(,)*}, {$(($optional_type_2: expr, $optional_field_2: expr)),* $(,)*}) => {
426                 get_varint_length_prefixed_tlv_length!(::util::ser::U8Wrapper, {$(($type, $field)),*} , {$(($optional_type, $optional_field)),*, $(($optional_type_2, $optional_field_2)),*})
427         }
428 }
429 macro_rules! _read_tlv_fields {
430         ($stream: expr, {$(($reqtype: expr, $reqfield: ident)),* $(,)*}, {}, {$(($type: expr, $field: ident)),* $(,)*}) => {
431                 read_tlv_fields!($stream, {$(($reqtype, $reqfield)),*}, {$(($type, $field)),*});
432         };
433         ($stream: expr, {$(($reqtype: expr, $reqfield: ident)),* $(,)*}, {$(($type: expr, $field: ident)),* $(,)*}, {$(($type_2: expr, $field_2: ident)),* $(,)*}) => {
434                 read_tlv_fields!($stream, {$(($reqtype, $reqfield)),*}, {$(($type, $field)),*, $(($type_2, $field_2)),*});
435         }
436 }
437
438 /// Implements Readable/Writeable for a struct storing it as a set of TLVs
439 /// First block includes all the required fields including a dummy value which is used during
440 /// deserialization but which will never be exposed to other code.
441 /// The second block includes optional fields.
442 /// The third block includes any Vecs which need to have their individual elements serialized.
443 macro_rules! impl_writeable_tlv_based {
444         ($st: ident, {$(($reqtype: expr, $reqfield: ident)),* $(,)*}, {$(($type: expr, $field: ident)),* $(,)*}, {$(($vectype: expr, $vecfield: ident)),* $(,)*}) => {
445                 impl ::util::ser::Writeable for $st {
446                         fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
447                                 _write_tlv_fields!(writer, {
448                                         $(($reqtype, self.$reqfield)),*
449                                 }, {
450                                         $(($type, self.$field)),*
451                                 }, {
452                                         $(($vectype, Some(::util::ser::VecWriteWrapper(&self.$vecfield)))),*
453                                 });
454                                 Ok(())
455                         }
456
457                         #[inline]
458                         fn serialized_length(&self) -> usize {
459                                 let len = _get_tlv_len!({
460                                         $(($reqtype, self.$reqfield)),*
461                                 }, {
462                                         $(($type, self.$field)),*
463                                 }, {
464                                         $(($vectype, Some(::util::ser::VecWriteWrapper(&self.$vecfield)))),*
465                                 });
466                                 use util::ser::{BigSize, LengthCalculatingWriter};
467                                 let mut len_calc = LengthCalculatingWriter(0);
468                                 BigSize(len as u64).write(&mut len_calc).expect("No in-memory data may fail to serialize");
469                                 len + len_calc.0
470                         }
471                 }
472
473                 impl ::util::ser::Readable for $st {
474                         fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, ::ln::msgs::DecodeError> {
475                                 $(
476                                         let mut $reqfield = ::util::ser::OptionDeserWrapper(None);
477                                 )*
478                                 $(
479                                         let mut $field = None;
480                                 )*
481                                 $(
482                                         let mut $vecfield = Some(::util::ser::VecReadWrapper(Vec::new()));
483                                 )*
484                                 _read_tlv_fields!(reader, {
485                                         $(($reqtype, $reqfield)),*
486                                 }, {
487                                         $(($type, $field)),*
488                                 }, {
489                                         $(($vectype, $vecfield)),*
490                                 });
491                                 _init_tlv_based_struct!({$($reqfield),*}, {$($field),*}, {$($vecfield),*})
492                         }
493                 }
494         }
495 }
496
497 #[cfg(test)]
498 mod tests {
499         use prelude::*;
500         use std::io::{Cursor, Read};
501         use ln::msgs::DecodeError;
502         use util::ser::{Readable, Writeable, HighZeroBytesDroppedVarInt, VecWriter};
503         use bitcoin::secp256k1::PublicKey;
504
505         // The BOLT TLV test cases don't include any tests which use our "required-value" logic since
506         // the encoding layer in the BOLTs has no such concept, though it makes our macros easier to
507         // work with so they're baked into the decoder. Thus, we have a few additional tests below
508         fn tlv_reader(s: &[u8]) -> Result<(u64, u32, Option<u32>), DecodeError> {
509                 let mut s = Cursor::new(s);
510                 let mut a: u64 = 0;
511                 let mut b: u32 = 0;
512                 let mut c: Option<u32> = None;
513                 decode_tlv!(&mut s, {(2, a), (3, b)}, {(4, c)});
514                 Ok((a, b, c))
515         }
516
517         #[test]
518         fn tlv_v_short_read() {
519                 // We only expect a u32 for type 3 (which we are given), but the L says its 8 bytes.
520                 if let Err(DecodeError::ShortRead) = tlv_reader(&::hex::decode(
521                                 concat!("0100", "0208deadbeef1badbeef", "0308deadbeef")
522                                 ).unwrap()[..]) {
523                 } else { panic!(); }
524         }
525
526         #[test]
527         fn tlv_types_out_of_order() {
528                 if let Err(DecodeError::InvalidValue) = tlv_reader(&::hex::decode(
529                                 concat!("0100", "0304deadbeef", "0208deadbeef1badbeef")
530                                 ).unwrap()[..]) {
531                 } else { panic!(); }
532                 // ...even if its some field we don't understand
533                 if let Err(DecodeError::InvalidValue) = tlv_reader(&::hex::decode(
534                                 concat!("0208deadbeef1badbeef", "0100", "0304deadbeef")
535                                 ).unwrap()[..]) {
536                 } else { panic!(); }
537         }
538
539         #[test]
540         fn tlv_req_type_missing_or_extra() {
541                 // It's also bad if they included even fields we don't understand
542                 if let Err(DecodeError::UnknownRequiredFeature) = tlv_reader(&::hex::decode(
543                                 concat!("0100", "0208deadbeef1badbeef", "0304deadbeef", "0600")
544                                 ).unwrap()[..]) {
545                 } else { panic!(); }
546                 // ... or if they're missing fields we need
547                 if let Err(DecodeError::InvalidValue) = tlv_reader(&::hex::decode(
548                                 concat!("0100", "0208deadbeef1badbeef")
549                                 ).unwrap()[..]) {
550                 } else { panic!(); }
551                 // ... even if that field is even
552                 if let Err(DecodeError::InvalidValue) = tlv_reader(&::hex::decode(
553                                 concat!("0304deadbeef", "0500")
554                                 ).unwrap()[..]) {
555                 } else { panic!(); }
556         }
557
558         #[test]
559         fn tlv_simple_good_cases() {
560                 assert_eq!(tlv_reader(&::hex::decode(
561                                 concat!("0208deadbeef1badbeef", "03041bad1dea")
562                                 ).unwrap()[..]).unwrap(),
563                         (0xdeadbeef1badbeef, 0x1bad1dea, None));
564                 assert_eq!(tlv_reader(&::hex::decode(
565                                 concat!("0208deadbeef1badbeef", "03041bad1dea", "040401020304")
566                                 ).unwrap()[..]).unwrap(),
567                         (0xdeadbeef1badbeef, 0x1bad1dea, Some(0x01020304)));
568         }
569
570         impl Readable for (PublicKey, u64, u64) {
571                 #[inline]
572                 fn read<R: Read>(reader: &mut R) -> Result<(PublicKey, u64, u64), DecodeError> {
573                         Ok((Readable::read(reader)?, Readable::read(reader)?, Readable::read(reader)?))
574                 }
575         }
576
577         // BOLT TLV test cases
578         fn tlv_reader_n1(s: &[u8]) -> Result<(Option<HighZeroBytesDroppedVarInt<u64>>, Option<u64>, Option<(PublicKey, u64, u64)>, Option<u16>), DecodeError> {
579                 let mut s = Cursor::new(s);
580                 let mut tlv1: Option<HighZeroBytesDroppedVarInt<u64>> = None;
581                 let mut tlv2: Option<u64> = None;
582                 let mut tlv3: Option<(PublicKey, u64, u64)> = None;
583                 let mut tlv4: Option<u16> = None;
584                 decode_tlv!(&mut s, {}, {(1, tlv1), (2, tlv2), (3, tlv3), (254, tlv4)});
585                 Ok((tlv1, tlv2, tlv3, tlv4))
586         }
587
588         #[test]
589         fn bolt_tlv_bogus_stream() {
590                 macro_rules! do_test {
591                         ($stream: expr, $reason: ident) => {
592                                 if let Err(DecodeError::$reason) = tlv_reader_n1(&::hex::decode($stream).unwrap()[..]) {
593                                 } else { panic!(); }
594                         }
595                 }
596
597                 // TLVs from the BOLT test cases which should not decode as either n1 or n2
598                 do_test!(concat!("fd01"), ShortRead);
599                 do_test!(concat!("fd0001", "00"), InvalidValue);
600                 do_test!(concat!("fd0101"), ShortRead);
601                 do_test!(concat!("0f", "fd"), ShortRead);
602                 do_test!(concat!("0f", "fd26"), ShortRead);
603                 do_test!(concat!("0f", "fd2602"), ShortRead);
604                 do_test!(concat!("0f", "fd0001", "00"), InvalidValue);
605                 do_test!(concat!("0f", "fd0201", "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), ShortRead);
606
607                 do_test!(concat!("12", "00"), UnknownRequiredFeature);
608                 do_test!(concat!("fd0102", "00"), UnknownRequiredFeature);
609                 do_test!(concat!("fe01000002", "00"), UnknownRequiredFeature);
610                 do_test!(concat!("ff0100000000000002", "00"), UnknownRequiredFeature);
611         }
612
613         #[test]
614         fn bolt_tlv_bogus_n1_stream() {
615                 macro_rules! do_test {
616                         ($stream: expr, $reason: ident) => {
617                                 if let Err(DecodeError::$reason) = tlv_reader_n1(&::hex::decode($stream).unwrap()[..]) {
618                                 } else { panic!(); }
619                         }
620                 }
621
622                 // TLVs from the BOLT test cases which should not decode as n1
623                 do_test!(concat!("01", "09", "ffffffffffffffffff"), InvalidValue);
624                 do_test!(concat!("01", "01", "00"), InvalidValue);
625                 do_test!(concat!("01", "02", "0001"), InvalidValue);
626                 do_test!(concat!("01", "03", "000100"), InvalidValue);
627                 do_test!(concat!("01", "04", "00010000"), InvalidValue);
628                 do_test!(concat!("01", "05", "0001000000"), InvalidValue);
629                 do_test!(concat!("01", "06", "000100000000"), InvalidValue);
630                 do_test!(concat!("01", "07", "00010000000000"), InvalidValue);
631                 do_test!(concat!("01", "08", "0001000000000000"), InvalidValue);
632                 do_test!(concat!("02", "07", "01010101010101"), ShortRead);
633                 do_test!(concat!("02", "09", "010101010101010101"), InvalidValue);
634                 do_test!(concat!("03", "21", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb"), ShortRead);
635                 do_test!(concat!("03", "29", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb0000000000000001"), ShortRead);
636                 do_test!(concat!("03", "30", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb000000000000000100000000000001"), ShortRead);
637                 do_test!(concat!("03", "31", "043da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb00000000000000010000000000000002"), InvalidValue);
638                 do_test!(concat!("03", "32", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb0000000000000001000000000000000001"), InvalidValue);
639                 do_test!(concat!("fd00fe", "00"), ShortRead);
640                 do_test!(concat!("fd00fe", "01", "01"), ShortRead);
641                 do_test!(concat!("fd00fe", "03", "010101"), InvalidValue);
642                 do_test!(concat!("00", "00"), UnknownRequiredFeature);
643
644                 do_test!(concat!("02", "08", "0000000000000226", "01", "01", "2a"), InvalidValue);
645                 do_test!(concat!("02", "08", "0000000000000231", "02", "08", "0000000000000451"), InvalidValue);
646                 do_test!(concat!("1f", "00", "0f", "01", "2a"), InvalidValue);
647                 do_test!(concat!("1f", "00", "1f", "01", "2a"), InvalidValue);
648
649                 // The last BOLT test modified to not require creating a new decoder for one trivial test.
650                 do_test!(concat!("ffffffffffffffffff", "00", "01", "00"), InvalidValue);
651         }
652
653         #[test]
654         fn bolt_tlv_valid_n1_stream() {
655                 macro_rules! do_test {
656                         ($stream: expr, $tlv1: expr, $tlv2: expr, $tlv3: expr, $tlv4: expr) => {
657                                 if let Ok((tlv1, tlv2, tlv3, tlv4)) = tlv_reader_n1(&::hex::decode($stream).unwrap()[..]) {
658                                         assert_eq!(tlv1.map(|v| v.0), $tlv1);
659                                         assert_eq!(tlv2, $tlv2);
660                                         assert_eq!(tlv3, $tlv3);
661                                         assert_eq!(tlv4, $tlv4);
662                                 } else { panic!(); }
663                         }
664                 }
665
666                 do_test!(concat!(""), None, None, None, None);
667                 do_test!(concat!("21", "00"), None, None, None, None);
668                 do_test!(concat!("fd0201", "00"), None, None, None, None);
669                 do_test!(concat!("fd00fd", "00"), None, None, None, None);
670                 do_test!(concat!("fd00ff", "00"), None, None, None, None);
671                 do_test!(concat!("fe02000001", "00"), None, None, None, None);
672                 do_test!(concat!("ff0200000000000001", "00"), None, None, None, None);
673
674                 do_test!(concat!("01", "00"), Some(0), None, None, None);
675                 do_test!(concat!("01", "01", "01"), Some(1), None, None, None);
676                 do_test!(concat!("01", "02", "0100"), Some(256), None, None, None);
677                 do_test!(concat!("01", "03", "010000"), Some(65536), None, None, None);
678                 do_test!(concat!("01", "04", "01000000"), Some(16777216), None, None, None);
679                 do_test!(concat!("01", "05", "0100000000"), Some(4294967296), None, None, None);
680                 do_test!(concat!("01", "06", "010000000000"), Some(1099511627776), None, None, None);
681                 do_test!(concat!("01", "07", "01000000000000"), Some(281474976710656), None, None, None);
682                 do_test!(concat!("01", "08", "0100000000000000"), Some(72057594037927936), None, None, None);
683                 do_test!(concat!("02", "08", "0000000000000226"), None, Some((0 << 30) | (0 << 5) | (550 << 0)), None, None);
684                 do_test!(concat!("03", "31", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb00000000000000010000000000000002"),
685                         None, None, Some((
686                                 PublicKey::from_slice(&::hex::decode("023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb").unwrap()[..]).unwrap(), 1, 2)),
687                         None);
688                 do_test!(concat!("fd00fe", "02", "0226"), None, None, None, Some(550));
689         }
690
691         fn do_simple_test_tlv_write() -> Result<(), ::std::io::Error> {
692                 let mut stream = VecWriter(Vec::new());
693
694                 stream.0.clear();
695                 encode_varint_length_prefixed_tlv!(&mut stream, { (1, 1u8) }, { (42, None::<u64>) });
696                 assert_eq!(stream.0, ::hex::decode("03010101").unwrap());
697
698                 stream.0.clear();
699                 encode_varint_length_prefixed_tlv!(&mut stream, { }, { (1, Some(1u8)) });
700                 assert_eq!(stream.0, ::hex::decode("03010101").unwrap());
701
702                 stream.0.clear();
703                 encode_varint_length_prefixed_tlv!(&mut stream, { (4, 0xabcdu16) }, { (42, None::<u64>) });
704                 assert_eq!(stream.0, ::hex::decode("040402abcd").unwrap());
705
706                 stream.0.clear();
707                 encode_varint_length_prefixed_tlv!(&mut stream, { (0xff, 0xabcdu16) }, { (42, None::<u64>) });
708                 assert_eq!(stream.0, ::hex::decode("06fd00ff02abcd").unwrap());
709
710                 stream.0.clear();
711                 encode_varint_length_prefixed_tlv!(&mut stream, { (0, 1u64), (0xff, HighZeroBytesDroppedVarInt(0u64)) }, { (42, None::<u64>) });
712                 assert_eq!(stream.0, ::hex::decode("0e00080000000000000001fd00ff00").unwrap());
713
714                 stream.0.clear();
715                 encode_varint_length_prefixed_tlv!(&mut stream, { (0xff, HighZeroBytesDroppedVarInt(0u64)) }, { (0, Some(1u64)) });
716                 assert_eq!(stream.0, ::hex::decode("0e00080000000000000001fd00ff00").unwrap());
717
718                 Ok(())
719         }
720
721         #[test]
722         fn simple_test_tlv_write() {
723                 do_simple_test_tlv_write().unwrap();
724         }
725 }