Merge pull request #2006 from TheBlueMatt/2023-02-no-recursive-read-locks
[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>(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 impl<A, T: ReadableArgs<A>> ReadableArgs<A> for RequiredWrapper<T> {
300         #[inline]
301         fn read<R: Read>(reader: &mut R, args: A) -> Result<Self, DecodeError> {
302                 Ok(Self(Some(ReadableArgs::read(reader, args)?)))
303         }
304 }
305 /// When handling `default_values`, we want to map the default-value T directly
306 /// to a `RequiredWrapper<T>` in a way that works for `field: T = t;` as
307 /// well. Thus, we assume `Into<T> for T` does nothing and use that.
308 impl<T> From<T> for RequiredWrapper<T> {
309         fn from(t: T) -> RequiredWrapper<T> { RequiredWrapper(Some(t)) }
310 }
311
312 /// Wrapper to read a required (non-optional) TLV record that may have been upgraded without
313 /// backwards compat.
314 pub struct UpgradableRequired<T: MaybeReadable>(pub Option<T>);
315 impl<T: MaybeReadable> MaybeReadable for UpgradableRequired<T> {
316         #[inline]
317         fn read<R: Read>(reader: &mut R) -> Result<Option<Self>, DecodeError> {
318                 let tlv = MaybeReadable::read(reader)?;
319                 if let Some(tlv) = tlv { return Ok(Some(Self(Some(tlv)))) }
320                 Ok(None)
321         }
322 }
323
324 pub(crate) struct U48(pub u64);
325 impl Writeable for U48 {
326         #[inline]
327         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
328                 writer.write_all(&be48_to_array(self.0))
329         }
330 }
331 impl Readable for U48 {
332         #[inline]
333         fn read<R: Read>(reader: &mut R) -> Result<U48, DecodeError> {
334                 let mut buf = [0; 6];
335                 reader.read_exact(&mut buf)?;
336                 Ok(U48(slice_to_be48(&buf)))
337         }
338 }
339
340 /// Lightning TLV uses a custom variable-length integer called `BigSize`. It is similar to Bitcoin's
341 /// variable-length integers except that it is serialized in big-endian instead of little-endian.
342 ///
343 /// Like Bitcoin's variable-length integer, it exhibits ambiguity in that certain values can be
344 /// encoded in several different ways, which we must check for at deserialization-time. Thus, if
345 /// you're looking for an example of a variable-length integer to use for your own project, move
346 /// along, this is a rather poor design.
347 pub struct BigSize(pub u64);
348 impl Writeable for BigSize {
349         #[inline]
350         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
351                 match self.0 {
352                         0...0xFC => {
353                                 (self.0 as u8).write(writer)
354                         },
355                         0xFD...0xFFFF => {
356                                 0xFDu8.write(writer)?;
357                                 (self.0 as u16).write(writer)
358                         },
359                         0x10000...0xFFFFFFFF => {
360                                 0xFEu8.write(writer)?;
361                                 (self.0 as u32).write(writer)
362                         },
363                         _ => {
364                                 0xFFu8.write(writer)?;
365                                 (self.0 as u64).write(writer)
366                         },
367                 }
368         }
369 }
370 impl Readable for BigSize {
371         #[inline]
372         fn read<R: Read>(reader: &mut R) -> Result<BigSize, DecodeError> {
373                 let n: u8 = Readable::read(reader)?;
374                 match n {
375                         0xFF => {
376                                 let x: u64 = Readable::read(reader)?;
377                                 if x < 0x100000000 {
378                                         Err(DecodeError::InvalidValue)
379                                 } else {
380                                         Ok(BigSize(x))
381                                 }
382                         }
383                         0xFE => {
384                                 let x: u32 = Readable::read(reader)?;
385                                 if x < 0x10000 {
386                                         Err(DecodeError::InvalidValue)
387                                 } else {
388                                         Ok(BigSize(x as u64))
389                                 }
390                         }
391                         0xFD => {
392                                 let x: u16 = Readable::read(reader)?;
393                                 if x < 0xFD {
394                                         Err(DecodeError::InvalidValue)
395                                 } else {
396                                         Ok(BigSize(x as u64))
397                                 }
398                         }
399                         n => Ok(BigSize(n as u64))
400                 }
401         }
402 }
403
404 /// The lightning protocol uses u16s for lengths in most cases. As our serialization framework
405 /// primarily targets that, we must as well. However, because we may serialize objects that have
406 /// more than 65K entries, we need to be able to store larger values. Thus, we define a variable
407 /// length integer here that is backwards-compatible for values < 0xffff. We treat 0xffff as
408 /// "read eight more bytes".
409 ///
410 /// To ensure we only have one valid encoding per value, we add 0xffff to values written as eight
411 /// bytes. Thus, 0xfffe is serialized as 0xfffe, whereas 0xffff is serialized as
412 /// 0xffff0000000000000000 (i.e. read-eight-bytes then zero).
413 struct CollectionLength(pub u64);
414 impl Writeable for CollectionLength {
415         #[inline]
416         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
417                 if self.0 < 0xffff {
418                         (self.0 as u16).write(writer)
419                 } else {
420                         0xffffu16.write(writer)?;
421                         (self.0 - 0xffff).write(writer)
422                 }
423         }
424 }
425
426 impl Readable for CollectionLength {
427         #[inline]
428         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
429                 let mut val: u64 = <u16 as Readable>::read(r)? as u64;
430                 if val == 0xffff {
431                         val = <u64 as Readable>::read(r)?
432                                 .checked_add(0xffff).ok_or(DecodeError::InvalidValue)?;
433                 }
434                 Ok(CollectionLength(val))
435         }
436 }
437
438 /// In TLV we occasionally send fields which only consist of, or potentially end with, a
439 /// variable-length integer which is simply truncated by skipping high zero bytes. This type
440 /// encapsulates such integers implementing [`Readable`]/[`Writeable`] for them.
441 #[cfg_attr(test, derive(PartialEq, Eq, Debug))]
442 pub(crate) struct HighZeroBytesDroppedBigSize<T>(pub T);
443
444 macro_rules! impl_writeable_primitive {
445         ($val_type:ty, $len: expr) => {
446                 impl Writeable for $val_type {
447                         #[inline]
448                         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
449                                 writer.write_all(&self.to_be_bytes())
450                         }
451                 }
452                 impl Writeable for HighZeroBytesDroppedBigSize<$val_type> {
453                         #[inline]
454                         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
455                                 // Skip any full leading 0 bytes when writing (in BE):
456                                 writer.write_all(&self.0.to_be_bytes()[(self.0.leading_zeros()/8) as usize..$len])
457                         }
458                 }
459                 impl Readable for $val_type {
460                         #[inline]
461                         fn read<R: Read>(reader: &mut R) -> Result<$val_type, DecodeError> {
462                                 let mut buf = [0; $len];
463                                 reader.read_exact(&mut buf)?;
464                                 Ok(<$val_type>::from_be_bytes(buf))
465                         }
466                 }
467                 impl Readable for HighZeroBytesDroppedBigSize<$val_type> {
468                         #[inline]
469                         fn read<R: Read>(reader: &mut R) -> Result<HighZeroBytesDroppedBigSize<$val_type>, DecodeError> {
470                                 // We need to accept short reads (read_len == 0) as "EOF" and handle them as simply
471                                 // the high bytes being dropped. To do so, we start reading into the middle of buf
472                                 // and then convert the appropriate number of bytes with extra high bytes out of
473                                 // buf.
474                                 let mut buf = [0; $len*2];
475                                 let mut read_len = reader.read(&mut buf[$len..])?;
476                                 let mut total_read_len = read_len;
477                                 while read_len != 0 && total_read_len != $len {
478                                         read_len = reader.read(&mut buf[($len + total_read_len)..])?;
479                                         total_read_len += read_len;
480                                 }
481                                 if total_read_len == 0 || buf[$len] != 0 {
482                                         let first_byte = $len - ($len - total_read_len);
483                                         let mut bytes = [0; $len];
484                                         bytes.copy_from_slice(&buf[first_byte..first_byte + $len]);
485                                         Ok(HighZeroBytesDroppedBigSize(<$val_type>::from_be_bytes(bytes)))
486                                 } else {
487                                         // If the encoding had extra zero bytes, return a failure even though we know
488                                         // what they meant (as the TLV test vectors require this)
489                                         Err(DecodeError::InvalidValue)
490                                 }
491                         }
492                 }
493                 impl From<$val_type> for HighZeroBytesDroppedBigSize<$val_type> {
494                         fn from(val: $val_type) -> Self { Self(val) }
495                 }
496         }
497 }
498
499 impl_writeable_primitive!(u128, 16);
500 impl_writeable_primitive!(u64, 8);
501 impl_writeable_primitive!(u32, 4);
502 impl_writeable_primitive!(u16, 2);
503
504 impl Writeable for u8 {
505         #[inline]
506         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
507                 writer.write_all(&[*self])
508         }
509 }
510 impl Readable for u8 {
511         #[inline]
512         fn read<R: Read>(reader: &mut R) -> Result<u8, DecodeError> {
513                 let mut buf = [0; 1];
514                 reader.read_exact(&mut buf)?;
515                 Ok(buf[0])
516         }
517 }
518
519 impl Writeable for bool {
520         #[inline]
521         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
522                 writer.write_all(&[if *self {1} else {0}])
523         }
524 }
525 impl Readable for bool {
526         #[inline]
527         fn read<R: Read>(reader: &mut R) -> Result<bool, DecodeError> {
528                 let mut buf = [0; 1];
529                 reader.read_exact(&mut buf)?;
530                 if buf[0] != 0 && buf[0] != 1 {
531                         return Err(DecodeError::InvalidValue);
532                 }
533                 Ok(buf[0] == 1)
534         }
535 }
536
537 // u8 arrays
538 macro_rules! impl_array {
539         ( $size:expr ) => (
540                 impl Writeable for [u8; $size]
541                 {
542                         #[inline]
543                         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
544                                 w.write_all(self)
545                         }
546                 }
547
548                 impl Readable for [u8; $size]
549                 {
550                         #[inline]
551                         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
552                                 let mut buf = [0u8; $size];
553                                 r.read_exact(&mut buf)?;
554                                 Ok(buf)
555                         }
556                 }
557         );
558 }
559
560 impl_array!(3); // for rgb, ISO 4712 code
561 impl_array!(4); // for IPv4
562 impl_array!(12); // for OnionV2
563 impl_array!(16); // for IPv6
564 impl_array!(32); // for channel id & hmac
565 impl_array!(PUBLIC_KEY_SIZE); // for PublicKey
566 impl_array!(64); // for ecdsa::Signature and schnorr::Signature
567 impl_array!(1300); // for OnionPacket.hop_data
568
569 impl Writeable for [u16; 8] {
570         #[inline]
571         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
572                 for v in self.iter() {
573                         w.write_all(&v.to_be_bytes())?
574                 }
575                 Ok(())
576         }
577 }
578
579 impl Readable for [u16; 8] {
580         #[inline]
581         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
582                 let mut buf = [0u8; 16];
583                 r.read_exact(&mut buf)?;
584                 let mut res = [0u16; 8];
585                 for (idx, v) in res.iter_mut().enumerate() {
586                         *v = (buf[idx] as u16) << 8 | (buf[idx + 1] as u16)
587                 }
588                 Ok(res)
589         }
590 }
591
592 /// A type for variable-length values within TLV record where the length is encoded as part of the record.
593 /// Used to prevent encoding the length twice.
594 pub struct WithoutLength<T>(pub T);
595
596 impl Writeable for WithoutLength<&String> {
597         #[inline]
598         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
599                 w.write_all(self.0.as_bytes())
600         }
601 }
602 impl Readable for WithoutLength<String> {
603         #[inline]
604         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
605                 let v: WithoutLength<Vec<u8>> = Readable::read(r)?;
606                 Ok(Self(String::from_utf8(v.0).map_err(|_| DecodeError::InvalidValue)?))
607         }
608 }
609 impl<'a> From<&'a String> for WithoutLength<&'a String> {
610         fn from(s: &'a String) -> Self { Self(s) }
611 }
612
613 impl<'a, T: Writeable> Writeable for WithoutLength<&'a Vec<T>> {
614         #[inline]
615         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
616                 for ref v in self.0.iter() {
617                         v.write(writer)?;
618                 }
619                 Ok(())
620         }
621 }
622
623 impl<T: MaybeReadable> Readable for WithoutLength<Vec<T>> {
624         #[inline]
625         fn read<R: Read>(mut reader: &mut R) -> Result<Self, DecodeError> {
626                 let mut values = Vec::new();
627                 loop {
628                         let mut track_read = ReadTrackingReader::new(&mut reader);
629                         match MaybeReadable::read(&mut track_read) {
630                                 Ok(Some(v)) => { values.push(v); },
631                                 Ok(None) => { },
632                                 // If we failed to read any bytes at all, we reached the end of our TLV
633                                 // stream and have simply exhausted all entries.
634                                 Err(ref e) if e == &DecodeError::ShortRead && !track_read.have_read => break,
635                                 Err(e) => return Err(e),
636                         }
637                 }
638                 Ok(Self(values))
639         }
640 }
641 impl<'a, T> From<&'a Vec<T>> for WithoutLength<&'a Vec<T>> {
642         fn from(v: &'a Vec<T>) -> Self { Self(v) }
643 }
644
645 #[derive(Debug)]
646 pub(crate) struct Iterable<'a, I: Iterator<Item = &'a T> + Clone, T: 'a>(pub I);
647
648 impl<'a, I: Iterator<Item = &'a T> + Clone, T: 'a + Writeable> Writeable for Iterable<'a, I, T> {
649         #[inline]
650         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
651                 for ref v in self.0.clone() {
652                         v.write(writer)?;
653                 }
654                 Ok(())
655         }
656 }
657
658 #[cfg(test)]
659 impl<'a, I: Iterator<Item = &'a T> + Clone, T: 'a + PartialEq> PartialEq for Iterable<'a, I, T> {
660         fn eq(&self, other: &Self) -> bool {
661                 self.0.clone().collect::<Vec<_>>() == other.0.clone().collect::<Vec<_>>()
662         }
663 }
664
665 macro_rules! impl_for_map {
666         ($ty: ident, $keybound: ident, $constr: expr) => {
667                 impl<K, V> Writeable for $ty<K, V>
668                         where K: Writeable + Eq + $keybound, V: Writeable
669                 {
670                         #[inline]
671                         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
672                                 CollectionLength(self.len() as u64).write(w)?;
673                                 for (key, value) in self.iter() {
674                                         key.write(w)?;
675                                         value.write(w)?;
676                                 }
677                                 Ok(())
678                         }
679                 }
680
681                 impl<K, V> Readable for $ty<K, V>
682                         where K: Readable + Eq + $keybound, V: MaybeReadable
683                 {
684                         #[inline]
685                         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
686                                 let len: CollectionLength = Readable::read(r)?;
687                                 let mut ret = $constr(len.0 as usize);
688                                 for _ in 0..len.0 {
689                                         let k = K::read(r)?;
690                                         let v_opt = V::read(r)?;
691                                         if let Some(v) = v_opt {
692                                                 if ret.insert(k, v).is_some() {
693                                                         return Err(DecodeError::InvalidValue);
694                                                 }
695                                         }
696                                 }
697                                 Ok(ret)
698                         }
699                 }
700         }
701 }
702
703 impl_for_map!(BTreeMap, Ord, |_| BTreeMap::new());
704 impl_for_map!(HashMap, Hash, |len| HashMap::with_capacity(len));
705
706 // HashSet
707 impl<T> Writeable for HashSet<T>
708 where T: Writeable + Eq + Hash
709 {
710         #[inline]
711         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
712                 CollectionLength(self.len() as u64).write(w)?;
713                 for item in self.iter() {
714                         item.write(w)?;
715                 }
716                 Ok(())
717         }
718 }
719
720 impl<T> Readable for HashSet<T>
721 where T: Readable + Eq + Hash
722 {
723         #[inline]
724         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
725                 let len: CollectionLength = Readable::read(r)?;
726                 let mut ret = HashSet::with_capacity(cmp::min(len.0 as usize, MAX_BUF_SIZE / core::mem::size_of::<T>()));
727                 for _ in 0..len.0 {
728                         if !ret.insert(T::read(r)?) {
729                                 return Err(DecodeError::InvalidValue)
730                         }
731                 }
732                 Ok(ret)
733         }
734 }
735
736 // Vectors
737 macro_rules! impl_for_vec {
738         ($ty: ty $(, $name: ident)*) => {
739                 impl<$($name : Writeable),*> Writeable for Vec<$ty> {
740                         #[inline]
741                         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
742                                 CollectionLength(self.len() as u64).write(w)?;
743                                 for elem in self.iter() {
744                                         elem.write(w)?;
745                                 }
746                                 Ok(())
747                         }
748                 }
749
750                 impl<$($name : Readable),*> Readable for Vec<$ty> {
751                         #[inline]
752                         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
753                                 let len: CollectionLength = Readable::read(r)?;
754                                 let mut ret = Vec::with_capacity(cmp::min(len.0 as usize, MAX_BUF_SIZE / core::mem::size_of::<$ty>()));
755                                 for _ in 0..len.0 {
756                                         if let Some(val) = MaybeReadable::read(r)? {
757                                                 ret.push(val);
758                                         }
759                                 }
760                                 Ok(ret)
761                         }
762                 }
763         }
764 }
765
766 impl Writeable for Vec<u8> {
767         #[inline]
768         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
769                 CollectionLength(self.len() as u64).write(w)?;
770                 w.write_all(&self)
771         }
772 }
773
774 impl Readable for Vec<u8> {
775         #[inline]
776         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
777                 let mut len: CollectionLength = Readable::read(r)?;
778                 let mut ret = Vec::new();
779                 while len.0 > 0 {
780                         let readamt = cmp::min(len.0 as usize, MAX_BUF_SIZE);
781                         let readstart = ret.len();
782                         ret.resize(readstart + readamt, 0);
783                         r.read_exact(&mut ret[readstart..])?;
784                         len.0 -= readamt as u64;
785                 }
786                 Ok(ret)
787         }
788 }
789
790 impl_for_vec!(ecdsa::Signature);
791 impl_for_vec!(crate::ln::channelmanager::MonitorUpdateCompletionAction);
792 impl_for_vec!((A, B), A, B);
793
794 impl Writeable for Script {
795         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
796                 (self.len() as u16).write(w)?;
797                 w.write_all(self.as_bytes())
798         }
799 }
800
801 impl Readable for Script {
802         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
803                 let len = <u16 as Readable>::read(r)? as usize;
804                 let mut buf = vec![0; len];
805                 r.read_exact(&mut buf)?;
806                 Ok(Script::from(buf))
807         }
808 }
809
810 impl Writeable for PublicKey {
811         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
812                 self.serialize().write(w)
813         }
814         #[inline]
815         fn serialized_length(&self) -> usize {
816                 PUBLIC_KEY_SIZE
817         }
818 }
819
820 impl Readable for PublicKey {
821         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
822                 let buf: [u8; PUBLIC_KEY_SIZE] = Readable::read(r)?;
823                 match PublicKey::from_slice(&buf) {
824                         Ok(key) => Ok(key),
825                         Err(_) => return Err(DecodeError::InvalidValue),
826                 }
827         }
828 }
829
830 impl Writeable for SecretKey {
831         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
832                 let mut ser = [0; SECRET_KEY_SIZE];
833                 ser.copy_from_slice(&self[..]);
834                 ser.write(w)
835         }
836         #[inline]
837         fn serialized_length(&self) -> usize {
838                 SECRET_KEY_SIZE
839         }
840 }
841
842 impl Readable for SecretKey {
843         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
844                 let buf: [u8; SECRET_KEY_SIZE] = Readable::read(r)?;
845                 match SecretKey::from_slice(&buf) {
846                         Ok(key) => Ok(key),
847                         Err(_) => return Err(DecodeError::InvalidValue),
848                 }
849         }
850 }
851
852 impl Writeable for Sha256dHash {
853         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
854                 w.write_all(&self[..])
855         }
856 }
857
858 impl Readable for Sha256dHash {
859         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
860                 use bitcoin::hashes::Hash;
861
862                 let buf: [u8; 32] = Readable::read(r)?;
863                 Ok(Sha256dHash::from_slice(&buf[..]).unwrap())
864         }
865 }
866
867 impl Writeable for ecdsa::Signature {
868         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
869                 self.serialize_compact().write(w)
870         }
871 }
872
873 impl Readable for ecdsa::Signature {
874         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
875                 let buf: [u8; COMPACT_SIGNATURE_SIZE] = Readable::read(r)?;
876                 match ecdsa::Signature::from_compact(&buf) {
877                         Ok(sig) => Ok(sig),
878                         Err(_) => return Err(DecodeError::InvalidValue),
879                 }
880         }
881 }
882
883 impl Writeable for schnorr::Signature {
884         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
885                 self.as_ref().write(w)
886         }
887 }
888
889 impl Readable for schnorr::Signature {
890         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
891                 let buf: [u8; SCHNORR_SIGNATURE_SIZE] = Readable::read(r)?;
892                 match schnorr::Signature::from_slice(&buf) {
893                         Ok(sig) => Ok(sig),
894                         Err(_) => return Err(DecodeError::InvalidValue),
895                 }
896         }
897 }
898
899 impl Writeable for PaymentPreimage {
900         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
901                 self.0.write(w)
902         }
903 }
904
905 impl Readable for PaymentPreimage {
906         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
907                 let buf: [u8; 32] = Readable::read(r)?;
908                 Ok(PaymentPreimage(buf))
909         }
910 }
911
912 impl Writeable for PaymentHash {
913         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
914                 self.0.write(w)
915         }
916 }
917
918 impl Readable for PaymentHash {
919         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
920                 let buf: [u8; 32] = Readable::read(r)?;
921                 Ok(PaymentHash(buf))
922         }
923 }
924
925 impl Writeable for PaymentSecret {
926         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
927                 self.0.write(w)
928         }
929 }
930
931 impl Readable for PaymentSecret {
932         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
933                 let buf: [u8; 32] = Readable::read(r)?;
934                 Ok(PaymentSecret(buf))
935         }
936 }
937
938 impl<T: Writeable> Writeable for Box<T> {
939         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
940                 T::write(&**self, w)
941         }
942 }
943
944 impl<T: Readable> Readable for Box<T> {
945         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
946                 Ok(Box::new(Readable::read(r)?))
947         }
948 }
949
950 impl<T: Writeable> Writeable for Option<T> {
951         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
952                 match *self {
953                         None => 0u8.write(w)?,
954                         Some(ref data) => {
955                                 BigSize(data.serialized_length() as u64 + 1).write(w)?;
956                                 data.write(w)?;
957                         }
958                 }
959                 Ok(())
960         }
961 }
962
963 impl<T: Readable> Readable for Option<T>
964 {
965         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
966                 let len: BigSize = Readable::read(r)?;
967                 match len.0 {
968                         0 => Ok(None),
969                         len => {
970                                 let mut reader = FixedLengthReader::new(r, len - 1);
971                                 Ok(Some(Readable::read(&mut reader)?))
972                         }
973                 }
974         }
975 }
976
977 impl Writeable for Txid {
978         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
979                 w.write_all(&self[..])
980         }
981 }
982
983 impl Readable for Txid {
984         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
985                 use bitcoin::hashes::Hash;
986
987                 let buf: [u8; 32] = Readable::read(r)?;
988                 Ok(Txid::from_slice(&buf[..]).unwrap())
989         }
990 }
991
992 impl Writeable for BlockHash {
993         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
994                 w.write_all(&self[..])
995         }
996 }
997
998 impl Readable for BlockHash {
999         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1000                 use bitcoin::hashes::Hash;
1001
1002                 let buf: [u8; 32] = Readable::read(r)?;
1003                 Ok(BlockHash::from_slice(&buf[..]).unwrap())
1004         }
1005 }
1006
1007 impl Writeable for ChainHash {
1008         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1009                 w.write_all(self.as_bytes())
1010         }
1011 }
1012
1013 impl Readable for ChainHash {
1014         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1015                 let buf: [u8; 32] = Readable::read(r)?;
1016                 Ok(ChainHash::from(&buf[..]))
1017         }
1018 }
1019
1020 impl Writeable for OutPoint {
1021         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1022                 self.txid.write(w)?;
1023                 self.vout.write(w)?;
1024                 Ok(())
1025         }
1026 }
1027
1028 impl Readable for OutPoint {
1029         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1030                 let txid = Readable::read(r)?;
1031                 let vout = Readable::read(r)?;
1032                 Ok(OutPoint {
1033                         txid,
1034                         vout,
1035                 })
1036         }
1037 }
1038
1039 macro_rules! impl_consensus_ser {
1040         ($bitcoin_type: ty) => {
1041                 impl Writeable for $bitcoin_type {
1042                         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
1043                                 match self.consensus_encode(&mut WriterWriteAdaptor(writer)) {
1044                                         Ok(_) => Ok(()),
1045                                         Err(e) => Err(e),
1046                                 }
1047                         }
1048                 }
1049
1050                 impl Readable for $bitcoin_type {
1051                         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1052                                 match consensus::encode::Decodable::consensus_decode(r) {
1053                                         Ok(t) => Ok(t),
1054                                         Err(consensus::encode::Error::Io(ref e)) if e.kind() == io::ErrorKind::UnexpectedEof => Err(DecodeError::ShortRead),
1055                                         Err(consensus::encode::Error::Io(e)) => Err(DecodeError::Io(e.kind())),
1056                                         Err(_) => Err(DecodeError::InvalidValue),
1057                                 }
1058                         }
1059                 }
1060         }
1061 }
1062 impl_consensus_ser!(Transaction);
1063 impl_consensus_ser!(TxOut);
1064
1065 impl<T: Readable> Readable for Mutex<T> {
1066         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1067                 let t: T = Readable::read(r)?;
1068                 Ok(Mutex::new(t))
1069         }
1070 }
1071 impl<T: Writeable> Writeable for Mutex<T> {
1072         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1073                 self.lock().unwrap().write(w)
1074         }
1075 }
1076
1077 impl<A: Readable, B: Readable> Readable for (A, B) {
1078         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1079                 let a: A = Readable::read(r)?;
1080                 let b: B = Readable::read(r)?;
1081                 Ok((a, b))
1082         }
1083 }
1084 impl<A: Writeable, B: Writeable> Writeable for (A, B) {
1085         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1086                 self.0.write(w)?;
1087                 self.1.write(w)
1088         }
1089 }
1090
1091 impl<A: Readable, B: Readable, C: Readable> Readable for (A, B, C) {
1092         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1093                 let a: A = Readable::read(r)?;
1094                 let b: B = Readable::read(r)?;
1095                 let c: C = Readable::read(r)?;
1096                 Ok((a, b, c))
1097         }
1098 }
1099 impl<A: Writeable, B: Writeable, C: Writeable> Writeable for (A, B, C) {
1100         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1101                 self.0.write(w)?;
1102                 self.1.write(w)?;
1103                 self.2.write(w)
1104         }
1105 }
1106
1107 impl<A: Readable, B: Readable, C: Readable, D: Readable> Readable for (A, B, C, D) {
1108         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1109                 let a: A = Readable::read(r)?;
1110                 let b: B = Readable::read(r)?;
1111                 let c: C = Readable::read(r)?;
1112                 let d: D = Readable::read(r)?;
1113                 Ok((a, b, c, d))
1114         }
1115 }
1116 impl<A: Writeable, B: Writeable, C: Writeable, D: Writeable> Writeable for (A, B, C, D) {
1117         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1118                 self.0.write(w)?;
1119                 self.1.write(w)?;
1120                 self.2.write(w)?;
1121                 self.3.write(w)
1122         }
1123 }
1124
1125 impl Writeable for () {
1126         fn write<W: Writer>(&self, _: &mut W) -> Result<(), io::Error> {
1127                 Ok(())
1128         }
1129 }
1130 impl Readable for () {
1131         fn read<R: Read>(_r: &mut R) -> Result<Self, DecodeError> {
1132                 Ok(())
1133         }
1134 }
1135
1136 impl Writeable for String {
1137         #[inline]
1138         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1139                 CollectionLength(self.len() as u64).write(w)?;
1140                 w.write_all(self.as_bytes())
1141         }
1142 }
1143 impl Readable for String {
1144         #[inline]
1145         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1146                 let v: Vec<u8> = Readable::read(r)?;
1147                 let ret = String::from_utf8(v).map_err(|_| DecodeError::InvalidValue)?;
1148                 Ok(ret)
1149         }
1150 }
1151
1152 /// Represents a hostname for serialization purposes.
1153 /// Only the character set and length will be validated.
1154 /// The character set consists of ASCII alphanumeric characters, hyphens, and periods.
1155 /// Its length is guaranteed to be representable by a single byte.
1156 /// This serialization is used by [`BOLT 7`] hostnames.
1157 ///
1158 /// [`BOLT 7`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md
1159 #[derive(Clone, Debug, PartialEq, Eq)]
1160 pub struct Hostname(String);
1161 impl Hostname {
1162         /// Returns the length of the hostname.
1163         pub fn len(&self) -> u8 {
1164                 (&self.0).len() as u8
1165         }
1166 }
1167 impl Deref for Hostname {
1168         type Target = String;
1169
1170         fn deref(&self) -> &Self::Target {
1171                 &self.0
1172         }
1173 }
1174 impl From<Hostname> for String {
1175         fn from(hostname: Hostname) -> Self {
1176                 hostname.0
1177         }
1178 }
1179 impl TryFrom<Vec<u8>> for Hostname {
1180         type Error = ();
1181
1182         fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
1183                 if let Ok(s) = String::from_utf8(bytes) {
1184                         Hostname::try_from(s)
1185                 } else {
1186                         Err(())
1187                 }
1188         }
1189 }
1190 impl TryFrom<String> for Hostname {
1191         type Error = ();
1192
1193         fn try_from(s: String) -> Result<Self, Self::Error> {
1194                 if s.len() <= 255 && s.chars().all(|c|
1195                         c.is_ascii_alphanumeric() ||
1196                         c == '.' ||
1197                         c == '-'
1198                 ) {
1199                         Ok(Hostname(s))
1200                 } else {
1201                         Err(())
1202                 }
1203         }
1204 }
1205 impl Writeable for Hostname {
1206         #[inline]
1207         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1208                 self.len().write(w)?;
1209                 w.write_all(self.as_bytes())
1210         }
1211 }
1212 impl Readable for Hostname {
1213         #[inline]
1214         fn read<R: Read>(r: &mut R) -> Result<Hostname, DecodeError> {
1215                 let len: u8 = Readable::read(r)?;
1216                 let mut vec = Vec::with_capacity(len.into());
1217                 vec.resize(len.into(), 0);
1218                 r.read_exact(&mut vec)?;
1219                 Hostname::try_from(vec).map_err(|_| DecodeError::InvalidValue)
1220         }
1221 }
1222
1223 impl Writeable for Duration {
1224         #[inline]
1225         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1226                 self.as_secs().write(w)?;
1227                 self.subsec_nanos().write(w)
1228         }
1229 }
1230 impl Readable for Duration {
1231         #[inline]
1232         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1233                 let secs = Readable::read(r)?;
1234                 let nanos = Readable::read(r)?;
1235                 Ok(Duration::new(secs, nanos))
1236         }
1237 }
1238
1239 #[cfg(test)]
1240 mod tests {
1241         use core::convert::TryFrom;
1242         use crate::util::ser::{Readable, Hostname, Writeable};
1243
1244         #[test]
1245         fn hostname_conversion() {
1246                 assert_eq!(Hostname::try_from(String::from("a-test.com")).unwrap().as_str(), "a-test.com");
1247
1248                 assert!(Hostname::try_from(String::from("\"")).is_err());
1249                 assert!(Hostname::try_from(String::from("$")).is_err());
1250                 assert!(Hostname::try_from(String::from("⚡")).is_err());
1251                 let mut large_vec = Vec::with_capacity(256);
1252                 large_vec.resize(256, b'A');
1253                 assert!(Hostname::try_from(String::from_utf8(large_vec).unwrap()).is_err());
1254         }
1255
1256         #[test]
1257         fn hostname_serialization() {
1258                 let hostname = Hostname::try_from(String::from("test")).unwrap();
1259                 let mut buf: Vec<u8> = Vec::new();
1260                 hostname.write(&mut buf).unwrap();
1261                 assert_eq!(Hostname::read(&mut buf.as_slice()).unwrap().as_str(), "test");
1262         }
1263 }