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