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