Fix upgradable_required fields to actually be required in lower level macros
[rust-lightning] / lightning / src / util / ser.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 //! A very simple serialization framework which is used to serialize/deserialize messages as well
11 //! as [`ChannelManager`]s and [`ChannelMonitor`]s.
12 //!
13 //! [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
14 //! [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor
15
16 use crate::prelude::*;
17 use crate::io::{self, Read, Seek, Write};
18 use crate::io_extras::{copy, sink};
19 use core::hash::Hash;
20 use crate::sync::Mutex;
21 use core::cmp;
22 use core::convert::TryFrom;
23 use core::ops::Deref;
24
25 use alloc::collections::BTreeMap;
26
27 use bitcoin::secp256k1::{PublicKey, SecretKey};
28 use bitcoin::secp256k1::constants::{PUBLIC_KEY_SIZE, SECRET_KEY_SIZE, COMPACT_SIGNATURE_SIZE, SCHNORR_SIGNATURE_SIZE};
29 use bitcoin::secp256k1::ecdsa;
30 use bitcoin::secp256k1::schnorr;
31 use bitcoin::blockdata::constants::ChainHash;
32 use bitcoin::blockdata::script::Script;
33 use bitcoin::blockdata::transaction::{OutPoint, Transaction, TxOut};
34 use bitcoin::consensus;
35 use bitcoin::consensus::Encodable;
36 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
37 use bitcoin::hash_types::{Txid, BlockHash};
38 use core::marker::Sized;
39 use core::time::Duration;
40 use crate::ln::msgs::DecodeError;
41 use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
42
43 use crate::util::byte_utils::{be48_to_array, slice_to_be48};
44
45 /// serialization buffer size
46 pub const MAX_BUF_SIZE: usize = 64 * 1024;
47
48 /// A simplified version of [`std::io::Write`] that exists largely for backwards compatibility.
49 /// An impl is provided for any type that also impls [`std::io::Write`].
50 ///
51 /// (C-not exported) as we only export serialization to/from byte arrays instead
52 pub trait Writer {
53         /// Writes the given buf out. See std::io::Write::write_all for more
54         fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error>;
55 }
56
57 impl<W: Write> Writer for W {
58         #[inline]
59         fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
60                 <Self as io::Write>::write_all(self, buf)
61         }
62 }
63
64 pub(crate) struct WriterWriteAdaptor<'a, W: Writer + 'a>(pub &'a mut W);
65 impl<'a, W: Writer + 'a> Write for WriterWriteAdaptor<'a, W> {
66         #[inline]
67         fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
68                 self.0.write_all(buf)
69         }
70         #[inline]
71         fn write(&mut self, buf: &[u8]) -> Result<usize, io::Error> {
72                 self.0.write_all(buf)?;
73                 Ok(buf.len())
74         }
75         #[inline]
76         fn flush(&mut self) -> Result<(), io::Error> {
77                 Ok(())
78         }
79 }
80
81 pub(crate) struct VecWriter(pub Vec<u8>);
82 impl Writer for VecWriter {
83         #[inline]
84         fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
85                 self.0.extend_from_slice(buf);
86                 Ok(())
87         }
88 }
89
90 /// Writer that only tracks the amount of data written - useful if you need to calculate the length
91 /// of some data when serialized but don't yet need the full data.
92 pub struct LengthCalculatingWriter(pub usize);
93 impl Writer for LengthCalculatingWriter {
94         #[inline]
95         fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
96                 self.0 += buf.len();
97                 Ok(())
98         }
99 }
100
101 /// Essentially [`std::io::Take`] but a bit simpler and with a method to walk the underlying stream
102 /// forward to ensure we always consume exactly the fixed length specified.
103 pub struct FixedLengthReader<R: Read> {
104         read: R,
105         bytes_read: u64,
106         total_bytes: u64,
107 }
108 impl<R: Read> FixedLengthReader<R> {
109         /// Returns a new [`FixedLengthReader`].
110         pub fn new(read: R, total_bytes: u64) -> Self {
111                 Self { read, bytes_read: 0, total_bytes }
112         }
113
114         /// Returns whether some bytes are remaining or not.
115         #[inline]
116         pub fn bytes_remain(&mut self) -> bool {
117                 self.bytes_read != self.total_bytes
118         }
119
120         /// Consumes the remaining bytes.
121         #[inline]
122         pub fn eat_remaining(&mut self) -> Result<(), DecodeError> {
123                 copy(self, &mut sink()).unwrap();
124                 if self.bytes_read != self.total_bytes {
125                         Err(DecodeError::ShortRead)
126                 } else {
127                         Ok(())
128                 }
129         }
130 }
131 impl<R: Read> Read for FixedLengthReader<R> {
132         #[inline]
133         fn read(&mut self, dest: &mut [u8]) -> Result<usize, io::Error> {
134                 if self.total_bytes == self.bytes_read {
135                         Ok(0)
136                 } else {
137                         let read_len = cmp::min(dest.len() as u64, self.total_bytes - self.bytes_read);
138                         match self.read.read(&mut dest[0..(read_len as usize)]) {
139                                 Ok(v) => {
140                                         self.bytes_read += v as u64;
141                                         Ok(v)
142                                 },
143                                 Err(e) => Err(e),
144                         }
145                 }
146         }
147 }
148
149 impl<R: Read> LengthRead for FixedLengthReader<R> {
150         #[inline]
151         fn total_bytes(&self) -> u64 {
152                 self.total_bytes
153         }
154 }
155
156 /// A [`Read`] implementation which tracks whether any bytes have been read at all. This allows us to distinguish
157 /// between "EOF reached before we started" and "EOF reached mid-read".
158 pub struct ReadTrackingReader<R: Read> {
159         read: R,
160         /// Returns whether we have read from this reader or not yet.
161         pub have_read: bool,
162 }
163 impl<R: Read> ReadTrackingReader<R> {
164         /// Returns a new [`ReadTrackingReader`].
165         pub fn new(read: R) -> Self {
166                 Self { read, have_read: false }
167         }
168 }
169 impl<R: Read> Read for ReadTrackingReader<R> {
170         #[inline]
171         fn read(&mut self, dest: &mut [u8]) -> Result<usize, io::Error> {
172                 match self.read.read(dest) {
173                         Ok(0) => Ok(0),
174                         Ok(len) => {
175                                 self.have_read = true;
176                                 Ok(len)
177                         },
178                         Err(e) => Err(e),
179                 }
180         }
181 }
182
183 /// A trait that various LDK types implement allowing them to be written out to a [`Writer`].
184 ///
185 /// (C-not exported) as we only export serialization to/from byte arrays instead
186 pub trait Writeable {
187         /// Writes `self` out to the given [`Writer`].
188         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error>;
189
190         /// Writes `self` out to a `Vec<u8>`.
191         fn encode(&self) -> Vec<u8> {
192                 let mut msg = VecWriter(Vec::new());
193                 self.write(&mut msg).unwrap();
194                 msg.0
195         }
196
197         /// Writes `self` out to a `Vec<u8>`.
198         #[cfg(test)]
199         fn encode_with_len(&self) -> Vec<u8> {
200                 let mut msg = VecWriter(Vec::new());
201                 0u16.write(&mut msg).unwrap();
202                 self.write(&mut msg).unwrap();
203                 let len = msg.0.len();
204                 msg.0[..2].copy_from_slice(&(len as u16 - 2).to_be_bytes());
205                 msg.0
206         }
207
208         /// Gets the length of this object after it has been serialized. This can be overridden to
209         /// optimize cases where we prepend an object with its length.
210         // Note that LLVM optimizes this away in most cases! Check that it isn't before you override!
211         #[inline]
212         fn serialized_length(&self) -> usize {
213                 let mut len_calc = LengthCalculatingWriter(0);
214                 self.write(&mut len_calc).expect("No in-memory data may fail to serialize");
215                 len_calc.0
216         }
217 }
218
219 impl<'a, T: Writeable> Writeable for &'a T {
220         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { (*self).write(writer) }
221 }
222
223 /// A trait that various LDK types implement allowing them to be read in from a [`Read`].
224 ///
225 /// (C-not exported) as we only export serialization to/from byte arrays instead
226 pub trait Readable
227         where Self: Sized
228 {
229         /// Reads a `Self` in from the given [`Read`].
230         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError>;
231 }
232
233 /// A trait that various LDK types implement allowing them to be read in from a
234 /// [`Read`]` + `[`Seek`].
235 pub(crate) trait SeekReadable where Self: Sized {
236         /// Reads a `Self` in from the given [`Read`].
237         fn read<R: Read + Seek>(reader: &mut R) -> Result<Self, DecodeError>;
238 }
239
240 /// A trait that various higher-level LDK types implement allowing them to be read in
241 /// from a [`Read`] given some additional set of arguments which is required to deserialize.
242 ///
243 /// (C-not exported) as we only export serialization to/from byte arrays instead
244 pub trait ReadableArgs<P>
245         where Self: Sized
246 {
247         /// Reads a `Self` in from the given [`Read`].
248         fn read<R: Read>(reader: &mut R, params: P) -> Result<Self, DecodeError>;
249 }
250
251 /// A [`std::io::Read`] that also provides the total bytes available to be read.
252 pub(crate) trait LengthRead: Read {
253         /// The total number of bytes available to be read.
254         fn total_bytes(&self) -> u64;
255 }
256
257 /// A trait that various higher-level LDK types implement allowing them to be read in
258 /// from a Read given some additional set of arguments which is required to deserialize, requiring
259 /// the implementer to provide the total length of the read.
260 pub(crate) trait LengthReadableArgs<P> where Self: Sized
261 {
262         /// Reads a `Self` in from the given [`LengthRead`].
263         fn read<R: LengthRead>(reader: &mut R, params: P) -> Result<Self, DecodeError>;
264 }
265
266 /// A trait that various higher-level LDK types implement allowing them to be read in
267 /// from a [`Read`], requiring the implementer to provide the total length of the read.
268 pub(crate) trait LengthReadable where Self: Sized
269 {
270         /// Reads a `Self` in from the given [`LengthRead`].
271         fn read<R: LengthRead>(reader: &mut R) -> Result<Self, DecodeError>;
272 }
273
274 /// A trait that various LDK types implement allowing them to (maybe) be read in from a [`Read`].
275 ///
276 /// (C-not exported) as we only export serialization to/from byte arrays instead
277 pub trait MaybeReadable
278         where Self: Sized
279 {
280         /// Reads a `Self` in from the given [`Read`].
281         fn read<R: Read>(reader: &mut R) -> Result<Option<Self>, DecodeError>;
282 }
283
284 impl<T: Readable> MaybeReadable for T {
285         #[inline]
286         fn read<R: Read>(reader: &mut R) -> Result<Option<T>, DecodeError> {
287                 Ok(Some(Readable::read(reader)?))
288         }
289 }
290
291 /// Wrapper to read a required (non-optional) TLV record.
292 pub struct RequiredWrapper<T: Readable>(pub Option<T>);
293 impl<T: Readable> Readable for RequiredWrapper<T> {
294         #[inline]
295         fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
296                 Ok(Self(Some(Readable::read(reader)?)))
297         }
298 }
299 /// When handling `default_values`, we want to map the default-value T directly
300 /// to a `RequiredWrapper<T>` in a way that works for `field: T = t;` as
301 /// well. Thus, we assume `Into<T> for T` does nothing and use that.
302 impl<T: Readable> From<T> for RequiredWrapper<T> {
303         fn from(t: T) -> RequiredWrapper<T> { RequiredWrapper(Some(t)) }
304 }
305
306 /// Wrapper to read a required (non-optional) TLV record that may have been upgraded without
307 /// backwards compat.
308 pub struct UpgradableRequired<T: MaybeReadable>(pub Option<T>);
309 impl<T: MaybeReadable> MaybeReadable for UpgradableRequired<T> {
310         #[inline]
311         fn read<R: Read>(reader: &mut R) -> Result<Option<Self>, DecodeError> {
312                 let tlv = MaybeReadable::read(reader)?;
313                 if let Some(tlv) = tlv { return Ok(Some(Self(Some(tlv)))) }
314                 Ok(None)
315         }
316 }
317
318 pub(crate) struct U48(pub u64);
319 impl Writeable for U48 {
320         #[inline]
321         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
322                 writer.write_all(&be48_to_array(self.0))
323         }
324 }
325 impl Readable for U48 {
326         #[inline]
327         fn read<R: Read>(reader: &mut R) -> Result<U48, DecodeError> {
328                 let mut buf = [0; 6];
329                 reader.read_exact(&mut buf)?;
330                 Ok(U48(slice_to_be48(&buf)))
331         }
332 }
333
334 /// Lightning TLV uses a custom variable-length integer called `BigSize`. It is similar to Bitcoin's
335 /// variable-length integers except that it is serialized in big-endian instead of little-endian.
336 ///
337 /// Like Bitcoin's variable-length integer, it exhibits ambiguity in that certain values can be
338 /// encoded in several different ways, which we must check for at deserialization-time. Thus, if
339 /// you're looking for an example of a variable-length integer to use for your own project, move
340 /// along, this is a rather poor design.
341 pub struct BigSize(pub u64);
342 impl Writeable for BigSize {
343         #[inline]
344         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
345                 match self.0 {
346                         0...0xFC => {
347                                 (self.0 as u8).write(writer)
348                         },
349                         0xFD...0xFFFF => {
350                                 0xFDu8.write(writer)?;
351                                 (self.0 as u16).write(writer)
352                         },
353                         0x10000...0xFFFFFFFF => {
354                                 0xFEu8.write(writer)?;
355                                 (self.0 as u32).write(writer)
356                         },
357                         _ => {
358                                 0xFFu8.write(writer)?;
359                                 (self.0 as u64).write(writer)
360                         },
361                 }
362         }
363 }
364 impl Readable for BigSize {
365         #[inline]
366         fn read<R: Read>(reader: &mut R) -> Result<BigSize, DecodeError> {
367                 let n: u8 = Readable::read(reader)?;
368                 match n {
369                         0xFF => {
370                                 let x: u64 = Readable::read(reader)?;
371                                 if x < 0x100000000 {
372                                         Err(DecodeError::InvalidValue)
373                                 } else {
374                                         Ok(BigSize(x))
375                                 }
376                         }
377                         0xFE => {
378                                 let x: u32 = Readable::read(reader)?;
379                                 if x < 0x10000 {
380                                         Err(DecodeError::InvalidValue)
381                                 } else {
382                                         Ok(BigSize(x as u64))
383                                 }
384                         }
385                         0xFD => {
386                                 let x: u16 = Readable::read(reader)?;
387                                 if x < 0xFD {
388                                         Err(DecodeError::InvalidValue)
389                                 } else {
390                                         Ok(BigSize(x as u64))
391                                 }
392                         }
393                         n => Ok(BigSize(n as u64))
394                 }
395         }
396 }
397
398 /// The lightning protocol uses u16s for lengths in most cases. As our serialization framework
399 /// primarily targets that, we must as well. However, because we may serialize objects that have
400 /// more than 65K entries, we need to be able to store larger values. Thus, we define a variable
401 /// length integer here that is backwards-compatible for values < 0xffff. We treat 0xffff as
402 /// "read eight more bytes".
403 ///
404 /// To ensure we only have one valid encoding per value, we add 0xffff to values written as eight
405 /// bytes. Thus, 0xfffe is serialized as 0xfffe, whereas 0xffff is serialized as
406 /// 0xffff0000000000000000 (i.e. read-eight-bytes then zero).
407 struct CollectionLength(pub u64);
408 impl Writeable for CollectionLength {
409         #[inline]
410         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
411                 if self.0 < 0xffff {
412                         (self.0 as u16).write(writer)
413                 } else {
414                         0xffffu16.write(writer)?;
415                         (self.0 - 0xffff).write(writer)
416                 }
417         }
418 }
419
420 impl Readable for CollectionLength {
421         #[inline]
422         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
423                 let mut val: u64 = <u16 as Readable>::read(r)? as u64;
424                 if val == 0xffff {
425                         val = <u64 as Readable>::read(r)?
426                                 .checked_add(0xffff).ok_or(DecodeError::InvalidValue)?;
427                 }
428                 Ok(CollectionLength(val))
429         }
430 }
431
432 /// In TLV we occasionally send fields which only consist of, or potentially end with, a
433 /// variable-length integer which is simply truncated by skipping high zero bytes. This type
434 /// encapsulates such integers implementing [`Readable`]/[`Writeable`] for them.
435 #[cfg_attr(test, derive(PartialEq, Eq, Debug))]
436 pub(crate) struct HighZeroBytesDroppedBigSize<T>(pub T);
437
438 macro_rules! impl_writeable_primitive {
439         ($val_type:ty, $len: expr) => {
440                 impl Writeable for $val_type {
441                         #[inline]
442                         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
443                                 writer.write_all(&self.to_be_bytes())
444                         }
445                 }
446                 impl Writeable for HighZeroBytesDroppedBigSize<$val_type> {
447                         #[inline]
448                         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
449                                 // Skip any full leading 0 bytes when writing (in BE):
450                                 writer.write_all(&self.0.to_be_bytes()[(self.0.leading_zeros()/8) as usize..$len])
451                         }
452                 }
453                 impl Readable for $val_type {
454                         #[inline]
455                         fn read<R: Read>(reader: &mut R) -> Result<$val_type, DecodeError> {
456                                 let mut buf = [0; $len];
457                                 reader.read_exact(&mut buf)?;
458                                 Ok(<$val_type>::from_be_bytes(buf))
459                         }
460                 }
461                 impl Readable for HighZeroBytesDroppedBigSize<$val_type> {
462                         #[inline]
463                         fn read<R: Read>(reader: &mut R) -> Result<HighZeroBytesDroppedBigSize<$val_type>, DecodeError> {
464                                 // We need to accept short reads (read_len == 0) as "EOF" and handle them as simply
465                                 // the high bytes being dropped. To do so, we start reading into the middle of buf
466                                 // and then convert the appropriate number of bytes with extra high bytes out of
467                                 // buf.
468                                 let mut buf = [0; $len*2];
469                                 let mut read_len = reader.read(&mut buf[$len..])?;
470                                 let mut total_read_len = read_len;
471                                 while read_len != 0 && total_read_len != $len {
472                                         read_len = reader.read(&mut buf[($len + total_read_len)..])?;
473                                         total_read_len += read_len;
474                                 }
475                                 if total_read_len == 0 || buf[$len] != 0 {
476                                         let first_byte = $len - ($len - total_read_len);
477                                         let mut bytes = [0; $len];
478                                         bytes.copy_from_slice(&buf[first_byte..first_byte + $len]);
479                                         Ok(HighZeroBytesDroppedBigSize(<$val_type>::from_be_bytes(bytes)))
480                                 } else {
481                                         // If the encoding had extra zero bytes, return a failure even though we know
482                                         // what they meant (as the TLV test vectors require this)
483                                         Err(DecodeError::InvalidValue)
484                                 }
485                         }
486                 }
487                 impl From<$val_type> for HighZeroBytesDroppedBigSize<$val_type> {
488                         fn from(val: $val_type) -> Self { Self(val) }
489                 }
490         }
491 }
492
493 impl_writeable_primitive!(u128, 16);
494 impl_writeable_primitive!(u64, 8);
495 impl_writeable_primitive!(u32, 4);
496 impl_writeable_primitive!(u16, 2);
497
498 impl Writeable for u8 {
499         #[inline]
500         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
501                 writer.write_all(&[*self])
502         }
503 }
504 impl Readable for u8 {
505         #[inline]
506         fn read<R: Read>(reader: &mut R) -> Result<u8, DecodeError> {
507                 let mut buf = [0; 1];
508                 reader.read_exact(&mut buf)?;
509                 Ok(buf[0])
510         }
511 }
512
513 impl Writeable for bool {
514         #[inline]
515         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
516                 writer.write_all(&[if *self {1} else {0}])
517         }
518 }
519 impl Readable for bool {
520         #[inline]
521         fn read<R: Read>(reader: &mut R) -> Result<bool, DecodeError> {
522                 let mut buf = [0; 1];
523                 reader.read_exact(&mut buf)?;
524                 if buf[0] != 0 && buf[0] != 1 {
525                         return Err(DecodeError::InvalidValue);
526                 }
527                 Ok(buf[0] == 1)
528         }
529 }
530
531 // u8 arrays
532 macro_rules! impl_array {
533         ( $size:expr ) => (
534                 impl Writeable for [u8; $size]
535                 {
536                         #[inline]
537                         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
538                                 w.write_all(self)
539                         }
540                 }
541
542                 impl Readable for [u8; $size]
543                 {
544                         #[inline]
545                         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
546                                 let mut buf = [0u8; $size];
547                                 r.read_exact(&mut buf)?;
548                                 Ok(buf)
549                         }
550                 }
551         );
552 }
553
554 impl_array!(3); // for rgb, ISO 4712 code
555 impl_array!(4); // for IPv4
556 impl_array!(12); // for OnionV2
557 impl_array!(16); // for IPv6
558 impl_array!(32); // for channel id & hmac
559 impl_array!(PUBLIC_KEY_SIZE); // for PublicKey
560 impl_array!(64); // for ecdsa::Signature and schnorr::Signature
561 impl_array!(1300); // for OnionPacket.hop_data
562
563 impl Writeable for [u16; 8] {
564         #[inline]
565         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
566                 for v in self.iter() {
567                         w.write_all(&v.to_be_bytes())?
568                 }
569                 Ok(())
570         }
571 }
572
573 impl Readable for [u16; 8] {
574         #[inline]
575         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
576                 let mut buf = [0u8; 16];
577                 r.read_exact(&mut buf)?;
578                 let mut res = [0u16; 8];
579                 for (idx, v) in res.iter_mut().enumerate() {
580                         *v = (buf[idx] as u16) << 8 | (buf[idx + 1] as u16)
581                 }
582                 Ok(res)
583         }
584 }
585
586 /// A type for variable-length values within TLV record where the length is encoded as part of the record.
587 /// Used to prevent encoding the length twice.
588 pub struct WithoutLength<T>(pub T);
589
590 impl Writeable for WithoutLength<&String> {
591         #[inline]
592         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
593                 w.write_all(self.0.as_bytes())
594         }
595 }
596 impl Readable for WithoutLength<String> {
597         #[inline]
598         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
599                 let v: WithoutLength<Vec<u8>> = Readable::read(r)?;
600                 Ok(Self(String::from_utf8(v.0).map_err(|_| DecodeError::InvalidValue)?))
601         }
602 }
603 impl<'a> From<&'a String> for WithoutLength<&'a String> {
604         fn from(s: &'a String) -> Self { Self(s) }
605 }
606
607 impl<'a, T: Writeable> Writeable for WithoutLength<&'a Vec<T>> {
608         #[inline]
609         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
610                 for ref v in self.0.iter() {
611                         v.write(writer)?;
612                 }
613                 Ok(())
614         }
615 }
616
617 impl<T: MaybeReadable> Readable for WithoutLength<Vec<T>> {
618         #[inline]
619         fn read<R: Read>(mut reader: &mut R) -> Result<Self, DecodeError> {
620                 let mut values = Vec::new();
621                 loop {
622                         let mut track_read = ReadTrackingReader::new(&mut reader);
623                         match MaybeReadable::read(&mut track_read) {
624                                 Ok(Some(v)) => { values.push(v); },
625                                 Ok(None) => { },
626                                 // If we failed to read any bytes at all, we reached the end of our TLV
627                                 // stream and have simply exhausted all entries.
628                                 Err(ref e) if e == &DecodeError::ShortRead && !track_read.have_read => break,
629                                 Err(e) => return Err(e),
630                         }
631                 }
632                 Ok(Self(values))
633         }
634 }
635 impl<'a, T> From<&'a Vec<T>> for WithoutLength<&'a Vec<T>> {
636         fn from(v: &'a Vec<T>) -> Self { Self(v) }
637 }
638
639 #[derive(Debug)]
640 pub(crate) struct Iterable<'a, I: Iterator<Item = &'a T> + Clone, T: 'a>(pub I);
641
642 impl<'a, I: Iterator<Item = &'a T> + Clone, T: 'a + Writeable> Writeable for Iterable<'a, I, T> {
643         #[inline]
644         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
645                 for ref v in self.0.clone() {
646                         v.write(writer)?;
647                 }
648                 Ok(())
649         }
650 }
651
652 #[cfg(test)]
653 impl<'a, I: Iterator<Item = &'a T> + Clone, T: 'a + PartialEq> PartialEq for Iterable<'a, I, T> {
654         fn eq(&self, other: &Self) -> bool {
655                 self.0.clone().collect::<Vec<_>>() == other.0.clone().collect::<Vec<_>>()
656         }
657 }
658
659 macro_rules! impl_for_map {
660         ($ty: ident, $keybound: ident, $constr: expr) => {
661                 impl<K, V> Writeable for $ty<K, V>
662                         where K: Writeable + Eq + $keybound, V: Writeable
663                 {
664                         #[inline]
665                         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
666                                 CollectionLength(self.len() as u64).write(w)?;
667                                 for (key, value) in self.iter() {
668                                         key.write(w)?;
669                                         value.write(w)?;
670                                 }
671                                 Ok(())
672                         }
673                 }
674
675                 impl<K, V> Readable for $ty<K, V>
676                         where K: Readable + Eq + $keybound, V: MaybeReadable
677                 {
678                         #[inline]
679                         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
680                                 let len: CollectionLength = Readable::read(r)?;
681                                 let mut ret = $constr(len.0 as usize);
682                                 for _ in 0..len.0 {
683                                         let k = K::read(r)?;
684                                         let v_opt = V::read(r)?;
685                                         if let Some(v) = v_opt {
686                                                 if ret.insert(k, v).is_some() {
687                                                         return Err(DecodeError::InvalidValue);
688                                                 }
689                                         }
690                                 }
691                                 Ok(ret)
692                         }
693                 }
694         }
695 }
696
697 impl_for_map!(BTreeMap, Ord, |_| BTreeMap::new());
698 impl_for_map!(HashMap, Hash, |len| HashMap::with_capacity(len));
699
700 // HashSet
701 impl<T> Writeable for HashSet<T>
702 where T: Writeable + Eq + Hash
703 {
704         #[inline]
705         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
706                 CollectionLength(self.len() as u64).write(w)?;
707                 for item in self.iter() {
708                         item.write(w)?;
709                 }
710                 Ok(())
711         }
712 }
713
714 impl<T> Readable for HashSet<T>
715 where T: Readable + Eq + Hash
716 {
717         #[inline]
718         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
719                 let len: CollectionLength = Readable::read(r)?;
720                 let mut ret = HashSet::with_capacity(cmp::min(len.0 as usize, MAX_BUF_SIZE / core::mem::size_of::<T>()));
721                 for _ in 0..len.0 {
722                         if !ret.insert(T::read(r)?) {
723                                 return Err(DecodeError::InvalidValue)
724                         }
725                 }
726                 Ok(ret)
727         }
728 }
729
730 // Vectors
731 macro_rules! impl_for_vec {
732         ($ty: ty $(, $name: ident)*) => {
733                 impl<$($name : Writeable),*> Writeable for Vec<$ty> {
734                         #[inline]
735                         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
736                                 CollectionLength(self.len() as u64).write(w)?;
737                                 for elem in self.iter() {
738                                         elem.write(w)?;
739                                 }
740                                 Ok(())
741                         }
742                 }
743
744                 impl<$($name : Readable),*> Readable for Vec<$ty> {
745                         #[inline]
746                         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
747                                 let len: CollectionLength = Readable::read(r)?;
748                                 let mut ret = Vec::with_capacity(cmp::min(len.0 as usize, MAX_BUF_SIZE / core::mem::size_of::<$ty>()));
749                                 for _ in 0..len.0 {
750                                         if let Some(val) = MaybeReadable::read(r)? {
751                                                 ret.push(val);
752                                         }
753                                 }
754                                 Ok(ret)
755                         }
756                 }
757         }
758 }
759
760 impl Writeable for Vec<u8> {
761         #[inline]
762         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
763                 CollectionLength(self.len() as u64).write(w)?;
764                 w.write_all(&self)
765         }
766 }
767
768 impl Readable for Vec<u8> {
769         #[inline]
770         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
771                 let mut len: CollectionLength = Readable::read(r)?;
772                 let mut ret = Vec::new();
773                 while len.0 > 0 {
774                         let readamt = cmp::min(len.0 as usize, MAX_BUF_SIZE);
775                         let readstart = ret.len();
776                         ret.resize(readstart + readamt, 0);
777                         r.read_exact(&mut ret[readstart..])?;
778                         len.0 -= readamt as u64;
779                 }
780                 Ok(ret)
781         }
782 }
783
784 impl_for_vec!(ecdsa::Signature);
785 impl_for_vec!(crate::ln::channelmanager::MonitorUpdateCompletionAction);
786 impl_for_vec!((A, B), A, B);
787
788 impl Writeable for Script {
789         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
790                 (self.len() as u16).write(w)?;
791                 w.write_all(self.as_bytes())
792         }
793 }
794
795 impl Readable for Script {
796         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
797                 let len = <u16 as Readable>::read(r)? as usize;
798                 let mut buf = vec![0; len];
799                 r.read_exact(&mut buf)?;
800                 Ok(Script::from(buf))
801         }
802 }
803
804 impl Writeable for PublicKey {
805         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
806                 self.serialize().write(w)
807         }
808         #[inline]
809         fn serialized_length(&self) -> usize {
810                 PUBLIC_KEY_SIZE
811         }
812 }
813
814 impl Readable for PublicKey {
815         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
816                 let buf: [u8; PUBLIC_KEY_SIZE] = Readable::read(r)?;
817                 match PublicKey::from_slice(&buf) {
818                         Ok(key) => Ok(key),
819                         Err(_) => return Err(DecodeError::InvalidValue),
820                 }
821         }
822 }
823
824 impl Writeable for SecretKey {
825         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
826                 let mut ser = [0; SECRET_KEY_SIZE];
827                 ser.copy_from_slice(&self[..]);
828                 ser.write(w)
829         }
830         #[inline]
831         fn serialized_length(&self) -> usize {
832                 SECRET_KEY_SIZE
833         }
834 }
835
836 impl Readable for SecretKey {
837         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
838                 let buf: [u8; SECRET_KEY_SIZE] = Readable::read(r)?;
839                 match SecretKey::from_slice(&buf) {
840                         Ok(key) => Ok(key),
841                         Err(_) => return Err(DecodeError::InvalidValue),
842                 }
843         }
844 }
845
846 impl Writeable for Sha256dHash {
847         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
848                 w.write_all(&self[..])
849         }
850 }
851
852 impl Readable for Sha256dHash {
853         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
854                 use bitcoin::hashes::Hash;
855
856                 let buf: [u8; 32] = Readable::read(r)?;
857                 Ok(Sha256dHash::from_slice(&buf[..]).unwrap())
858         }
859 }
860
861 impl Writeable for ecdsa::Signature {
862         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
863                 self.serialize_compact().write(w)
864         }
865 }
866
867 impl Readable for ecdsa::Signature {
868         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
869                 let buf: [u8; COMPACT_SIGNATURE_SIZE] = Readable::read(r)?;
870                 match ecdsa::Signature::from_compact(&buf) {
871                         Ok(sig) => Ok(sig),
872                         Err(_) => return Err(DecodeError::InvalidValue),
873                 }
874         }
875 }
876
877 impl Writeable for schnorr::Signature {
878         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
879                 self.as_ref().write(w)
880         }
881 }
882
883 impl Readable for schnorr::Signature {
884         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
885                 let buf: [u8; SCHNORR_SIGNATURE_SIZE] = Readable::read(r)?;
886                 match schnorr::Signature::from_slice(&buf) {
887                         Ok(sig) => Ok(sig),
888                         Err(_) => return Err(DecodeError::InvalidValue),
889                 }
890         }
891 }
892
893 impl Writeable for PaymentPreimage {
894         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
895                 self.0.write(w)
896         }
897 }
898
899 impl Readable for PaymentPreimage {
900         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
901                 let buf: [u8; 32] = Readable::read(r)?;
902                 Ok(PaymentPreimage(buf))
903         }
904 }
905
906 impl Writeable for PaymentHash {
907         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
908                 self.0.write(w)
909         }
910 }
911
912 impl Readable for PaymentHash {
913         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
914                 let buf: [u8; 32] = Readable::read(r)?;
915                 Ok(PaymentHash(buf))
916         }
917 }
918
919 impl Writeable for PaymentSecret {
920         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
921                 self.0.write(w)
922         }
923 }
924
925 impl Readable for PaymentSecret {
926         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
927                 let buf: [u8; 32] = Readable::read(r)?;
928                 Ok(PaymentSecret(buf))
929         }
930 }
931
932 impl<T: Writeable> Writeable for Box<T> {
933         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
934                 T::write(&**self, w)
935         }
936 }
937
938 impl<T: Readable> Readable for Box<T> {
939         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
940                 Ok(Box::new(Readable::read(r)?))
941         }
942 }
943
944 impl<T: Writeable> Writeable for Option<T> {
945         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
946                 match *self {
947                         None => 0u8.write(w)?,
948                         Some(ref data) => {
949                                 BigSize(data.serialized_length() as u64 + 1).write(w)?;
950                                 data.write(w)?;
951                         }
952                 }
953                 Ok(())
954         }
955 }
956
957 impl<T: Readable> Readable for Option<T>
958 {
959         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
960                 let len: BigSize = Readable::read(r)?;
961                 match len.0 {
962                         0 => Ok(None),
963                         len => {
964                                 let mut reader = FixedLengthReader::new(r, len - 1);
965                                 Ok(Some(Readable::read(&mut reader)?))
966                         }
967                 }
968         }
969 }
970
971 impl Writeable for Txid {
972         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
973                 w.write_all(&self[..])
974         }
975 }
976
977 impl Readable for Txid {
978         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
979                 use bitcoin::hashes::Hash;
980
981                 let buf: [u8; 32] = Readable::read(r)?;
982                 Ok(Txid::from_slice(&buf[..]).unwrap())
983         }
984 }
985
986 impl Writeable for BlockHash {
987         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
988                 w.write_all(&self[..])
989         }
990 }
991
992 impl Readable for BlockHash {
993         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
994                 use bitcoin::hashes::Hash;
995
996                 let buf: [u8; 32] = Readable::read(r)?;
997                 Ok(BlockHash::from_slice(&buf[..]).unwrap())
998         }
999 }
1000
1001 impl Writeable for ChainHash {
1002         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1003                 w.write_all(self.as_bytes())
1004         }
1005 }
1006
1007 impl Readable for ChainHash {
1008         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1009                 let buf: [u8; 32] = Readable::read(r)?;
1010                 Ok(ChainHash::from(&buf[..]))
1011         }
1012 }
1013
1014 impl Writeable for OutPoint {
1015         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1016                 self.txid.write(w)?;
1017                 self.vout.write(w)?;
1018                 Ok(())
1019         }
1020 }
1021
1022 impl Readable for OutPoint {
1023         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1024                 let txid = Readable::read(r)?;
1025                 let vout = Readable::read(r)?;
1026                 Ok(OutPoint {
1027                         txid,
1028                         vout,
1029                 })
1030         }
1031 }
1032
1033 macro_rules! impl_consensus_ser {
1034         ($bitcoin_type: ty) => {
1035                 impl Writeable for $bitcoin_type {
1036                         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1037                                 match self.consensus_encode(&mut WriterWriteAdaptor(writer)) {
1038                                         Ok(_) => Ok(()),
1039                                         Err(e) => Err(e),
1040                                 }
1041                         }
1042                 }
1043
1044                 impl Readable for $bitcoin_type {
1045                         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1046                                 match consensus::encode::Decodable::consensus_decode(r) {
1047                                         Ok(t) => Ok(t),
1048                                         Err(consensus::encode::Error::Io(ref e)) if e.kind() == io::ErrorKind::UnexpectedEof => Err(DecodeError::ShortRead),
1049                                         Err(consensus::encode::Error::Io(e)) => Err(DecodeError::Io(e.kind())),
1050                                         Err(_) => Err(DecodeError::InvalidValue),
1051                                 }
1052                         }
1053                 }
1054         }
1055 }
1056 impl_consensus_ser!(Transaction);
1057 impl_consensus_ser!(TxOut);
1058
1059 impl<T: Readable> Readable for Mutex<T> {
1060         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1061                 let t: T = Readable::read(r)?;
1062                 Ok(Mutex::new(t))
1063         }
1064 }
1065 impl<T: Writeable> Writeable for Mutex<T> {
1066         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1067                 self.lock().unwrap().write(w)
1068         }
1069 }
1070
1071 impl<A: Readable, B: Readable> Readable for (A, B) {
1072         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1073                 let a: A = Readable::read(r)?;
1074                 let b: B = Readable::read(r)?;
1075                 Ok((a, b))
1076         }
1077 }
1078 impl<A: Writeable, B: Writeable> Writeable for (A, B) {
1079         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1080                 self.0.write(w)?;
1081                 self.1.write(w)
1082         }
1083 }
1084
1085 impl<A: Readable, B: Readable, C: Readable> Readable for (A, B, C) {
1086         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1087                 let a: A = Readable::read(r)?;
1088                 let b: B = Readable::read(r)?;
1089                 let c: C = Readable::read(r)?;
1090                 Ok((a, b, c))
1091         }
1092 }
1093 impl<A: Writeable, B: Writeable, C: Writeable> Writeable for (A, B, C) {
1094         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1095                 self.0.write(w)?;
1096                 self.1.write(w)?;
1097                 self.2.write(w)
1098         }
1099 }
1100
1101 impl<A: Readable, B: Readable, C: Readable, D: Readable> Readable for (A, B, C, D) {
1102         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1103                 let a: A = Readable::read(r)?;
1104                 let b: B = Readable::read(r)?;
1105                 let c: C = Readable::read(r)?;
1106                 let d: D = Readable::read(r)?;
1107                 Ok((a, b, c, d))
1108         }
1109 }
1110 impl<A: Writeable, B: Writeable, C: Writeable, D: Writeable> Writeable for (A, B, C, D) {
1111         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1112                 self.0.write(w)?;
1113                 self.1.write(w)?;
1114                 self.2.write(w)?;
1115                 self.3.write(w)
1116         }
1117 }
1118
1119 impl Writeable for () {
1120         fn write<W: Writer>(&self, _: &mut W) -> Result<(), io::Error> {
1121                 Ok(())
1122         }
1123 }
1124 impl Readable for () {
1125         fn read<R: Read>(_r: &mut R) -> Result<Self, DecodeError> {
1126                 Ok(())
1127         }
1128 }
1129
1130 impl Writeable for String {
1131         #[inline]
1132         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1133                 CollectionLength(self.len() as u64).write(w)?;
1134                 w.write_all(self.as_bytes())
1135         }
1136 }
1137 impl Readable for String {
1138         #[inline]
1139         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1140                 let v: Vec<u8> = Readable::read(r)?;
1141                 let ret = String::from_utf8(v).map_err(|_| DecodeError::InvalidValue)?;
1142                 Ok(ret)
1143         }
1144 }
1145
1146 /// Represents a hostname for serialization purposes.
1147 /// Only the character set and length will be validated.
1148 /// The character set consists of ASCII alphanumeric characters, hyphens, and periods.
1149 /// Its length is guaranteed to be representable by a single byte.
1150 /// This serialization is used by [`BOLT 7`] hostnames.
1151 ///
1152 /// [`BOLT 7`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md
1153 #[derive(Clone, Debug, PartialEq, Eq)]
1154 pub struct Hostname(String);
1155 impl Hostname {
1156         /// Returns the length of the hostname.
1157         pub fn len(&self) -> u8 {
1158                 (&self.0).len() as u8
1159         }
1160 }
1161 impl Deref for Hostname {
1162         type Target = String;
1163
1164         fn deref(&self) -> &Self::Target {
1165                 &self.0
1166         }
1167 }
1168 impl From<Hostname> for String {
1169         fn from(hostname: Hostname) -> Self {
1170                 hostname.0
1171         }
1172 }
1173 impl TryFrom<Vec<u8>> for Hostname {
1174         type Error = ();
1175
1176         fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
1177                 if let Ok(s) = String::from_utf8(bytes) {
1178                         Hostname::try_from(s)
1179                 } else {
1180                         Err(())
1181                 }
1182         }
1183 }
1184 impl TryFrom<String> for Hostname {
1185         type Error = ();
1186
1187         fn try_from(s: String) -> Result<Self, Self::Error> {
1188                 if s.len() <= 255 && s.chars().all(|c|
1189                         c.is_ascii_alphanumeric() ||
1190                         c == '.' ||
1191                         c == '-'
1192                 ) {
1193                         Ok(Hostname(s))
1194                 } else {
1195                         Err(())
1196                 }
1197         }
1198 }
1199 impl Writeable for Hostname {
1200         #[inline]
1201         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1202                 self.len().write(w)?;
1203                 w.write_all(self.as_bytes())
1204         }
1205 }
1206 impl Readable for Hostname {
1207         #[inline]
1208         fn read<R: Read>(r: &mut R) -> Result<Hostname, DecodeError> {
1209                 let len: u8 = Readable::read(r)?;
1210                 let mut vec = Vec::with_capacity(len.into());
1211                 vec.resize(len.into(), 0);
1212                 r.read_exact(&mut vec)?;
1213                 Hostname::try_from(vec).map_err(|_| DecodeError::InvalidValue)
1214         }
1215 }
1216
1217 impl Writeable for Duration {
1218         #[inline]
1219         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1220                 self.as_secs().write(w)?;
1221                 self.subsec_nanos().write(w)
1222         }
1223 }
1224 impl Readable for Duration {
1225         #[inline]
1226         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1227                 let secs = Readable::read(r)?;
1228                 let nanos = Readable::read(r)?;
1229                 Ok(Duration::new(secs, nanos))
1230         }
1231 }
1232
1233 #[cfg(test)]
1234 mod tests {
1235         use core::convert::TryFrom;
1236         use crate::util::ser::{Readable, Hostname, Writeable};
1237
1238         #[test]
1239         fn hostname_conversion() {
1240                 assert_eq!(Hostname::try_from(String::from("a-test.com")).unwrap().as_str(), "a-test.com");
1241
1242                 assert!(Hostname::try_from(String::from("\"")).is_err());
1243                 assert!(Hostname::try_from(String::from("$")).is_err());
1244                 assert!(Hostname::try_from(String::from("⚡")).is_err());
1245                 let mut large_vec = Vec::with_capacity(256);
1246                 large_vec.resize(256, b'A');
1247                 assert!(Hostname::try_from(String::from_utf8(large_vec).unwrap()).is_err());
1248         }
1249
1250         #[test]
1251         fn hostname_serialization() {
1252                 let hostname = Hostname::try_from(String::from("test")).unwrap();
1253                 let mut buf: Vec<u8> = Vec::new();
1254                 hostname.write(&mut buf).unwrap();
1255                 assert_eq!(Hostname::read(&mut buf.as_slice()).unwrap().as_str(), "test");
1256         }
1257 }