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