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