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