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