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 encode_tlv!(::util::ser::BigSize, $stream, {$(($type, $field)),*}, {$(($optional_type, $optional_field)),*});
14 ($name_ty: path, $stream: expr, {$(($type: expr, $field: expr)),*}, {$(($optional_type: expr, $optional_field: expr)),*}) => { {
15 #[allow(unused_imports)]
16 use util::ser::BigSize;
17 // Fields must be serialized in order, so we have to potentially switch between optional
18 // fields and normal fields while serializing. Thus, we end up having to loop over the type
20 // Sadly, while LLVM does appear smart enough to make `max_field` a constant, it appears to
21 // refuse to unroll the loop. If we have enough entries that this is slow we can revisit
22 // this design in the future.
24 let mut max_field: u64 = 0;
26 if $type + 1 >= max_field { max_field = $type + 1; }
29 if $optional_type + 1 >= max_field { max_field = $optional_type + 1; }
31 #[allow(unused_variables)]
32 for i in 0..max_field {
35 $name_ty($type).write($stream)?;
36 BigSize($field.serialized_length() as u64).write($stream)?;
37 $field.write($stream)?;
41 if i == $optional_type {
42 if let Some(ref field) = $optional_field {
43 $name_ty($optional_type).write($stream)?;
44 BigSize(field.serialized_length() as u64).write($stream)?;
45 field.write($stream)?;
53 macro_rules! get_varint_length_prefixed_tlv_length {
54 ($name_ty: path, {$(($type: expr, $field: expr)),*}, {$(($optional_type: expr, $optional_field: expr)),* $(,)*}) => { {
55 use util::ser::LengthCalculatingWriter;
57 let mut len = LengthCalculatingWriter(0);
60 $name_ty($type).write(&mut len).expect("No in-memory data may fail to serialize");
61 let field_len = $field.serialized_length();
62 BigSize(field_len as u64).write(&mut len).expect("No in-memory data may fail to serialize");
66 if let Some(ref field) = $optional_field {
67 $name_ty($optional_type).write(&mut len).expect("No in-memory data may fail to serialize");
68 let field_len = field.serialized_length();
69 BigSize(field_len as u64).write(&mut len).expect("No in-memory data may fail to serialize");
78 macro_rules! encode_varint_length_prefixed_tlv {
79 ($stream: expr, {$(($type: expr, $field: expr)),*}, {$(($optional_type: expr, $optional_field: expr)),*}) => {
80 encode_varint_length_prefixed_tlv!(::util::ser::BigSize, $stream, {$(($type, $field)),*}, {$(($optional_type, $optional_field)),*});
82 ($name_ty: path, $stream: expr, {$(($type: expr, $field: expr)),*}, {$(($optional_type: expr, $optional_field: expr)),*}) => { {
83 use util::ser::BigSize;
84 let len = get_varint_length_prefixed_tlv_length!($name_ty, { $(($type, $field)),* }, { $(($optional_type, $optional_field)),* });
85 BigSize(len as u64).write($stream)?;
86 encode_tlv!($stream, { $(($type, $field)),* }, { $(($optional_type, $optional_field)),* });
90 macro_rules! decode_tlv {
91 ($stream: expr, {$(($reqtype: expr, $reqfield: ident)),*}, {$(($type: expr, $field: ident)),*}) => {
92 decode_tlv!(::util::ser::BigSize, $stream, {$(($reqtype, $reqfield)),*}, {$(($type, $field)),*});
94 ($name_ty: path, $stream: expr, {$(($reqtype: expr, $reqfield: ident)),*}, {$(($type: expr, $field: ident)),*}) => { {
95 use ln::msgs::DecodeError;
96 #[allow(unused_imports)]
98 #[allow(unused_imports)]
100 let mut last_seen_type = None;
104 // First decode the type of this TLV:
105 let typ: $name_ty = {
106 // We track whether any bytes were read during the consensus_decode call to
107 // determine whether we should break or return ShortRead if we get an
108 // UnexpectedEof. This should in every case be largely cosmetic, but its nice to
109 // pass the TLV test vectors exactly, which requre this distinction.
110 let mut tracking_reader = ser::ReadTrackingReader::new($stream);
111 match ser::Readable::read(&mut tracking_reader) {
112 Err(DecodeError::ShortRead) => {
113 if !tracking_reader.have_read {
116 Err(DecodeError::ShortRead)?
124 // Types must be unique and monotonically increasing:
125 match last_seen_type {
126 Some(t) if typ.0 <= t => {
127 Err(DecodeError::InvalidValue)?
131 // As we read types, make sure we hit every required type:
133 #[allow(unused_comparisons)] // Note that $reqtype may be 0 making the second comparison always true
134 let invalid_order = (last_seen_type.is_none() || last_seen_type.unwrap() < $reqtype) && typ.0 > $reqtype;
136 Err(DecodeError::InvalidValue)?
139 last_seen_type = Some(typ.0);
141 // Finally, read the length and value itself:
144 match $reqfield.fixed_len_read() {
145 Some(len) if len != 0 => {
146 let mut v = [0u8; 9];
148 let mut w = &mut v[..];
149 ser::BigSize(len as u64).write(&mut w).unwrap();
154 $stream.read_exact(&mut r[0..bslen])?;
155 if r[..bslen] != v[..bslen] {
156 Err(DecodeError::InvalidValue)?
158 $reqfield = ser::Readable::read($stream)?;
161 let length: ser::BigSize = Readable::read($stream)?;
162 let mut s = ser::FixedLengthReader::new($stream, length.0);
163 $reqfield = ser::Readable::read(&mut s)?;
164 if s.bytes_remain() {
165 s.eat_remaining()?; // Return ShortRead if there's actually not enough bytes
166 Err(DecodeError::InvalidValue)?
172 match $field.lulz_len_read() {
173 Some(len) if len != 0 => {
174 let mut v = [0u8; 9];
176 let mut w = &mut v[..];
177 ser::BigSize(len as u64).write(&mut w).unwrap();
182 $stream.read_exact(&mut r[0..bslen])?;
183 if r[..bslen] != v[..bslen] {
184 Err(DecodeError::InvalidValue)?
186 $field = Some(ser::Readable::read($stream)?);
189 let length: ser::BigSize = Readable::read($stream)?;
190 let mut s = ser::FixedLengthReader::new($stream, length.0);
191 $field = Some(ser::Readable::read(&mut s)?);
192 if s.bytes_remain() {
193 s.eat_remaining()?; // Return ShortRead if there's actually not enough bytes
194 Err(DecodeError::InvalidValue)?
200 Err(DecodeError::UnknownRequiredFeature)?
203 let length: ser::BigSize = Readable::read($stream)?;
204 let mut s = ser::FixedLengthReader::new($stream, length.0);
209 // Make sure we got to each required type after we've read every TLV:
211 #[allow(unused_comparisons)] // Note that $reqtype may be 0 making the second comparison always true
212 let missing_req_type = last_seen_type.is_none() || last_seen_type.unwrap() < $reqtype;
213 if missing_req_type {
214 Err(DecodeError::InvalidValue)?
220 macro_rules! impl_writeable {
221 ($st:ident, $len: expr, {$($field:ident),*}) => {
222 impl ::util::ser::Writeable for $st {
223 fn write<W: ::util::ser::Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
227 #[cfg(any(test, feature = "fuzztarget"))]
229 // In tests, assert that the hard-coded length matches the actual one
231 use util::ser::LengthCalculatingWriter;
232 let mut len_calc = LengthCalculatingWriter(0);
233 $( self.$field.write(&mut len_calc).expect("No in-memory data may fail to serialize"); )*
234 assert_eq!(len_calc.0, $len);
237 $( self.$field.write(w)?; )*
242 fn serialized_length(&self) -> usize {
243 if $len == 0 || cfg!(any(test, feature = "fuzztarget")) {
244 let mut len_calc = 0;
245 $( len_calc += self.$field.serialized_length(); )*
247 // In tests, assert that the hard-coded length matches the actual one
248 assert_eq!(len_calc, $len);
257 impl ::util::ser::Readable for $st {
258 fn read<R: ::std::io::Read>(r: &mut R) -> Result<Self, ::ln::msgs::DecodeError> {
260 $($field: ::util::ser::Readable::read(r)?),*
263 const FIXED_LEN: Option<usize> = Some($len);
267 macro_rules! impl_writeable_len_match {
268 ($struct: ident, $cmp: tt, ($calc_len: expr), {$({$match: pat, $length: expr}),*}, {$($field:ident),*}) => {
269 impl Writeable for $struct {
270 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
271 let len = match *self {
272 $($match => $length,)*
275 #[cfg(any(test, feature = "fuzztarget"))]
277 // In tests, assert that the hard-coded length matches the actual one
278 use util::ser::LengthCalculatingWriter;
279 let mut len_calc = LengthCalculatingWriter(0);
280 $( self.$field.write(&mut len_calc).expect("No in-memory data may fail to serialize"); )*
281 assert!(len_calc.0 $cmp len);
283 $( self.$field.write(w)?; )*
288 fn serialized_length(&self) -> usize {
289 if $calc_len || cfg!(any(test, feature = "fuzztarget")) {
290 let mut len_calc = 0;
291 $( len_calc += self.$field.serialized_length(); )*
293 assert_eq!(len_calc, match *self {
294 $($match => $length,)*
300 $($match => $length,)*
305 impl ::util::ser::Readable for $struct {
306 fn read<R: ::std::io::Read>(r: &mut R) -> Result<Self, DecodeError> {
308 $($field: Readable::read(r)?),*
313 ($struct: ident, $cmp: tt, {$({$match: pat, $length: expr}),*}, {$($field:ident),*}) => {
314 impl_writeable_len_match!($struct, $cmp, (true), { $({ $match, $length }),* }, { $($field),* });
316 ($struct: ident, {$({$match: pat, $length: expr}),*}, {$($field:ident),*}) => {
317 impl_writeable_len_match!($struct, ==, (false), { $({ $match, $length }),* }, { $($field),* });
321 /// Write out two bytes to indicate the version of an object.
322 /// $this_version represents a unique version of a type. Incremented whenever the type's
323 /// serialization format has changed or has a new interpretation. Used by a type's
324 /// reader to determine how to interpret fields or if it can understand a serialized
326 /// $min_version_that_can_read_this is the minimum reader version which can understand this
327 /// serialized object. Previous versions will simply err with a
328 /// DecodeError::UnknownVersion.
330 /// Updates to either $this_version or $min_version_that_can_read_this should be included in
333 /// Both version fields can be specific to this type of object.
334 macro_rules! write_ver_prefix {
335 ($stream: expr, $this_version: expr, $min_version_that_can_read_this: expr) => {
336 $stream.write_all(&[$this_version; 1])?;
337 $stream.write_all(&[$min_version_that_can_read_this; 1])?;
341 /// Writes out a suffix to an object which contains potentially backwards-compatible, optional
342 /// fields which old nodes can happily ignore.
344 /// It is written out in TLV format and, as with all TLV fields, unknown even fields cause a
345 /// DecodeError::UnknownRequiredFeature error, with unknown odd fields ignored.
347 /// This is the preferred method of adding new fields that old nodes can ignore and still function
349 macro_rules! write_tlv_fields {
350 ($stream: expr, {$(($type: expr, $field: expr)),* $(,)*}, {$(($optional_type: expr, $optional_field: expr)),* $(,)*}) => {
351 encode_varint_length_prefixed_tlv!(::util::ser::U8Wrapper, $stream, {$(($type, $field)),*} , {$(($optional_type, $optional_field)),*});
355 /// Reads a prefix added by write_ver_prefix!(), above. Takes the current version of the
356 /// serialization logic for this object. This is compared against the
357 /// $min_version_that_can_read_this added by write_ver_prefix!().
358 macro_rules! read_ver_prefix {
359 ($stream: expr, $this_version: expr) => { {
360 let ver: u8 = Readable::read($stream)?;
361 let min_ver: u8 = Readable::read($stream)?;
362 if min_ver > $this_version {
363 return Err(DecodeError::UnknownVersion);
369 /// Reads a suffix added by write_tlv_fields.
370 macro_rules! read_tlv_fields {
371 ($stream: expr, {$(($reqtype: expr, $reqfield: ident)),* $(,)*}, {$(($type: expr, $field: ident)),* $(,)*}) => { {
372 let tlv_len = ::util::ser::BigSize::read($stream)?;
373 let mut rd = ::util::ser::FixedLengthReader::new($stream, tlv_len.0);
374 decode_tlv!(::util::ser::U8Wrapper, &mut rd, {$(($reqtype, $reqfield)),*}, {$(($type, $field)),*});
375 rd.eat_remaining().map_err(|_| DecodeError::ShortRead)?;
379 // If we naively create a struct in impl_writeable_tlv_based below, we may end up returning
380 // `Self { ,,vecfield: vecfield }` which is obviously incorrect. Instead, we have to match here to
381 // detect at least one empty field set and skip the potentially-extra comma.
382 macro_rules! _init_tlv_based_struct {
383 ({}, {$($field: ident),*}, {$($vecfield: ident),*}) => {
386 $($vecfield: $vecfield.unwrap().0),*
389 ({$($reqfield: ident),*}, {}, {$($vecfield: ident),*}) => {
391 $($reqfield: $reqfield.0.unwrap()),*,
392 $($vecfield: $vecfield.unwrap().0),*
395 ({$($reqfield: ident),*}, {$($field: ident),*}, {}) => {
397 $($reqfield: $reqfield.0.unwrap()),*,
401 ({$($reqfield: ident),*}, {$($field: ident),*}, {$($vecfield: ident),*}) => {
403 $($reqfield: $reqfield.0.unwrap()),*,
405 $($vecfield: $vecfield.unwrap().0),*
410 // If we don't have any optional types below, but do have some vec types, we end up calling
411 // `write_tlv_field!($stream, {..}, {, (vec_ty, vec_val)})`, which is obviously broken.
412 // Instead, for write and read we match the missing values and skip the extra comma.
413 macro_rules! _write_tlv_fields {
414 ($stream: expr, {$(($type: expr, $field: expr)),* $(,)*}, {}, {$(($optional_type: expr, $optional_field: expr)),* $(,)*}) => {
415 write_tlv_fields!($stream, {$(($type, $field)),*} , {$(($optional_type, $optional_field)),*});
417 ($stream: expr, {$(($type: expr, $field: expr)),* $(,)*}, {$(($optional_type: expr, $optional_field: expr)),* $(,)*}, {$(($optional_type_2: expr, $optional_field_2: expr)),* $(,)*}) => {
418 write_tlv_fields!($stream, {$(($type, $field)),*} , {$(($optional_type, $optional_field)),*, $(($optional_type_2, $optional_field_2)),*});
421 macro_rules! _get_tlv_len {
422 ({$(($type: expr, $field: expr)),* $(,)*}, {}, {$(($optional_type: expr, $optional_field: expr)),* $(,)*}) => {
423 get_varint_length_prefixed_tlv_length!(::util::ser::U8Wrapper, {$(($type, $field)),*} , {$(($optional_type, $optional_field)),*})
425 ({$(($type: expr, $field: expr)),* $(,)*}, {$(($optional_type: expr, $optional_field: expr)),* $(,)*}, {$(($optional_type_2: expr, $optional_field_2: expr)),* $(,)*}) => {
426 get_varint_length_prefixed_tlv_length!(::util::ser::U8Wrapper, {$(($type, $field)),*} , {$(($optional_type, $optional_field)),*, $(($optional_type_2, $optional_field_2)),*})
429 macro_rules! _read_tlv_fields {
430 ($stream: expr, {$(($reqtype: expr, $reqfield: ident)),* $(,)*}, {}, {$(($type: expr, $field: ident)),* $(,)*}) => {
431 read_tlv_fields!($stream, {$(($reqtype, $reqfield)),*}, {$(($type, $field)),*});
433 ($stream: expr, {$(($reqtype: expr, $reqfield: ident)),* $(,)*}, {$(($type: expr, $field: ident)),* $(,)*}, {$(($type_2: expr, $field_2: ident)),* $(,)*}) => {
434 read_tlv_fields!($stream, {$(($reqtype, $reqfield)),*}, {$(($type, $field)),*, $(($type_2, $field_2)),*});
438 /// Implements Readable/Writeable for a struct storing it as a set of TLVs
439 /// First block includes all the required fields including a dummy value which is used during
440 /// deserialization but which will never be exposed to other code.
441 /// The second block includes optional fields.
442 /// The third block includes any Vecs which need to have their individual elements serialized.
443 macro_rules! impl_writeable_tlv_based {
444 ($st: ident, {$(($reqtype: expr, $reqfield: ident)),* $(,)*}, {$(($type: expr, $field: ident)),* $(,)*}, {$(($vectype: expr, $vecfield: ident)),* $(,)*}) => {
445 impl ::util::ser::Writeable for $st {
446 fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
447 _write_tlv_fields!(writer, {
448 $(($reqtype, self.$reqfield)),*
450 $(($type, self.$field)),*
452 $(($vectype, Some(::util::ser::VecWriteWrapper(&self.$vecfield)))),*
458 fn serialized_length(&self) -> usize {
459 let len = _get_tlv_len!({
460 $(($reqtype, self.$reqfield)),*
462 $(($type, self.$field)),*
464 $(($vectype, Some(::util::ser::VecWriteWrapper(&self.$vecfield)))),*
466 use util::ser::{BigSize, LengthCalculatingWriter};
467 let mut len_calc = LengthCalculatingWriter(0);
468 BigSize(len as u64).write(&mut len_calc).expect("No in-memory data may fail to serialize");
473 impl ::util::ser::Readable for $st {
474 fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Self, ::ln::msgs::DecodeError> {
476 let mut $reqfield = ::util::ser::OptionDeserWrapper(None);
479 let mut $field = None;
482 let mut $vecfield = Some(::util::ser::VecReadWrapper(Vec::new()));
484 _read_tlv_fields!(reader, {
485 $(($reqtype, $reqfield)),*
489 $(($vectype, $vecfield)),*
491 _init_tlv_based_struct!({$($reqfield),*}, {$($field),*}, {$($vecfield),*})
500 use std::io::{Cursor, Read};
501 use ln::msgs::DecodeError;
502 use util::ser::{Readable, Writeable, HighZeroBytesDroppedVarInt, VecWriter};
503 use bitcoin::secp256k1::PublicKey;
505 // The BOLT TLV test cases don't include any tests which use our "required-value" logic since
506 // the encoding layer in the BOLTs has no such concept, though it makes our macros easier to
507 // work with so they're baked into the decoder. Thus, we have a few additional tests below
508 fn tlv_reader(s: &[u8]) -> Result<(u64, u32, Option<u32>), DecodeError> {
509 let mut s = Cursor::new(s);
512 let mut c: Option<u32> = None;
513 decode_tlv!(&mut s, {(2, a), (3, b)}, {(4, c)});
518 fn tlv_v_short_read() {
519 // We only expect a u32 for type 3 (which we are given), but the L says its 8 bytes.
520 if let Err(DecodeError::ShortRead) = tlv_reader(&::hex::decode(
521 concat!("0100", "0208deadbeef1badbeef", "0308deadbeef")
527 fn tlv_types_out_of_order() {
528 if let Err(DecodeError::InvalidValue) = tlv_reader(&::hex::decode(
529 concat!("0100", "0304deadbeef", "0208deadbeef1badbeef")
532 // ...even if its some field we don't understand
533 if let Err(DecodeError::InvalidValue) = tlv_reader(&::hex::decode(
534 concat!("0208deadbeef1badbeef", "0100", "0304deadbeef")
540 fn tlv_req_type_missing_or_extra() {
541 // It's also bad if they included even fields we don't understand
542 if let Err(DecodeError::UnknownRequiredFeature) = tlv_reader(&::hex::decode(
543 concat!("0100", "0208deadbeef1badbeef", "0304deadbeef", "0600")
546 // ... or if they're missing fields we need
547 if let Err(DecodeError::InvalidValue) = tlv_reader(&::hex::decode(
548 concat!("0100", "0208deadbeef1badbeef")
551 // ... even if that field is even
552 if let Err(DecodeError::InvalidValue) = tlv_reader(&::hex::decode(
553 concat!("0304deadbeef", "0500")
559 fn tlv_simple_good_cases() {
560 assert_eq!(tlv_reader(&::hex::decode(
561 concat!("0208deadbeef1badbeef", "03041bad1dea")
562 ).unwrap()[..]).unwrap(),
563 (0xdeadbeef1badbeef, 0x1bad1dea, None));
564 assert_eq!(tlv_reader(&::hex::decode(
565 concat!("0208deadbeef1badbeef", "03041bad1dea", "040401020304")
566 ).unwrap()[..]).unwrap(),
567 (0xdeadbeef1badbeef, 0x1bad1dea, Some(0x01020304)));
570 impl Readable for (PublicKey, u64, u64) {
572 fn read<R: Read>(reader: &mut R) -> Result<(PublicKey, u64, u64), DecodeError> {
573 Ok((Readable::read(reader)?, Readable::read(reader)?, Readable::read(reader)?))
577 // BOLT TLV test cases
578 fn tlv_reader_n1(s: &[u8]) -> Result<(Option<HighZeroBytesDroppedVarInt<u64>>, Option<u64>, Option<(PublicKey, u64, u64)>, Option<u16>), DecodeError> {
579 let mut s = Cursor::new(s);
580 let mut tlv1: Option<HighZeroBytesDroppedVarInt<u64>> = None;
581 let mut tlv2: Option<u64> = None;
582 let mut tlv3: Option<(PublicKey, u64, u64)> = None;
583 let mut tlv4: Option<u16> = None;
584 decode_tlv!(&mut s, {}, {(1, tlv1), (2, tlv2), (3, tlv3), (254, tlv4)});
585 Ok((tlv1, tlv2, tlv3, tlv4))
589 fn bolt_tlv_bogus_stream() {
590 macro_rules! do_test {
591 ($stream: expr, $reason: ident) => {
592 if let Err(DecodeError::$reason) = tlv_reader_n1(&::hex::decode($stream).unwrap()[..]) {
597 // TLVs from the BOLT test cases which should not decode as either n1 or n2
598 do_test!(concat!("fd01"), ShortRead);
599 do_test!(concat!("fd0001", "00"), InvalidValue);
600 do_test!(concat!("fd0101"), ShortRead);
601 do_test!(concat!("0f", "fd"), ShortRead);
602 do_test!(concat!("0f", "fd26"), ShortRead);
603 do_test!(concat!("0f", "fd2602"), ShortRead);
604 do_test!(concat!("0f", "fd0001", "00"), InvalidValue);
605 do_test!(concat!("0f", "fd0201", "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"), ShortRead);
607 do_test!(concat!("12", "00"), UnknownRequiredFeature);
608 do_test!(concat!("fd0102", "00"), UnknownRequiredFeature);
609 do_test!(concat!("fe01000002", "00"), UnknownRequiredFeature);
610 do_test!(concat!("ff0100000000000002", "00"), UnknownRequiredFeature);
614 fn bolt_tlv_bogus_n1_stream() {
615 macro_rules! do_test {
616 ($stream: expr, $reason: ident) => {
617 if let Err(DecodeError::$reason) = tlv_reader_n1(&::hex::decode($stream).unwrap()[..]) {
622 // TLVs from the BOLT test cases which should not decode as n1
623 do_test!(concat!("01", "09", "ffffffffffffffffff"), InvalidValue);
624 do_test!(concat!("01", "01", "00"), InvalidValue);
625 do_test!(concat!("01", "02", "0001"), InvalidValue);
626 do_test!(concat!("01", "03", "000100"), InvalidValue);
627 do_test!(concat!("01", "04", "00010000"), InvalidValue);
628 do_test!(concat!("01", "05", "0001000000"), InvalidValue);
629 do_test!(concat!("01", "06", "000100000000"), InvalidValue);
630 do_test!(concat!("01", "07", "00010000000000"), InvalidValue);
631 do_test!(concat!("01", "08", "0001000000000000"), InvalidValue);
632 do_test!(concat!("02", "07", "01010101010101"), ShortRead);
633 do_test!(concat!("02", "09", "010101010101010101"), InvalidValue);
634 do_test!(concat!("03", "21", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb"), ShortRead);
635 do_test!(concat!("03", "29", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb0000000000000001"), ShortRead);
636 do_test!(concat!("03", "30", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb000000000000000100000000000001"), ShortRead);
637 do_test!(concat!("03", "31", "043da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb00000000000000010000000000000002"), InvalidValue);
638 do_test!(concat!("03", "32", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb0000000000000001000000000000000001"), InvalidValue);
639 do_test!(concat!("fd00fe", "00"), ShortRead);
640 do_test!(concat!("fd00fe", "01", "01"), ShortRead);
641 do_test!(concat!("fd00fe", "03", "010101"), InvalidValue);
642 do_test!(concat!("00", "00"), UnknownRequiredFeature);
644 do_test!(concat!("02", "08", "0000000000000226", "01", "01", "2a"), InvalidValue);
645 do_test!(concat!("02", "08", "0000000000000231", "02", "08", "0000000000000451"), InvalidValue);
646 do_test!(concat!("1f", "00", "0f", "01", "2a"), InvalidValue);
647 do_test!(concat!("1f", "00", "1f", "01", "2a"), InvalidValue);
649 // The last BOLT test modified to not require creating a new decoder for one trivial test.
650 do_test!(concat!("ffffffffffffffffff", "00", "01", "00"), InvalidValue);
654 fn bolt_tlv_valid_n1_stream() {
655 macro_rules! do_test {
656 ($stream: expr, $tlv1: expr, $tlv2: expr, $tlv3: expr, $tlv4: expr) => {
657 if let Ok((tlv1, tlv2, tlv3, tlv4)) = tlv_reader_n1(&::hex::decode($stream).unwrap()[..]) {
658 assert_eq!(tlv1.map(|v| v.0), $tlv1);
659 assert_eq!(tlv2, $tlv2);
660 assert_eq!(tlv3, $tlv3);
661 assert_eq!(tlv4, $tlv4);
666 do_test!(concat!(""), None, None, None, None);
667 do_test!(concat!("21", "00"), None, None, None, None);
668 do_test!(concat!("fd0201", "00"), None, None, None, None);
669 do_test!(concat!("fd00fd", "00"), None, None, None, None);
670 do_test!(concat!("fd00ff", "00"), None, None, None, None);
671 do_test!(concat!("fe02000001", "00"), None, None, None, None);
672 do_test!(concat!("ff0200000000000001", "00"), None, None, None, None);
674 do_test!(concat!("01", "00"), Some(0), None, None, None);
675 do_test!(concat!("01", "01", "01"), Some(1), None, None, None);
676 do_test!(concat!("01", "02", "0100"), Some(256), None, None, None);
677 do_test!(concat!("01", "03", "010000"), Some(65536), None, None, None);
678 do_test!(concat!("01", "04", "01000000"), Some(16777216), None, None, None);
679 do_test!(concat!("01", "05", "0100000000"), Some(4294967296), None, None, None);
680 do_test!(concat!("01", "06", "010000000000"), Some(1099511627776), None, None, None);
681 do_test!(concat!("01", "07", "01000000000000"), Some(281474976710656), None, None, None);
682 do_test!(concat!("01", "08", "0100000000000000"), Some(72057594037927936), None, None, None);
683 do_test!(concat!("02", "08", "0000000000000226"), None, Some((0 << 30) | (0 << 5) | (550 << 0)), None, None);
684 do_test!(concat!("03", "31", "023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb00000000000000010000000000000002"),
686 PublicKey::from_slice(&::hex::decode("023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb").unwrap()[..]).unwrap(), 1, 2)),
688 do_test!(concat!("fd00fe", "02", "0226"), None, None, None, Some(550));
691 fn do_simple_test_tlv_write() -> Result<(), ::std::io::Error> {
692 let mut stream = VecWriter(Vec::new());
695 encode_varint_length_prefixed_tlv!(&mut stream, { (1, 1u8) }, { (42, None::<u64>) });
696 assert_eq!(stream.0, ::hex::decode("03010101").unwrap());
699 encode_varint_length_prefixed_tlv!(&mut stream, { }, { (1, Some(1u8)) });
700 assert_eq!(stream.0, ::hex::decode("03010101").unwrap());
703 encode_varint_length_prefixed_tlv!(&mut stream, { (4, 0xabcdu16) }, { (42, None::<u64>) });
704 assert_eq!(stream.0, ::hex::decode("040402abcd").unwrap());
707 encode_varint_length_prefixed_tlv!(&mut stream, { (0xff, 0xabcdu16) }, { (42, None::<u64>) });
708 assert_eq!(stream.0, ::hex::decode("06fd00ff02abcd").unwrap());
711 encode_varint_length_prefixed_tlv!(&mut stream, { (0, 1u64), (0xff, HighZeroBytesDroppedVarInt(0u64)) }, { (42, None::<u64>) });
712 assert_eq!(stream.0, ::hex::decode("0e00080000000000000001fd00ff00").unwrap());
715 encode_varint_length_prefixed_tlv!(&mut stream, { (0xff, HighZeroBytesDroppedVarInt(0u64)) }, { (0, Some(1u64)) });
716 assert_eq!(stream.0, ::hex::decode("0e00080000000000000001fd00ff00").unwrap());
722 fn simple_test_tlv_write() {
723 do_simple_test_tlv_write().unwrap();