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