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