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