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