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