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