1 // This file is Copyright its original authors, visible in version control
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
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
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.
21 let mut max_field: u64 = 0;
23 if $type >= max_field { max_field = $type + 1; }
26 if $optional_type >= max_field { max_field = $optional_type + 1; }
28 #[allow(unused_variables)]
29 for i in 0..max_field {
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)?;
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)?;
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};
58 let mut len = LengthCalculatingWriter(0);
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)?;
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)?;
78 BigSize(len.0 as u64).write($stream)?;
79 encode_tlv!($stream, { $(($type, $field)),* }, { $(($optional_type, $optional_field)),* });
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;
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 {
102 Err(DecodeError::ShortRead)?
110 // Types must be unique and monotonically increasing:
111 match last_seen_type {
112 Some(t) if typ.0 <= t => {
113 Err(DecodeError::InvalidValue)?
117 // As we read types, make sure we hit every required type:
119 #[allow(unused_comparisons)] // Note that $reqtype may be 0 making the second comparison always true
120 let invalid_order = (last_seen_type.is_none() || last_seen_type.unwrap() < $reqtype) && typ.0 > $reqtype;
122 Err(DecodeError::InvalidValue)?
125 last_seen_type = Some(typ.0);
127 // Finally, read the length and value itself:
128 let length: ser::BigSize = Readable::read($stream)?;
129 let mut s = ser::FixedLengthReader::new($stream, length.0);
132 $reqfield = ser::Readable::read(&mut s)?;
133 if s.bytes_remain() {
134 s.eat_remaining()?; // Return ShortRead if there's actually not enough bytes
135 Err(DecodeError::InvalidValue)?
139 $field = Some(ser::Readable::read(&mut s)?);
140 if s.bytes_remain() {
141 s.eat_remaining()?; // Return ShortRead if there's actually not enough bytes
142 Err(DecodeError::InvalidValue)?
146 Err(DecodeError::UnknownRequiredFeature)?
152 // Make sure we got to each required type after we've read every TLV:
154 #[allow(unused_comparisons)] // Note that $reqtype may be 0 making the second comparison always true
155 let missing_req_type = last_seen_type.is_none() || last_seen_type.unwrap() < $reqtype;
156 if missing_req_type {
157 Err(DecodeError::InvalidValue)?
163 macro_rules! impl_writeable {
164 ($st:ident, $len: expr, {$($field:ident),*}) => {
165 impl ::util::ser::Writeable for $st {
166 fn write<W: ::util::ser::Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
170 #[cfg(any(test, feature = "fuzztarget"))]
172 // In tests, assert that the hard-coded length matches the actual one
174 use util::ser::LengthCalculatingWriter;
175 let mut len_calc = LengthCalculatingWriter(0);
176 $( self.$field.write(&mut len_calc)?; )*
177 assert_eq!(len_calc.0, $len);
180 $( self.$field.write(w)?; )*
185 impl ::util::ser::Readable for $st {
186 fn read<R: ::std::io::Read>(r: &mut R) -> Result<Self, ::ln::msgs::DecodeError> {
188 $($field: ::util::ser::Readable::read(r)?),*
194 macro_rules! impl_writeable_len_match {
195 ($struct: ident, $cmp: tt, {$({$match: pat, $length: expr}),*}, {$($field:ident),*}) => {
196 impl Writeable for $struct {
197 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
198 let len = match *self {
199 $($match => $length,)*
202 #[cfg(any(test, feature = "fuzztarget"))]
204 // In tests, assert that the hard-coded length matches the actual one
205 use util::ser::LengthCalculatingWriter;
206 let mut len_calc = LengthCalculatingWriter(0);
207 $( self.$field.write(&mut len_calc)?; )*
208 assert!(len_calc.0 $cmp len);
210 $( self.$field.write(w)?; )*
215 impl ::util::ser::Readable for $struct {
216 fn read<R: ::std::io::Read>(r: &mut R) -> Result<Self, DecodeError> {
218 $($field: Readable::read(r)?),*
223 ($struct: ident, {$({$match: pat, $length: expr}),*}, {$($field:ident),*}) => {
224 impl_writeable_len_match!($struct, ==, { $({ $match, $length }),* }, { $($field),* });
228 /// Write out two bytes to indicate the version of an object.
229 /// $this_version represents a unique version of a type. Incremented whenever the type's
230 /// serialization format has changed or has a new interpretation. Used by a type's
231 /// reader to determine how to interpret fields or if it can understand a serialized
233 /// $min_version_that_can_read_this is the minimum reader version which can understand this
234 /// serialized object. Previous versions will simply err with a
235 /// DecodeError::UnknownVersion.
237 /// Updates to either $this_version or $min_version_that_can_read_this should be included in
240 /// Both version fields can be specific to this type of object.
241 macro_rules! write_ver_prefix {
242 ($stream: expr, $this_version: expr, $min_version_that_can_read_this: expr) => {
243 $stream.write_all(&[$this_version; 1])?;
244 $stream.write_all(&[$min_version_that_can_read_this; 1])?;
248 /// Writes out a suffix to an object which contains potentially backwards-compatible, optional
249 /// fields which old nodes can happily ignore.
251 /// It is written out in TLV format and, as with all TLV fields, unknown even fields cause a
252 /// DecodeError::UnknownRequiredFeature error, with unknown odd fields ignored.
254 /// This is the preferred method of adding new fields that old nodes can ignore and still function
256 macro_rules! write_tlv_fields {
257 ($stream: expr, {$(($type: expr, $field: expr)),*}, {$(($optional_type: expr, $optional_field: expr)),*}) => {
258 encode_varint_length_prefixed_tlv!($stream, {$(($type, $field)),*} , {$(($optional_type, $optional_field)),*});
262 /// Reads a prefix added by write_ver_prefix!(), above. Takes the current version of the
263 /// serialization logic for this object. This is compared against the
264 /// $min_version_that_can_read_this added by write_ver_prefix!().
265 macro_rules! read_ver_prefix {
266 ($stream: expr, $this_version: expr) => { {
267 let ver: u8 = Readable::read($stream)?;
268 let min_ver: u8 = Readable::read($stream)?;
269 if min_ver > $this_version {
270 return Err(DecodeError::UnknownVersion);
276 /// Reads a suffix added by write_tlv_fields.
277 macro_rules! read_tlv_fields {
278 ($stream: expr, {$(($reqtype: expr, $reqfield: ident)),*}, {$(($type: expr, $field: ident)),*}) => { {
279 let tlv_len = ::util::ser::BigSize::read($stream)?;
280 let mut rd = ::util::ser::FixedLengthReader::new($stream, tlv_len.0);
281 decode_tlv!(&mut rd, {$(($reqtype, $reqfield)),*}, {$(($type, $field)),*});
282 rd.eat_remaining().map_err(|_| DecodeError::ShortRead)?;
288 use std::io::{Cursor, Read};
289 use ln::msgs::DecodeError;
290 use util::ser::{Readable, Writeable, HighZeroBytesDroppedVarInt, VecWriter};
291 use bitcoin::secp256k1::PublicKey;
293 // The BOLT TLV test cases don't include any tests which use our "required-value" logic since
294 // the encoding layer in the BOLTs has no such concept, though it makes our macros easier to
295 // work with so they're baked into the decoder. Thus, we have a few additional tests below
296 fn tlv_reader(s: &[u8]) -> Result<(u64, u32, Option<u32>), DecodeError> {
297 let mut s = Cursor::new(s);
300 let mut c: Option<u32> = None;
301 decode_tlv!(&mut s, {(2, a), (3, b)}, {(4, c)});
306 fn tlv_v_short_read() {
307 // We only expect a u32 for type 3 (which we are given), but the L says its 8 bytes.
308 if let Err(DecodeError::ShortRead) = tlv_reader(&::hex::decode(
309 concat!("0100", "0208deadbeef1badbeef", "0308deadbeef")
315 fn tlv_types_out_of_order() {
316 if let Err(DecodeError::InvalidValue) = tlv_reader(&::hex::decode(
317 concat!("0100", "0304deadbeef", "0208deadbeef1badbeef")
320 // ...even if its some field we don't understand
321 if let Err(DecodeError::InvalidValue) = tlv_reader(&::hex::decode(
322 concat!("0208deadbeef1badbeef", "0100", "0304deadbeef")
328 fn tlv_req_type_missing_or_extra() {
329 // It's also bad if they included even fields we don't understand
330 if let Err(DecodeError::UnknownRequiredFeature) = tlv_reader(&::hex::decode(
331 concat!("0100", "0208deadbeef1badbeef", "0304deadbeef", "0600")
334 // ... or if they're missing fields we need
335 if let Err(DecodeError::InvalidValue) = tlv_reader(&::hex::decode(
336 concat!("0100", "0208deadbeef1badbeef")
339 // ... even if that field is even
340 if let Err(DecodeError::InvalidValue) = tlv_reader(&::hex::decode(
341 concat!("0304deadbeef", "0500")
347 fn tlv_simple_good_cases() {
348 assert_eq!(tlv_reader(&::hex::decode(
349 concat!("0208deadbeef1badbeef", "03041bad1dea")
350 ).unwrap()[..]).unwrap(),
351 (0xdeadbeef1badbeef, 0x1bad1dea, None));
352 assert_eq!(tlv_reader(&::hex::decode(
353 concat!("0208deadbeef1badbeef", "03041bad1dea", "040401020304")
354 ).unwrap()[..]).unwrap(),
355 (0xdeadbeef1badbeef, 0x1bad1dea, Some(0x01020304)));
358 impl Readable for (PublicKey, u64, u64) {
360 fn read<R: Read>(reader: &mut R) -> Result<(PublicKey, u64, u64), DecodeError> {
361 Ok((Readable::read(reader)?, Readable::read(reader)?, Readable::read(reader)?))
365 // BOLT TLV test cases
366 fn tlv_reader_n1(s: &[u8]) -> Result<(Option<HighZeroBytesDroppedVarInt<u64>>, Option<u64>, Option<(PublicKey, u64, u64)>, Option<u16>), DecodeError> {
367 let mut s = Cursor::new(s);
368 let mut tlv1: Option<HighZeroBytesDroppedVarInt<u64>> = None;
369 let mut tlv2: Option<u64> = None;
370 let mut tlv3: Option<(PublicKey, u64, u64)> = None;
371 let mut tlv4: Option<u16> = None;
372 decode_tlv!(&mut s, {}, {(1, tlv1), (2, tlv2), (3, tlv3), (254, tlv4)});
373 Ok((tlv1, tlv2, tlv3, tlv4))
377 fn bolt_tlv_bogus_stream() {
378 macro_rules! do_test {
379 ($stream: expr, $reason: ident) => {
380 if let Err(DecodeError::$reason) = tlv_reader_n1(&::hex::decode($stream).unwrap()[..]) {
385 // TLVs from the BOLT test cases which should not decode as either n1 or n2
386 do_test!(concat!("fd01"), ShortRead);
387 do_test!(concat!("fd0001", "00"), InvalidValue);
388 do_test!(concat!("fd0101"), ShortRead);
389 do_test!(concat!("0f", "fd"), ShortRead);
390 do_test!(concat!("0f", "fd26"), ShortRead);
391 do_test!(concat!("0f", "fd2602"), ShortRead);
392 do_test!(concat!("0f", "fd0001", "00"), InvalidValue);
393 do_test!(concat!("0f", "fd0201", "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), ShortRead);
395 do_test!(concat!("12", "00"), UnknownRequiredFeature);
396 do_test!(concat!("fd0102", "00"), UnknownRequiredFeature);
397 do_test!(concat!("fe01000002", "00"), UnknownRequiredFeature);
398 do_test!(concat!("ff0100000000000002", "00"), UnknownRequiredFeature);
402 fn bolt_tlv_bogus_n1_stream() {
403 macro_rules! do_test {
404 ($stream: expr, $reason: ident) => {
405 if let Err(DecodeError::$reason) = tlv_reader_n1(&::hex::decode($stream).unwrap()[..]) {
410 // TLVs from the BOLT test cases which should not decode as n1
411 do_test!(concat!("01", "09", "ffffffffffffffffff"), InvalidValue);
412 do_test!(concat!("01", "01", "00"), InvalidValue);
413 do_test!(concat!("01", "02", "0001"), InvalidValue);
414 do_test!(concat!("01", "03", "000100"), InvalidValue);
415 do_test!(concat!("01", "04", "00010000"), InvalidValue);
416 do_test!(concat!("01", "05", "0001000000"), InvalidValue);
417 do_test!(concat!("01", "06", "000100000000"), InvalidValue);
418 do_test!(concat!("01", "07", "00010000000000"), InvalidValue);
419 do_test!(concat!("01", "08", "0001000000000000"), InvalidValue);
420 do_test!(concat!("02", "07", "01010101010101"), ShortRead);
421 do_test!(concat!("02", "09", "010101010101010101"), InvalidValue);
422 do_test!(concat!("03", "21", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb"), ShortRead);
423 do_test!(concat!("03", "29", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb0000000000000001"), ShortRead);
424 do_test!(concat!("03", "30", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb000000000000000100000000000001"), ShortRead);
425 do_test!(concat!("03", "31", "043da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb00000000000000010000000000000002"), InvalidValue);
426 do_test!(concat!("03", "32", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb0000000000000001000000000000000001"), InvalidValue);
427 do_test!(concat!("fd00fe", "00"), ShortRead);
428 do_test!(concat!("fd00fe", "01", "01"), ShortRead);
429 do_test!(concat!("fd00fe", "03", "010101"), InvalidValue);
430 do_test!(concat!("00", "00"), UnknownRequiredFeature);
432 do_test!(concat!("02", "08", "0000000000000226", "01", "01", "2a"), InvalidValue);
433 do_test!(concat!("02", "08", "0000000000000231", "02", "08", "0000000000000451"), InvalidValue);
434 do_test!(concat!("1f", "00", "0f", "01", "2a"), InvalidValue);
435 do_test!(concat!("1f", "00", "1f", "01", "2a"), InvalidValue);
437 // The last BOLT test modified to not require creating a new decoder for one trivial test.
438 do_test!(concat!("ffffffffffffffffff", "00", "01", "00"), InvalidValue);
442 fn bolt_tlv_valid_n1_stream() {
443 macro_rules! do_test {
444 ($stream: expr, $tlv1: expr, $tlv2: expr, $tlv3: expr, $tlv4: expr) => {
445 if let Ok((tlv1, tlv2, tlv3, tlv4)) = tlv_reader_n1(&::hex::decode($stream).unwrap()[..]) {
446 assert_eq!(tlv1.map(|v| v.0), $tlv1);
447 assert_eq!(tlv2, $tlv2);
448 assert_eq!(tlv3, $tlv3);
449 assert_eq!(tlv4, $tlv4);
454 do_test!(concat!(""), None, None, None, None);
455 do_test!(concat!("21", "00"), None, None, None, None);
456 do_test!(concat!("fd0201", "00"), None, None, None, None);
457 do_test!(concat!("fd00fd", "00"), None, None, None, None);
458 do_test!(concat!("fd00ff", "00"), None, None, None, None);
459 do_test!(concat!("fe02000001", "00"), None, None, None, None);
460 do_test!(concat!("ff0200000000000001", "00"), None, None, None, None);
462 do_test!(concat!("01", "00"), Some(0), None, None, None);
463 do_test!(concat!("01", "01", "01"), Some(1), None, None, None);
464 do_test!(concat!("01", "02", "0100"), Some(256), None, None, None);
465 do_test!(concat!("01", "03", "010000"), Some(65536), None, None, None);
466 do_test!(concat!("01", "04", "01000000"), Some(16777216), None, None, None);
467 do_test!(concat!("01", "05", "0100000000"), Some(4294967296), None, None, None);
468 do_test!(concat!("01", "06", "010000000000"), Some(1099511627776), None, None, None);
469 do_test!(concat!("01", "07", "01000000000000"), Some(281474976710656), None, None, None);
470 do_test!(concat!("01", "08", "0100000000000000"), Some(72057594037927936), None, None, None);
471 do_test!(concat!("02", "08", "0000000000000226"), None, Some((0 << 30) | (0 << 5) | (550 << 0)), None, None);
472 do_test!(concat!("03", "31", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb00000000000000010000000000000002"),
474 PublicKey::from_slice(&::hex::decode("023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb").unwrap()[..]).unwrap(), 1, 2)),
476 do_test!(concat!("fd00fe", "02", "0226"), None, None, None, Some(550));
479 fn do_simple_test_tlv_write() -> Result<(), ::std::io::Error> {
480 let mut stream = VecWriter(Vec::new());
483 encode_varint_length_prefixed_tlv!(&mut stream, { (1, 1u8) }, { (42, None::<u64>) });
484 assert_eq!(stream.0, ::hex::decode("03010101").unwrap());
487 encode_varint_length_prefixed_tlv!(&mut stream, { }, { (1, Some(1u8)) });
488 assert_eq!(stream.0, ::hex::decode("03010101").unwrap());
491 encode_varint_length_prefixed_tlv!(&mut stream, { (4, 0xabcdu16) }, { (42, None::<u64>) });
492 assert_eq!(stream.0, ::hex::decode("040402abcd").unwrap());
495 encode_varint_length_prefixed_tlv!(&mut stream, { (0xff, 0xabcdu16) }, { (42, None::<u64>) });
496 assert_eq!(stream.0, ::hex::decode("06fd00ff02abcd").unwrap());
499 encode_varint_length_prefixed_tlv!(&mut stream, { (0, 1u64), (0xff, HighZeroBytesDroppedVarInt(0u64)) }, { (42, None::<u64>) });
500 assert_eq!(stream.0, ::hex::decode("0e00080000000000000001fd00ff00").unwrap());
503 encode_varint_length_prefixed_tlv!(&mut stream, { (0xff, HighZeroBytesDroppedVarInt(0u64)) }, { (0, Some(1u64)) });
504 assert_eq!(stream.0, ::hex::decode("0e00080000000000000001fd00ff00").unwrap());
510 fn simple_test_tlv_write() {
511 do_simple_test_tlv_write().unwrap();