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