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