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