Support serializing TLV fields which may or may not be present
[rust-lightning] / lightning / src / util / ser_macros.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 macro_rules! encode_tlv {
11         ($stream: expr, {$(($type: expr, $field: expr)),*}, {$(($optional_type: expr, $optional_field: expr)),*}) => { {
12                 #[allow(unused_imports)]
13                 use util::ser::{BigSize, LengthCalculatingWriter};
14                 // Fields must be serialized in order, so we have to potentially switch between optional
15                 // fields and normal fields while serializing. Thus, we end up having to loop over the type
16                 // counts.
17                 // Sadly, while LLVM does appear smart enough to make `max_field` a constant, it appears to
18                 // refuse to unroll the loop. If we have enough entries that this is slow we can revisit
19                 // this design in the future.
20                 #[allow(unused_mut)]
21                 let mut max_field: u64 = 0;
22                 $(
23                         if $type >= max_field { max_field = $type + 1; }
24                 )*
25                 $(
26                         if $optional_type >= max_field { max_field = $optional_type + 1; }
27                 )*
28                 #[allow(unused_variables)]
29                 for i in 0..max_field {
30                         $(
31                                 if i == $type {
32                                         BigSize($type).write($stream)?;
33                                         let mut len_calc = LengthCalculatingWriter(0);
34                                         $field.write(&mut len_calc)?;
35                                         BigSize(len_calc.0 as u64).write($stream)?;
36                                         $field.write($stream)?;
37                                 }
38                         )*
39                         $(
40                                 if i == $optional_type {
41                                         if let Some(ref field) = $optional_field {
42                                                 BigSize($optional_type).write($stream)?;
43                                                 let mut len_calc = LengthCalculatingWriter(0);
44                                                 field.write(&mut len_calc)?;
45                                                 BigSize(len_calc.0 as u64).write($stream)?;
46                                                 field.write($stream)?;
47                                         }
48                                 }
49                         )*
50                 }
51         } }
52 }
53
54 macro_rules! encode_varint_length_prefixed_tlv {
55         ($stream: expr, {$(($type: expr, $field: expr)),*}, {$(($optional_type: expr, $optional_field: expr)),*}) => { {
56                 use util::ser::{BigSize, LengthCalculatingWriter};
57                 #[allow(unused_mut)]
58                 let mut len = LengthCalculatingWriter(0);
59                 {
60                         $(
61                                 BigSize($type).write(&mut len)?;
62                                 let mut field_len = LengthCalculatingWriter(0);
63                                 $field.write(&mut field_len)?;
64                                 BigSize(field_len.0 as u64).write(&mut len)?;
65                                 len.0 += field_len.0;
66                         )*
67                         $(
68                                 if let Some(ref field) = $optional_field {
69                                         BigSize($optional_type).write(&mut len)?;
70                                         let mut field_len = LengthCalculatingWriter(0);
71                                         field.write(&mut field_len)?;
72                                         BigSize(field_len.0 as u64).write(&mut len)?;
73                                         len.0 += field_len.0;
74                                 }
75                         )*
76                 }
77
78                 BigSize(len.0 as u64).write($stream)?;
79                 encode_tlv!($stream, { $(($type, $field)),* }, { $(($optional_type, $optional_field)),* });
80         } }
81 }
82
83 macro_rules! decode_tlv {
84         ($stream: expr, {$(($reqtype: expr, $reqfield: ident)),*}, {$(($type: expr, $field: ident)),*}) => { {
85                 use ln::msgs::DecodeError;
86                 let mut last_seen_type: Option<u64> = None;
87                 'tlv_read: loop {
88                         use util::ser;
89
90                         // First decode the type of this TLV:
91                         let typ: ser::BigSize = {
92                                 // We track whether any bytes were read during the consensus_decode call to
93                                 // determine whether we should break or return ShortRead if we get an
94                                 // UnexpectedEof. This should in every case be largely cosmetic, but its nice to
95                                 // pass the TLV test vectors exactly, which requre this distinction.
96                                 let mut tracking_reader = ser::ReadTrackingReader::new($stream);
97                                 match ser::Readable::read(&mut tracking_reader) {
98                                         Err(DecodeError::ShortRead) => {
99                                                 if !tracking_reader.have_read {
100                                                         break 'tlv_read
101                                                 } else {
102                                                         Err(DecodeError::ShortRead)?
103                                                 }
104                                         },
105                                         Err(e) => Err(e)?,
106                                         Ok(t) => t,
107                                 }
108                         };
109
110                         // Types must be unique and monotonically increasing:
111                         match last_seen_type {
112                                 Some(t) if typ.0 <= t => {
113                                         Err(DecodeError::InvalidValue)?
114                                 },
115                                 _ => {},
116                         }
117                         // As we read types, make sure we hit every required type:
118                         $(if (last_seen_type.is_none() || last_seen_type.unwrap() < $reqtype) && typ.0 > $reqtype {
119                                 Err(DecodeError::InvalidValue)?
120                         })*
121                         last_seen_type = Some(typ.0);
122
123                         // Finally, read the length and value itself:
124                         let length: ser::BigSize = Readable::read($stream)?;
125                         let mut s = ser::FixedLengthReader::new($stream, length.0);
126                         match typ.0 {
127                                 $($reqtype => {
128                                         $reqfield = ser::Readable::read(&mut s)?;
129                                         if s.bytes_remain() {
130                                                 s.eat_remaining()?; // Return ShortRead if there's actually not enough bytes
131                                                 Err(DecodeError::InvalidValue)?
132                                         }
133                                 },)*
134                                 $($type => {
135                                         $field = Some(ser::Readable::read(&mut s)?);
136                                         if s.bytes_remain() {
137                                                 s.eat_remaining()?; // Return ShortRead if there's actually not enough bytes
138                                                 Err(DecodeError::InvalidValue)?
139                                         }
140                                 },)*
141                                 x if x % 2 == 0 => {
142                                         Err(DecodeError::UnknownRequiredFeature)?
143                                 },
144                                 _ => {},
145                         }
146                         s.eat_remaining()?;
147                 }
148                 // Make sure we got to each required type after we've read every TLV:
149                 $(if last_seen_type.is_none() || last_seen_type.unwrap() < $reqtype {
150                         Err(DecodeError::InvalidValue)?
151                 })*
152         } }
153 }
154
155 macro_rules! impl_writeable {
156         ($st:ident, $len: expr, {$($field:ident),*}) => {
157                 impl ::util::ser::Writeable for $st {
158                         fn write<W: ::util::ser::Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
159                                 if $len != 0 {
160                                         w.size_hint($len);
161                                 }
162                                 #[cfg(any(test, feature = "fuzztarget"))]
163                                 {
164                                         // In tests, assert that the hard-coded length matches the actual one
165                                         if $len != 0 {
166                                                 use util::ser::LengthCalculatingWriter;
167                                                 let mut len_calc = LengthCalculatingWriter(0);
168                                                 $( self.$field.write(&mut len_calc)?; )*
169                                                 assert_eq!(len_calc.0, $len);
170                                         }
171                                 }
172                                 $( self.$field.write(w)?; )*
173                                 Ok(())
174                         }
175                 }
176
177                 impl ::util::ser::Readable for $st {
178                         fn read<R: ::std::io::Read>(r: &mut R) -> Result<Self, ::ln::msgs::DecodeError> {
179                                 Ok(Self {
180                                         $($field: ::util::ser::Readable::read(r)?),*
181                                 })
182                         }
183                 }
184         }
185 }
186 macro_rules! impl_writeable_len_match {
187         ($struct: ident, $cmp: tt, {$({$match: pat, $length: expr}),*}, {$($field:ident),*}) => {
188                 impl Writeable for $struct {
189                         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
190                                 let len = match *self {
191                                         $($match => $length,)*
192                                 };
193                                 w.size_hint(len);
194                                 #[cfg(any(test, feature = "fuzztarget"))]
195                                 {
196                                         // In tests, assert that the hard-coded length matches the actual one
197                                         use util::ser::LengthCalculatingWriter;
198                                         let mut len_calc = LengthCalculatingWriter(0);
199                                         $( self.$field.write(&mut len_calc)?; )*
200                                         assert!(len_calc.0 $cmp len);
201                                 }
202                                 $( self.$field.write(w)?; )*
203                                 Ok(())
204                         }
205                 }
206
207                 impl ::util::ser::Readable for $struct {
208                         fn read<R: ::std::io::Read>(r: &mut R) -> Result<Self, DecodeError> {
209                                 Ok(Self {
210                                         $($field: Readable::read(r)?),*
211                                 })
212                         }
213                 }
214         };
215         ($struct: ident, {$({$match: pat, $length: expr}),*}, {$($field:ident),*}) => {
216                 impl_writeable_len_match!($struct, ==, { $({ $match, $length }),* }, { $($field),* });
217         }
218 }
219
220 /// Write out two bytes to indicate the version of an object.
221 /// $this_version represents a unique version of a type. Incremented whenever the type's
222 ///               serialization format has changed or has a new interpretation. Used by a type's
223 ///               reader to determine how to interpret fields or if it can understand a serialized
224 ///               object.
225 /// $min_version_that_can_read_this is the minimum reader version which can understand this
226 ///                                 serialized object. Previous versions will simply err with a
227 ///                                 DecodeError::UnknownVersion.
228 ///
229 /// Updates to either $this_version or $min_version_that_can_read_this should be included in
230 /// release notes.
231 ///
232 /// Both version fields can be specific to this type of object.
233 macro_rules! write_ver_prefix {
234         ($stream: expr, $this_version: expr, $min_version_that_can_read_this: expr) => {
235                 $stream.write_all(&[$this_version; 1])?;
236                 $stream.write_all(&[$min_version_that_can_read_this; 1])?;
237         }
238 }
239
240 /// Writes out a suffix to an object which contains potentially backwards-compatible, optional
241 /// fields which old nodes can happily ignore.
242 ///
243 /// It is written out in TLV format and, as with all TLV fields, unknown even fields cause a
244 /// DecodeError::UnknownRequiredFeature error, with unknown odd fields ignored.
245 ///
246 /// This is the preferred method of adding new fields that old nodes can ignore and still function
247 /// correctly.
248 macro_rules! write_tlv_fields {
249         ($stream: expr, {$(($type: expr, $field: expr)),*}, {$(($optional_type: expr, $optional_field: expr)),*}) => {
250                 encode_varint_length_prefixed_tlv!($stream, {$(($type, $field)),*} , {$(($optional_type, $optional_field)),*});
251         }
252 }
253
254 /// Reads a prefix added by write_ver_prefix!(), above. Takes the current version of the
255 /// serialization logic for this object. This is compared against the
256 /// $min_version_that_can_read_this added by write_ver_prefix!().
257 macro_rules! read_ver_prefix {
258         ($stream: expr, $this_version: expr) => { {
259                 let ver: u8 = Readable::read($stream)?;
260                 let min_ver: u8 = Readable::read($stream)?;
261                 if min_ver > $this_version {
262                         return Err(DecodeError::UnknownVersion);
263                 }
264                 ver
265         } }
266 }
267
268 /// Reads a suffix added by write_tlv_fields.
269 macro_rules! read_tlv_fields {
270         ($stream: expr, {$(($reqtype: expr, $reqfield: ident)),*}, {$(($type: expr, $field: ident)),*}) => { {
271                 let tlv_len = ::util::ser::BigSize::read($stream)?;
272                 let mut rd = ::util::ser::FixedLengthReader::new($stream, tlv_len.0);
273                 decode_tlv!(&mut rd, {$(($reqtype, $reqfield)),*}, {$(($type, $field)),*});
274                 rd.eat_remaining().map_err(|_| DecodeError::ShortRead)?;
275         } }
276 }
277
278 #[cfg(test)]
279 mod tests {
280         use std::io::{Cursor, Read};
281         use ln::msgs::DecodeError;
282         use util::ser::{Readable, Writeable, HighZeroBytesDroppedVarInt, VecWriter};
283         use bitcoin::secp256k1::PublicKey;
284
285         // The BOLT TLV test cases don't include any tests which use our "required-value" logic since
286         // the encoding layer in the BOLTs has no such concept, though it makes our macros easier to
287         // work with so they're baked into the decoder. Thus, we have a few additional tests below
288         fn tlv_reader(s: &[u8]) -> Result<(u64, u32, Option<u32>), DecodeError> {
289                 let mut s = Cursor::new(s);
290                 let mut a: u64 = 0;
291                 let mut b: u32 = 0;
292                 let mut c: Option<u32> = None;
293                 decode_tlv!(&mut s, {(2, a), (3, b)}, {(4, c)});
294                 Ok((a, b, c))
295         }
296
297         #[test]
298         fn tlv_v_short_read() {
299                 // We only expect a u32 for type 3 (which we are given), but the L says its 8 bytes.
300                 if let Err(DecodeError::ShortRead) = tlv_reader(&::hex::decode(
301                                 concat!("0100", "0208deadbeef1badbeef", "0308deadbeef")
302                                 ).unwrap()[..]) {
303                 } else { panic!(); }
304         }
305
306         #[test]
307         fn tlv_types_out_of_order() {
308                 if let Err(DecodeError::InvalidValue) = tlv_reader(&::hex::decode(
309                                 concat!("0100", "0304deadbeef", "0208deadbeef1badbeef")
310                                 ).unwrap()[..]) {
311                 } else { panic!(); }
312                 // ...even if its some field we don't understand
313                 if let Err(DecodeError::InvalidValue) = tlv_reader(&::hex::decode(
314                                 concat!("0208deadbeef1badbeef", "0100", "0304deadbeef")
315                                 ).unwrap()[..]) {
316                 } else { panic!(); }
317         }
318
319         #[test]
320         fn tlv_req_type_missing_or_extra() {
321                 // It's also bad if they included even fields we don't understand
322                 if let Err(DecodeError::UnknownRequiredFeature) = tlv_reader(&::hex::decode(
323                                 concat!("0100", "0208deadbeef1badbeef", "0304deadbeef", "0600")
324                                 ).unwrap()[..]) {
325                 } else { panic!(); }
326                 // ... or if they're missing fields we need
327                 if let Err(DecodeError::InvalidValue) = tlv_reader(&::hex::decode(
328                                 concat!("0100", "0208deadbeef1badbeef")
329                                 ).unwrap()[..]) {
330                 } else { panic!(); }
331                 // ... even if that field is even
332                 if let Err(DecodeError::InvalidValue) = tlv_reader(&::hex::decode(
333                                 concat!("0304deadbeef", "0500")
334                                 ).unwrap()[..]) {
335                 } else { panic!(); }
336         }
337
338         #[test]
339         fn tlv_simple_good_cases() {
340                 assert_eq!(tlv_reader(&::hex::decode(
341                                 concat!("0208deadbeef1badbeef", "03041bad1dea")
342                                 ).unwrap()[..]).unwrap(),
343                         (0xdeadbeef1badbeef, 0x1bad1dea, None));
344                 assert_eq!(tlv_reader(&::hex::decode(
345                                 concat!("0208deadbeef1badbeef", "03041bad1dea", "040401020304")
346                                 ).unwrap()[..]).unwrap(),
347                         (0xdeadbeef1badbeef, 0x1bad1dea, Some(0x01020304)));
348         }
349
350         impl Readable for (PublicKey, u64, u64) {
351                 #[inline]
352                 fn read<R: Read>(reader: &mut R) -> Result<(PublicKey, u64, u64), DecodeError> {
353                         Ok((Readable::read(reader)?, Readable::read(reader)?, Readable::read(reader)?))
354                 }
355         }
356
357         // BOLT TLV test cases
358         fn tlv_reader_n1(s: &[u8]) -> Result<(Option<HighZeroBytesDroppedVarInt<u64>>, Option<u64>, Option<(PublicKey, u64, u64)>, Option<u16>), DecodeError> {
359                 let mut s = Cursor::new(s);
360                 let mut tlv1: Option<HighZeroBytesDroppedVarInt<u64>> = None;
361                 let mut tlv2: Option<u64> = None;
362                 let mut tlv3: Option<(PublicKey, u64, u64)> = None;
363                 let mut tlv4: Option<u16> = None;
364                 decode_tlv!(&mut s, {}, {(1, tlv1), (2, tlv2), (3, tlv3), (254, tlv4)});
365                 Ok((tlv1, tlv2, tlv3, tlv4))
366         }
367
368         #[test]
369         fn bolt_tlv_bogus_stream() {
370                 macro_rules! do_test {
371                         ($stream: expr, $reason: ident) => {
372                                 if let Err(DecodeError::$reason) = tlv_reader_n1(&::hex::decode($stream).unwrap()[..]) {
373                                 } else { panic!(); }
374                         }
375                 }
376
377                 // TLVs from the BOLT test cases which should not decode as either n1 or n2
378                 do_test!(concat!("fd01"), ShortRead);
379                 do_test!(concat!("fd0001", "00"), InvalidValue);
380                 do_test!(concat!("fd0101"), ShortRead);
381                 do_test!(concat!("0f", "fd"), ShortRead);
382                 do_test!(concat!("0f", "fd26"), ShortRead);
383                 do_test!(concat!("0f", "fd2602"), ShortRead);
384                 do_test!(concat!("0f", "fd0001", "00"), InvalidValue);
385                 do_test!(concat!("0f", "fd0201", "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), ShortRead);
386
387                 do_test!(concat!("12", "00"), UnknownRequiredFeature);
388                 do_test!(concat!("fd0102", "00"), UnknownRequiredFeature);
389                 do_test!(concat!("fe01000002", "00"), UnknownRequiredFeature);
390                 do_test!(concat!("ff0100000000000002", "00"), UnknownRequiredFeature);
391         }
392
393         #[test]
394         fn bolt_tlv_bogus_n1_stream() {
395                 macro_rules! do_test {
396                         ($stream: expr, $reason: ident) => {
397                                 if let Err(DecodeError::$reason) = tlv_reader_n1(&::hex::decode($stream).unwrap()[..]) {
398                                 } else { panic!(); }
399                         }
400                 }
401
402                 // TLVs from the BOLT test cases which should not decode as n1
403                 do_test!(concat!("01", "09", "ffffffffffffffffff"), InvalidValue);
404                 do_test!(concat!("01", "01", "00"), InvalidValue);
405                 do_test!(concat!("01", "02", "0001"), InvalidValue);
406                 do_test!(concat!("01", "03", "000100"), InvalidValue);
407                 do_test!(concat!("01", "04", "00010000"), InvalidValue);
408                 do_test!(concat!("01", "05", "0001000000"), InvalidValue);
409                 do_test!(concat!("01", "06", "000100000000"), InvalidValue);
410                 do_test!(concat!("01", "07", "00010000000000"), InvalidValue);
411                 do_test!(concat!("01", "08", "0001000000000000"), InvalidValue);
412                 do_test!(concat!("02", "07", "01010101010101"), ShortRead);
413                 do_test!(concat!("02", "09", "010101010101010101"), InvalidValue);
414                 do_test!(concat!("03", "21", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb"), ShortRead);
415                 do_test!(concat!("03", "29", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb0000000000000001"), ShortRead);
416                 do_test!(concat!("03", "30", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb000000000000000100000000000001"), ShortRead);
417                 do_test!(concat!("03", "31", "043da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb00000000000000010000000000000002"), InvalidValue);
418                 do_test!(concat!("03", "32", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb0000000000000001000000000000000001"), InvalidValue);
419                 do_test!(concat!("fd00fe", "00"), ShortRead);
420                 do_test!(concat!("fd00fe", "01", "01"), ShortRead);
421                 do_test!(concat!("fd00fe", "03", "010101"), InvalidValue);
422                 do_test!(concat!("00", "00"), UnknownRequiredFeature);
423
424                 do_test!(concat!("02", "08", "0000000000000226", "01", "01", "2a"), InvalidValue);
425                 do_test!(concat!("02", "08", "0000000000000231", "02", "08", "0000000000000451"), InvalidValue);
426                 do_test!(concat!("1f", "00", "0f", "01", "2a"), InvalidValue);
427                 do_test!(concat!("1f", "00", "1f", "01", "2a"), InvalidValue);
428
429                 // The last BOLT test modified to not require creating a new decoder for one trivial test.
430                 do_test!(concat!("ffffffffffffffffff", "00", "01", "00"), InvalidValue);
431         }
432
433         #[test]
434         fn bolt_tlv_valid_n1_stream() {
435                 macro_rules! do_test {
436                         ($stream: expr, $tlv1: expr, $tlv2: expr, $tlv3: expr, $tlv4: expr) => {
437                                 if let Ok((tlv1, tlv2, tlv3, tlv4)) = tlv_reader_n1(&::hex::decode($stream).unwrap()[..]) {
438                                         assert_eq!(tlv1.map(|v| v.0), $tlv1);
439                                         assert_eq!(tlv2, $tlv2);
440                                         assert_eq!(tlv3, $tlv3);
441                                         assert_eq!(tlv4, $tlv4);
442                                 } else { panic!(); }
443                         }
444                 }
445
446                 do_test!(concat!(""), None, None, None, None);
447                 do_test!(concat!("21", "00"), None, None, None, None);
448                 do_test!(concat!("fd0201", "00"), None, None, None, None);
449                 do_test!(concat!("fd00fd", "00"), None, None, None, None);
450                 do_test!(concat!("fd00ff", "00"), None, None, None, None);
451                 do_test!(concat!("fe02000001", "00"), None, None, None, None);
452                 do_test!(concat!("ff0200000000000001", "00"), None, None, None, None);
453
454                 do_test!(concat!("01", "00"), Some(0), None, None, None);
455                 do_test!(concat!("01", "01", "01"), Some(1), None, None, None);
456                 do_test!(concat!("01", "02", "0100"), Some(256), None, None, None);
457                 do_test!(concat!("01", "03", "010000"), Some(65536), None, None, None);
458                 do_test!(concat!("01", "04", "01000000"), Some(16777216), None, None, None);
459                 do_test!(concat!("01", "05", "0100000000"), Some(4294967296), None, None, None);
460                 do_test!(concat!("01", "06", "010000000000"), Some(1099511627776), None, None, None);
461                 do_test!(concat!("01", "07", "01000000000000"), Some(281474976710656), None, None, None);
462                 do_test!(concat!("01", "08", "0100000000000000"), Some(72057594037927936), None, None, None);
463                 do_test!(concat!("02", "08", "0000000000000226"), None, Some((0 << 30) | (0 << 5) | (550 << 0)), None, None);
464                 do_test!(concat!("03", "31", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb00000000000000010000000000000002"),
465                         None, None, Some((
466                                 PublicKey::from_slice(&::hex::decode("023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb").unwrap()[..]).unwrap(), 1, 2)),
467                         None);
468                 do_test!(concat!("fd00fe", "02", "0226"), None, None, None, Some(550));
469         }
470
471         fn do_simple_test_tlv_write() -> Result<(), ::std::io::Error> {
472                 let mut stream = VecWriter(Vec::new());
473
474                 stream.0.clear();
475                 encode_varint_length_prefixed_tlv!(&mut stream, { (1, 1u8) }, { (42, None::<u64>) });
476                 assert_eq!(stream.0, ::hex::decode("03010101").unwrap());
477
478                 stream.0.clear();
479                 encode_varint_length_prefixed_tlv!(&mut stream, { }, { (1, Some(1u8)) });
480                 assert_eq!(stream.0, ::hex::decode("03010101").unwrap());
481
482                 stream.0.clear();
483                 encode_varint_length_prefixed_tlv!(&mut stream, { (4, 0xabcdu16) }, { (42, None::<u64>) });
484                 assert_eq!(stream.0, ::hex::decode("040402abcd").unwrap());
485
486                 stream.0.clear();
487                 encode_varint_length_prefixed_tlv!(&mut stream, { (0xff, 0xabcdu16) }, { (42, None::<u64>) });
488                 assert_eq!(stream.0, ::hex::decode("06fd00ff02abcd").unwrap());
489
490                 stream.0.clear();
491                 encode_varint_length_prefixed_tlv!(&mut stream, { (0, 1u64), (0xff, HighZeroBytesDroppedVarInt(0u64)) }, { (42, None::<u64>) });
492                 assert_eq!(stream.0, ::hex::decode("0e00080000000000000001fd00ff00").unwrap());
493
494                 stream.0.clear();
495                 encode_varint_length_prefixed_tlv!(&mut stream, { (0xff, HighZeroBytesDroppedVarInt(0u64)) }, { (0, Some(1u64)) });
496                 assert_eq!(stream.0, ::hex::decode("0e00080000000000000001fd00ff00").unwrap());
497
498                 Ok(())
499         }
500
501         #[test]
502         fn simple_test_tlv_write() {
503                 do_simple_test_tlv_write().unwrap();
504         }
505 }