Use more descriptive names in serialization impl macros
[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)),*}) => { {
12                 use util::ser::{BigSize, LengthCalculatingWriter};
13                 $(
14                         BigSize($type).write($stream)?;
15                         let mut len_calc = LengthCalculatingWriter(0);
16                         $field.write(&mut len_calc)?;
17                         BigSize(len_calc.0 as u64).write($stream)?;
18                         $field.write($stream)?;
19                 )*
20         } }
21 }
22
23 macro_rules! encode_varint_length_prefixed_tlv {
24         ($stream: expr, {$(($type: expr, $field: expr)),*}) => { {
25                 use util::ser::{BigSize, LengthCalculatingWriter};
26                 let mut len = LengthCalculatingWriter(0);
27                 {
28                         $(
29                                 BigSize($type).write(&mut len)?;
30                                 let mut field_len = LengthCalculatingWriter(0);
31                                 $field.write(&mut field_len)?;
32                                 BigSize(field_len.0 as u64).write(&mut len)?;
33                                 len.0 += field_len.0;
34                         )*
35                 }
36
37                 BigSize(len.0 as u64).write($stream)?;
38                 encode_tlv!($stream, {
39                         $(($type, $field)),*
40                 });
41         } }
42 }
43
44 macro_rules! decode_tlv {
45         ($stream: expr, {$(($reqtype: expr, $reqfield: ident)),*}, {$(($type: expr, $field: ident)),*}) => { {
46                 use ln::msgs::DecodeError;
47                 let mut last_seen_type: Option<u64> = None;
48                 'tlv_read: loop {
49                         use util::ser;
50
51                         // First decode the type of this TLV:
52                         let typ: ser::BigSize = {
53                                 // We track whether any bytes were read during the consensus_decode call to
54                                 // determine whether we should break or return ShortRead if we get an
55                                 // UnexpectedEof. This should in every case be largely cosmetic, but its nice to
56                                 // pass the TLV test vectors exactly, which requre this distinction.
57                                 let mut tracking_reader = ser::ReadTrackingReader::new($stream);
58                                 match ser::Readable::read(&mut tracking_reader) {
59                                         Err(DecodeError::ShortRead) => {
60                                                 if !tracking_reader.have_read {
61                                                         break 'tlv_read
62                                                 } else {
63                                                         Err(DecodeError::ShortRead)?
64                                                 }
65                                         },
66                                         Err(e) => Err(e)?,
67                                         Ok(t) => t,
68                                 }
69                         };
70
71                         // Types must be unique and monotonically increasing:
72                         match last_seen_type {
73                                 Some(t) if typ.0 <= t => {
74                                         Err(DecodeError::InvalidValue)?
75                                 },
76                                 _ => {},
77                         }
78                         // As we read types, make sure we hit every required type:
79                         $(if (last_seen_type.is_none() || last_seen_type.unwrap() < $reqtype) && typ.0 > $reqtype {
80                                 Err(DecodeError::InvalidValue)?
81                         })*
82                         last_seen_type = Some(typ.0);
83
84                         // Finally, read the length and value itself:
85                         let length: ser::BigSize = Readable::read($stream)?;
86                         let mut s = ser::FixedLengthReader::new($stream, length.0);
87                         match typ.0 {
88                                 $($reqtype => {
89                                         $reqfield = ser::Readable::read(&mut s)?;
90                                         if s.bytes_remain() {
91                                                 s.eat_remaining()?; // Return ShortRead if there's actually not enough bytes
92                                                 Err(DecodeError::InvalidValue)?
93                                         }
94                                 },)*
95                                 $($type => {
96                                         $field = Some(ser::Readable::read(&mut s)?);
97                                         if s.bytes_remain() {
98                                                 s.eat_remaining()?; // Return ShortRead if there's actually not enough bytes
99                                                 Err(DecodeError::InvalidValue)?
100                                         }
101                                 },)*
102                                 x if x % 2 == 0 => {
103                                         Err(DecodeError::UnknownRequiredFeature)?
104                                 },
105                                 _ => {},
106                         }
107                         s.eat_remaining()?;
108                 }
109                 // Make sure we got to each required type after we've read every TLV:
110                 $(if last_seen_type.is_none() || last_seen_type.unwrap() < $reqtype {
111                         Err(DecodeError::InvalidValue)?
112                 })*
113         } }
114 }
115
116 macro_rules! impl_writeable {
117         ($st:ident, $len: expr, {$($field:ident),*}) => {
118                 impl ::util::ser::Writeable for $st {
119                         fn write<W: ::util::ser::Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
120                                 if $len != 0 {
121                                         w.size_hint($len);
122                                 }
123                                 #[cfg(any(test, feature = "fuzztarget"))]
124                                 {
125                                         // In tests, assert that the hard-coded length matches the actual one
126                                         if $len != 0 {
127                                                 use util::ser::LengthCalculatingWriter;
128                                                 let mut len_calc = LengthCalculatingWriter(0);
129                                                 $( self.$field.write(&mut len_calc)?; )*
130                                                 assert_eq!(len_calc.0, $len);
131                                         }
132                                 }
133                                 $( self.$field.write(w)?; )*
134                                 Ok(())
135                         }
136                 }
137
138                 impl ::util::ser::Readable for $st {
139                         fn read<R: ::std::io::Read>(r: &mut R) -> Result<Self, ::ln::msgs::DecodeError> {
140                                 Ok(Self {
141                                         $($field: ::util::ser::Readable::read(r)?),*
142                                 })
143                         }
144                 }
145         }
146 }
147 macro_rules! impl_writeable_len_match {
148         ($struct: ident, $cmp: tt, {$({$match: pat, $length: expr}),*}, {$($field:ident),*}) => {
149                 impl Writeable for $struct {
150                         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
151                                 let len = match *self {
152                                         $($match => $length,)*
153                                 };
154                                 w.size_hint(len);
155                                 #[cfg(any(test, feature = "fuzztarget"))]
156                                 {
157                                         // In tests, assert that the hard-coded length matches the actual one
158                                         use util::ser::LengthCalculatingWriter;
159                                         let mut len_calc = LengthCalculatingWriter(0);
160                                         $( self.$field.write(&mut len_calc)?; )*
161                                         assert!(len_calc.0 $cmp len);
162                                 }
163                                 $( self.$field.write(w)?; )*
164                                 Ok(())
165                         }
166                 }
167
168                 impl ::util::ser::Readable for $struct {
169                         fn read<R: ::std::io::Read>(r: &mut R) -> Result<Self, DecodeError> {
170                                 Ok(Self {
171                                         $($field: Readable::read(r)?),*
172                                 })
173                         }
174                 }
175         };
176         ($struct: ident, {$({$match: pat, $length: expr}),*}, {$($field:ident),*}) => {
177                 impl_writeable_len_match!($struct, ==, { $({ $match, $length }),* }, { $($field),* });
178         }
179 }
180
181 #[cfg(test)]
182 mod tests {
183         use std::io::{Cursor, Read};
184         use ln::msgs::DecodeError;
185         use util::ser::{Readable, Writeable, HighZeroBytesDroppedVarInt, VecWriter};
186         use bitcoin::secp256k1::PublicKey;
187
188         // The BOLT TLV test cases don't include any tests which use our "required-value" logic since
189         // the encoding layer in the BOLTs has no such concept, though it makes our macros easier to
190         // work with so they're baked into the decoder. Thus, we have a few additional tests below
191         fn tlv_reader(s: &[u8]) -> Result<(u64, u32, Option<u32>), DecodeError> {
192                 let mut s = Cursor::new(s);
193                 let mut a: u64 = 0;
194                 let mut b: u32 = 0;
195                 let mut c: Option<u32> = None;
196                 decode_tlv!(&mut s, {(2, a), (3, b)}, {(4, c)});
197                 Ok((a, b, c))
198         }
199
200         #[test]
201         fn tlv_v_short_read() {
202                 // We only expect a u32 for type 3 (which we are given), but the L says its 8 bytes.
203                 if let Err(DecodeError::ShortRead) = tlv_reader(&::hex::decode(
204                                 concat!("0100", "0208deadbeef1badbeef", "0308deadbeef")
205                                 ).unwrap()[..]) {
206                 } else { panic!(); }
207         }
208
209         #[test]
210         fn tlv_types_out_of_order() {
211                 if let Err(DecodeError::InvalidValue) = tlv_reader(&::hex::decode(
212                                 concat!("0100", "0304deadbeef", "0208deadbeef1badbeef")
213                                 ).unwrap()[..]) {
214                 } else { panic!(); }
215                 // ...even if its some field we don't understand
216                 if let Err(DecodeError::InvalidValue) = tlv_reader(&::hex::decode(
217                                 concat!("0208deadbeef1badbeef", "0100", "0304deadbeef")
218                                 ).unwrap()[..]) {
219                 } else { panic!(); }
220         }
221
222         #[test]
223         fn tlv_req_type_missing_or_extra() {
224                 // It's also bad if they included even fields we don't understand
225                 if let Err(DecodeError::UnknownRequiredFeature) = tlv_reader(&::hex::decode(
226                                 concat!("0100", "0208deadbeef1badbeef", "0304deadbeef", "0600")
227                                 ).unwrap()[..]) {
228                 } else { panic!(); }
229                 // ... or if they're missing fields we need
230                 if let Err(DecodeError::InvalidValue) = tlv_reader(&::hex::decode(
231                                 concat!("0100", "0208deadbeef1badbeef")
232                                 ).unwrap()[..]) {
233                 } else { panic!(); }
234                 // ... even if that field is even
235                 if let Err(DecodeError::InvalidValue) = tlv_reader(&::hex::decode(
236                                 concat!("0304deadbeef", "0500")
237                                 ).unwrap()[..]) {
238                 } else { panic!(); }
239         }
240
241         #[test]
242         fn tlv_simple_good_cases() {
243                 assert_eq!(tlv_reader(&::hex::decode(
244                                 concat!("0208deadbeef1badbeef", "03041bad1dea")
245                                 ).unwrap()[..]).unwrap(),
246                         (0xdeadbeef1badbeef, 0x1bad1dea, None));
247                 assert_eq!(tlv_reader(&::hex::decode(
248                                 concat!("0208deadbeef1badbeef", "03041bad1dea", "040401020304")
249                                 ).unwrap()[..]).unwrap(),
250                         (0xdeadbeef1badbeef, 0x1bad1dea, Some(0x01020304)));
251         }
252
253         impl Readable for (PublicKey, u64, u64) {
254                 #[inline]
255                 fn read<R: Read>(reader: &mut R) -> Result<(PublicKey, u64, u64), DecodeError> {
256                         Ok((Readable::read(reader)?, Readable::read(reader)?, Readable::read(reader)?))
257                 }
258         }
259
260         // BOLT TLV test cases
261         fn tlv_reader_n1(s: &[u8]) -> Result<(Option<HighZeroBytesDroppedVarInt<u64>>, Option<u64>, Option<(PublicKey, u64, u64)>, Option<u16>), DecodeError> {
262                 let mut s = Cursor::new(s);
263                 let mut tlv1: Option<HighZeroBytesDroppedVarInt<u64>> = None;
264                 let mut tlv2: Option<u64> = None;
265                 let mut tlv3: Option<(PublicKey, u64, u64)> = None;
266                 let mut tlv4: Option<u16> = None;
267                 decode_tlv!(&mut s, {}, {(1, tlv1), (2, tlv2), (3, tlv3), (254, tlv4)});
268                 Ok((tlv1, tlv2, tlv3, tlv4))
269         }
270
271         #[test]
272         fn bolt_tlv_bogus_stream() {
273                 macro_rules! do_test {
274                         ($stream: expr, $reason: ident) => {
275                                 if let Err(DecodeError::$reason) = tlv_reader_n1(&::hex::decode($stream).unwrap()[..]) {
276                                 } else { panic!(); }
277                         }
278                 }
279
280                 // TLVs from the BOLT test cases which should not decode as either n1 or n2
281                 do_test!(concat!("fd01"), ShortRead);
282                 do_test!(concat!("fd0001", "00"), InvalidValue);
283                 do_test!(concat!("fd0101"), ShortRead);
284                 do_test!(concat!("0f", "fd"), ShortRead);
285                 do_test!(concat!("0f", "fd26"), ShortRead);
286                 do_test!(concat!("0f", "fd2602"), ShortRead);
287                 do_test!(concat!("0f", "fd0001", "00"), InvalidValue);
288                 do_test!(concat!("0f", "fd0201", "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), ShortRead);
289
290                 do_test!(concat!("12", "00"), UnknownRequiredFeature);
291                 do_test!(concat!("fd0102", "00"), UnknownRequiredFeature);
292                 do_test!(concat!("fe01000002", "00"), UnknownRequiredFeature);
293                 do_test!(concat!("ff0100000000000002", "00"), UnknownRequiredFeature);
294         }
295
296         #[test]
297         fn bolt_tlv_bogus_n1_stream() {
298                 macro_rules! do_test {
299                         ($stream: expr, $reason: ident) => {
300                                 if let Err(DecodeError::$reason) = tlv_reader_n1(&::hex::decode($stream).unwrap()[..]) {
301                                 } else { panic!(); }
302                         }
303                 }
304
305                 // TLVs from the BOLT test cases which should not decode as n1
306                 do_test!(concat!("01", "09", "ffffffffffffffffff"), InvalidValue);
307                 do_test!(concat!("01", "01", "00"), InvalidValue);
308                 do_test!(concat!("01", "02", "0001"), InvalidValue);
309                 do_test!(concat!("01", "03", "000100"), InvalidValue);
310                 do_test!(concat!("01", "04", "00010000"), InvalidValue);
311                 do_test!(concat!("01", "05", "0001000000"), InvalidValue);
312                 do_test!(concat!("01", "06", "000100000000"), InvalidValue);
313                 do_test!(concat!("01", "07", "00010000000000"), InvalidValue);
314                 do_test!(concat!("01", "08", "0001000000000000"), InvalidValue);
315                 do_test!(concat!("02", "07", "01010101010101"), ShortRead);
316                 do_test!(concat!("02", "09", "010101010101010101"), InvalidValue);
317                 do_test!(concat!("03", "21", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb"), ShortRead);
318                 do_test!(concat!("03", "29", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb0000000000000001"), ShortRead);
319                 do_test!(concat!("03", "30", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb000000000000000100000000000001"), ShortRead);
320                 do_test!(concat!("03", "31", "043da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb00000000000000010000000000000002"), InvalidValue);
321                 do_test!(concat!("03", "32", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb0000000000000001000000000000000001"), InvalidValue);
322                 do_test!(concat!("fd00fe", "00"), ShortRead);
323                 do_test!(concat!("fd00fe", "01", "01"), ShortRead);
324                 do_test!(concat!("fd00fe", "03", "010101"), InvalidValue);
325                 do_test!(concat!("00", "00"), UnknownRequiredFeature);
326
327                 do_test!(concat!("02", "08", "0000000000000226", "01", "01", "2a"), InvalidValue);
328                 do_test!(concat!("02", "08", "0000000000000231", "02", "08", "0000000000000451"), InvalidValue);
329                 do_test!(concat!("1f", "00", "0f", "01", "2a"), InvalidValue);
330                 do_test!(concat!("1f", "00", "1f", "01", "2a"), InvalidValue);
331
332                 // The last BOLT test modified to not require creating a new decoder for one trivial test.
333                 do_test!(concat!("ffffffffffffffffff", "00", "01", "00"), InvalidValue);
334         }
335
336         #[test]
337         fn bolt_tlv_valid_n1_stream() {
338                 macro_rules! do_test {
339                         ($stream: expr, $tlv1: expr, $tlv2: expr, $tlv3: expr, $tlv4: expr) => {
340                                 if let Ok((tlv1, tlv2, tlv3, tlv4)) = tlv_reader_n1(&::hex::decode($stream).unwrap()[..]) {
341                                         assert_eq!(tlv1.map(|v| v.0), $tlv1);
342                                         assert_eq!(tlv2, $tlv2);
343                                         assert_eq!(tlv3, $tlv3);
344                                         assert_eq!(tlv4, $tlv4);
345                                 } else { panic!(); }
346                         }
347                 }
348
349                 do_test!(concat!(""), None, None, None, None);
350                 do_test!(concat!("21", "00"), None, None, None, None);
351                 do_test!(concat!("fd0201", "00"), None, None, None, None);
352                 do_test!(concat!("fd00fd", "00"), None, None, None, None);
353                 do_test!(concat!("fd00ff", "00"), None, None, None, None);
354                 do_test!(concat!("fe02000001", "00"), None, None, None, None);
355                 do_test!(concat!("ff0200000000000001", "00"), None, None, None, None);
356
357                 do_test!(concat!("01", "00"), Some(0), None, None, None);
358                 do_test!(concat!("01", "01", "01"), Some(1), None, None, None);
359                 do_test!(concat!("01", "02", "0100"), Some(256), None, None, None);
360                 do_test!(concat!("01", "03", "010000"), Some(65536), None, None, None);
361                 do_test!(concat!("01", "04", "01000000"), Some(16777216), None, None, None);
362                 do_test!(concat!("01", "05", "0100000000"), Some(4294967296), None, None, None);
363                 do_test!(concat!("01", "06", "010000000000"), Some(1099511627776), None, None, None);
364                 do_test!(concat!("01", "07", "01000000000000"), Some(281474976710656), None, None, None);
365                 do_test!(concat!("01", "08", "0100000000000000"), Some(72057594037927936), None, None, None);
366                 do_test!(concat!("02", "08", "0000000000000226"), None, Some((0 << 30) | (0 << 5) | (550 << 0)), None, None);
367                 do_test!(concat!("03", "31", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb00000000000000010000000000000002"),
368                         None, None, Some((
369                                 PublicKey::from_slice(&::hex::decode("023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb").unwrap()[..]).unwrap(), 1, 2)),
370                         None);
371                 do_test!(concat!("fd00fe", "02", "0226"), None, None, None, Some(550));
372         }
373
374         fn do_simple_test_tlv_write() -> Result<(), ::std::io::Error> {
375                 let mut stream = VecWriter(Vec::new());
376
377                 stream.0.clear();
378                 encode_varint_length_prefixed_tlv!(&mut stream, { (1, 1u8) });
379                 assert_eq!(stream.0, ::hex::decode("03010101").unwrap());
380
381                 stream.0.clear();
382                 encode_varint_length_prefixed_tlv!(&mut stream, { (4, 0xabcdu16) });
383                 assert_eq!(stream.0, ::hex::decode("040402abcd").unwrap());
384
385                 stream.0.clear();
386                 encode_varint_length_prefixed_tlv!(&mut stream, { (0xff, 0xabcdu16) });
387                 assert_eq!(stream.0, ::hex::decode("06fd00ff02abcd").unwrap());
388
389                 stream.0.clear();
390                 encode_varint_length_prefixed_tlv!(&mut stream, { (0, 1u64), (0xff, HighZeroBytesDroppedVarInt(0u64)) });
391                 assert_eq!(stream.0, ::hex::decode("0e00080000000000000001fd00ff00").unwrap());
392
393                 Ok(())
394         }
395
396         #[test]
397         fn simple_test_tlv_write() {
398                 do_simple_test_tlv_write().unwrap();
399         }
400 }