Update bitcoin crate to 0.29.0
[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 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, Debug))]
403 pub(crate) struct HighZeroBytesDroppedVarInt<T>(pub T);
404
405 macro_rules! impl_writeable_primitive {
406         ($val_type:ty, $len: expr) => {
407                 impl Writeable for $val_type {
408                         #[inline]
409                         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
410                                 writer.write_all(&self.to_be_bytes())
411                         }
412                 }
413                 impl Writeable for HighZeroBytesDroppedVarInt<$val_type> {
414                         #[inline]
415                         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
416                                 // Skip any full leading 0 bytes when writing (in BE):
417                                 writer.write_all(&self.0.to_be_bytes()[(self.0.leading_zeros()/8) as usize..$len])
418                         }
419                 }
420                 impl Readable for $val_type {
421                         #[inline]
422                         fn read<R: Read>(reader: &mut R) -> Result<$val_type, DecodeError> {
423                                 let mut buf = [0; $len];
424                                 reader.read_exact(&mut buf)?;
425                                 Ok(<$val_type>::from_be_bytes(buf))
426                         }
427                 }
428                 impl Readable for HighZeroBytesDroppedVarInt<$val_type> {
429                         #[inline]
430                         fn read<R: Read>(reader: &mut R) -> Result<HighZeroBytesDroppedVarInt<$val_type>, DecodeError> {
431                                 // We need to accept short reads (read_len == 0) as "EOF" and handle them as simply
432                                 // the high bytes being dropped. To do so, we start reading into the middle of buf
433                                 // and then convert the appropriate number of bytes with extra high bytes out of
434                                 // buf.
435                                 let mut buf = [0; $len*2];
436                                 let mut read_len = reader.read(&mut buf[$len..])?;
437                                 let mut total_read_len = read_len;
438                                 while read_len != 0 && total_read_len != $len {
439                                         read_len = reader.read(&mut buf[($len + total_read_len)..])?;
440                                         total_read_len += read_len;
441                                 }
442                                 if total_read_len == 0 || buf[$len] != 0 {
443                                         let first_byte = $len - ($len - total_read_len);
444                                         let mut bytes = [0; $len];
445                                         bytes.copy_from_slice(&buf[first_byte..first_byte + $len]);
446                                         Ok(HighZeroBytesDroppedVarInt(<$val_type>::from_be_bytes(bytes)))
447                                 } else {
448                                         // If the encoding had extra zero bytes, return a failure even though we know
449                                         // what they meant (as the TLV test vectors require this)
450                                         Err(DecodeError::InvalidValue)
451                                 }
452                         }
453                 }
454         }
455 }
456
457 impl_writeable_primitive!(u64, 8);
458 impl_writeable_primitive!(u32, 4);
459 impl_writeable_primitive!(u16, 2);
460
461 impl Writeable for u8 {
462         #[inline]
463         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
464                 writer.write_all(&[*self])
465         }
466 }
467 impl Readable for u8 {
468         #[inline]
469         fn read<R: Read>(reader: &mut R) -> Result<u8, DecodeError> {
470                 let mut buf = [0; 1];
471                 reader.read_exact(&mut buf)?;
472                 Ok(buf[0])
473         }
474 }
475
476 impl Writeable for bool {
477         #[inline]
478         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
479                 writer.write_all(&[if *self {1} else {0}])
480         }
481 }
482 impl Readable for bool {
483         #[inline]
484         fn read<R: Read>(reader: &mut R) -> Result<bool, DecodeError> {
485                 let mut buf = [0; 1];
486                 reader.read_exact(&mut buf)?;
487                 if buf[0] != 0 && buf[0] != 1 {
488                         return Err(DecodeError::InvalidValue);
489                 }
490                 Ok(buf[0] == 1)
491         }
492 }
493
494 // u8 arrays
495 macro_rules! impl_array {
496         ( $size:expr ) => (
497                 impl Writeable for [u8; $size]
498                 {
499                         #[inline]
500                         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
501                                 w.write_all(self)
502                         }
503                 }
504
505                 impl Readable for [u8; $size]
506                 {
507                         #[inline]
508                         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
509                                 let mut buf = [0u8; $size];
510                                 r.read_exact(&mut buf)?;
511                                 Ok(buf)
512                         }
513                 }
514         );
515 }
516
517 impl_array!(3); // for rgb
518 impl_array!(4); // for IPv4
519 impl_array!(12); // for OnionV2
520 impl_array!(16); // for IPv6
521 impl_array!(32); // for channel id & hmac
522 impl_array!(PUBLIC_KEY_SIZE); // for PublicKey
523 impl_array!(COMPACT_SIGNATURE_SIZE); // for Signature
524 impl_array!(1300); // for OnionPacket.hop_data
525
526 // HashMap
527 impl<K, V> Writeable for HashMap<K, V>
528         where K: Writeable + Eq + Hash,
529               V: Writeable
530 {
531         #[inline]
532         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
533         (self.len() as u16).write(w)?;
534                 for (key, value) in self.iter() {
535                         key.write(w)?;
536                         value.write(w)?;
537                 }
538                 Ok(())
539         }
540 }
541
542 impl<K, V> Readable for HashMap<K, V>
543         where K: Readable + Eq + Hash,
544               V: MaybeReadable
545 {
546         #[inline]
547         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
548                 let len: u16 = Readable::read(r)?;
549                 let mut ret = HashMap::with_capacity(len as usize);
550                 for _ in 0..len {
551                         let k = K::read(r)?;
552                         let v_opt = V::read(r)?;
553                         if let Some(v) = v_opt {
554                                 if ret.insert(k, v).is_some() {
555                                         return Err(DecodeError::InvalidValue);
556                                 }
557                         }
558                 }
559                 Ok(ret)
560         }
561 }
562
563 // HashSet
564 impl<T> Writeable for HashSet<T>
565 where T: Writeable + Eq + Hash
566 {
567         #[inline]
568         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
569                 (self.len() as u16).write(w)?;
570                 for item in self.iter() {
571                         item.write(w)?;
572                 }
573                 Ok(())
574         }
575 }
576
577 impl<T> Readable for HashSet<T>
578 where T: Readable + Eq + Hash
579 {
580         #[inline]
581         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
582                 let len: u16 = Readable::read(r)?;
583                 let mut ret = HashSet::with_capacity(len as usize);
584                 for _ in 0..len {
585                         if !ret.insert(T::read(r)?) {
586                                 return Err(DecodeError::InvalidValue)
587                         }
588                 }
589                 Ok(ret)
590         }
591 }
592
593 // Vectors
594 impl Writeable for Vec<u8> {
595         #[inline]
596         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
597                 (self.len() as u16).write(w)?;
598                 w.write_all(&self)
599         }
600 }
601
602 impl Readable for Vec<u8> {
603         #[inline]
604         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
605                 let len: u16 = Readable::read(r)?;
606                 let mut ret = Vec::with_capacity(len as usize);
607                 ret.resize(len as usize, 0);
608                 r.read_exact(&mut ret)?;
609                 Ok(ret)
610         }
611 }
612 impl Writeable for Vec<Signature> {
613         #[inline]
614         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
615                 (self.len() as u16).write(w)?;
616                 for e in self.iter() {
617                         e.write(w)?;
618                 }
619                 Ok(())
620         }
621 }
622
623 impl Readable for Vec<Signature> {
624         #[inline]
625         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
626                 let len: u16 = Readable::read(r)?;
627                 let byte_size = (len as usize)
628                                 .checked_mul(COMPACT_SIGNATURE_SIZE)
629                                 .ok_or(DecodeError::BadLengthDescriptor)?;
630                 if byte_size > MAX_BUF_SIZE {
631                         return Err(DecodeError::BadLengthDescriptor);
632                 }
633                 let mut ret = Vec::with_capacity(len as usize);
634                 for _ in 0..len { ret.push(Readable::read(r)?); }
635                 Ok(ret)
636         }
637 }
638
639 impl Writeable for Script {
640         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
641                 (self.len() as u16).write(w)?;
642                 w.write_all(self.as_bytes())
643         }
644 }
645
646 impl Readable for Script {
647         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
648                 let len = <u16 as Readable>::read(r)? as usize;
649                 let mut buf = vec![0; len];
650                 r.read_exact(&mut buf)?;
651                 Ok(Script::from(buf))
652         }
653 }
654
655 impl Writeable for PublicKey {
656         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
657                 self.serialize().write(w)
658         }
659         #[inline]
660         fn serialized_length(&self) -> usize {
661                 PUBLIC_KEY_SIZE
662         }
663 }
664
665 impl Readable for PublicKey {
666         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
667                 let buf: [u8; PUBLIC_KEY_SIZE] = Readable::read(r)?;
668                 match PublicKey::from_slice(&buf) {
669                         Ok(key) => Ok(key),
670                         Err(_) => return Err(DecodeError::InvalidValue),
671                 }
672         }
673 }
674
675 impl Writeable for SecretKey {
676         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
677                 let mut ser = [0; SECRET_KEY_SIZE];
678                 ser.copy_from_slice(&self[..]);
679                 ser.write(w)
680         }
681         #[inline]
682         fn serialized_length(&self) -> usize {
683                 SECRET_KEY_SIZE
684         }
685 }
686
687 impl Readable for SecretKey {
688         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
689                 let buf: [u8; SECRET_KEY_SIZE] = Readable::read(r)?;
690                 match SecretKey::from_slice(&buf) {
691                         Ok(key) => Ok(key),
692                         Err(_) => return Err(DecodeError::InvalidValue),
693                 }
694         }
695 }
696
697 impl Writeable for Sha256dHash {
698         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
699                 w.write_all(&self[..])
700         }
701 }
702
703 impl Readable for Sha256dHash {
704         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
705                 use bitcoin::hashes::Hash;
706
707                 let buf: [u8; 32] = Readable::read(r)?;
708                 Ok(Sha256dHash::from_slice(&buf[..]).unwrap())
709         }
710 }
711
712 impl Writeable for Signature {
713         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
714                 self.serialize_compact().write(w)
715         }
716         #[inline]
717         fn serialized_length(&self) -> usize {
718                 COMPACT_SIGNATURE_SIZE
719         }
720 }
721
722 impl Readable for Signature {
723         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
724                 let buf: [u8; COMPACT_SIGNATURE_SIZE] = Readable::read(r)?;
725                 match Signature::from_compact(&buf) {
726                         Ok(sig) => Ok(sig),
727                         Err(_) => return Err(DecodeError::InvalidValue),
728                 }
729         }
730 }
731
732 impl Writeable for PaymentPreimage {
733         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
734                 self.0.write(w)
735         }
736 }
737
738 impl Readable for PaymentPreimage {
739         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
740                 let buf: [u8; 32] = Readable::read(r)?;
741                 Ok(PaymentPreimage(buf))
742         }
743 }
744
745 impl Writeable for PaymentHash {
746         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
747                 self.0.write(w)
748         }
749 }
750
751 impl Readable for PaymentHash {
752         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
753                 let buf: [u8; 32] = Readable::read(r)?;
754                 Ok(PaymentHash(buf))
755         }
756 }
757
758 impl Writeable for PaymentSecret {
759         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
760                 self.0.write(w)
761         }
762 }
763
764 impl Readable for PaymentSecret {
765         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
766                 let buf: [u8; 32] = Readable::read(r)?;
767                 Ok(PaymentSecret(buf))
768         }
769 }
770
771 impl<T: Writeable> Writeable for Box<T> {
772         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
773                 T::write(&**self, w)
774         }
775 }
776
777 impl<T: Readable> Readable for Box<T> {
778         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
779                 Ok(Box::new(Readable::read(r)?))
780         }
781 }
782
783 impl<T: Writeable> Writeable for Option<T> {
784         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
785                 match *self {
786                         None => 0u8.write(w)?,
787                         Some(ref data) => {
788                                 BigSize(data.serialized_length() as u64 + 1).write(w)?;
789                                 data.write(w)?;
790                         }
791                 }
792                 Ok(())
793         }
794 }
795
796 impl<T: Readable> Readable for Option<T>
797 {
798         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
799                 let len: BigSize = Readable::read(r)?;
800                 match len.0 {
801                         0 => Ok(None),
802                         len => {
803                                 let mut reader = FixedLengthReader::new(r, len - 1);
804                                 Ok(Some(Readable::read(&mut reader)?))
805                         }
806                 }
807         }
808 }
809
810 impl Writeable for Txid {
811         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
812                 w.write_all(&self[..])
813         }
814 }
815
816 impl Readable for Txid {
817         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
818                 use bitcoin::hashes::Hash;
819
820                 let buf: [u8; 32] = Readable::read(r)?;
821                 Ok(Txid::from_slice(&buf[..]).unwrap())
822         }
823 }
824
825 impl Writeable for BlockHash {
826         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
827                 w.write_all(&self[..])
828         }
829 }
830
831 impl Readable for BlockHash {
832         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
833                 use bitcoin::hashes::Hash;
834
835                 let buf: [u8; 32] = Readable::read(r)?;
836                 Ok(BlockHash::from_slice(&buf[..]).unwrap())
837         }
838 }
839
840 impl Writeable for OutPoint {
841         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
842                 self.txid.write(w)?;
843                 self.vout.write(w)?;
844                 Ok(())
845         }
846 }
847
848 impl Readable for OutPoint {
849         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
850                 let txid = Readable::read(r)?;
851                 let vout = Readable::read(r)?;
852                 Ok(OutPoint {
853                         txid,
854                         vout,
855                 })
856         }
857 }
858
859 macro_rules! impl_consensus_ser {
860         ($bitcoin_type: ty) => {
861                 impl Writeable for $bitcoin_type {
862                         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
863                                 match self.consensus_encode(&mut WriterWriteAdaptor(writer)) {
864                                         Ok(_) => Ok(()),
865                                         Err(e) => Err(e),
866                                 }
867                         }
868                 }
869
870                 impl Readable for $bitcoin_type {
871                         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
872                                 match consensus::encode::Decodable::consensus_decode(r) {
873                                         Ok(t) => Ok(t),
874                                         Err(consensus::encode::Error::Io(ref e)) if e.kind() == io::ErrorKind::UnexpectedEof => Err(DecodeError::ShortRead),
875                                         Err(consensus::encode::Error::Io(e)) => Err(DecodeError::Io(e.kind())),
876                                         Err(_) => Err(DecodeError::InvalidValue),
877                                 }
878                         }
879                 }
880         }
881 }
882 impl_consensus_ser!(Transaction);
883 impl_consensus_ser!(TxOut);
884
885 impl<T: Readable> Readable for Mutex<T> {
886         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
887                 let t: T = Readable::read(r)?;
888                 Ok(Mutex::new(t))
889         }
890 }
891 impl<T: Writeable> Writeable for Mutex<T> {
892         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
893                 self.lock().unwrap().write(w)
894         }
895 }
896
897 impl<A: Readable, B: Readable> Readable for (A, B) {
898         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
899                 let a: A = Readable::read(r)?;
900                 let b: B = Readable::read(r)?;
901                 Ok((a, b))
902         }
903 }
904 impl<A: Writeable, B: Writeable> Writeable for (A, B) {
905         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
906                 self.0.write(w)?;
907                 self.1.write(w)
908         }
909 }
910
911 impl<A: Readable, B: Readable, C: Readable> Readable for (A, B, C) {
912         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
913                 let a: A = Readable::read(r)?;
914                 let b: B = Readable::read(r)?;
915                 let c: C = Readable::read(r)?;
916                 Ok((a, b, c))
917         }
918 }
919 impl<A: Writeable, B: Writeable, C: Writeable> Writeable for (A, B, C) {
920         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
921                 self.0.write(w)?;
922                 self.1.write(w)?;
923                 self.2.write(w)
924         }
925 }
926
927 impl Writeable for () {
928         fn write<W: Writer>(&self, _: &mut W) -> Result<(), io::Error> {
929                 Ok(())
930         }
931 }
932 impl Readable for () {
933         fn read<R: Read>(_r: &mut R) -> Result<Self, DecodeError> {
934                 Ok(())
935         }
936 }
937
938 impl Writeable for String {
939         #[inline]
940         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
941                 (self.len() as u16).write(w)?;
942                 w.write_all(self.as_bytes())
943         }
944 }
945 impl Readable for String {
946         #[inline]
947         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
948                 let v: Vec<u8> = Readable::read(r)?;
949                 let ret = String::from_utf8(v).map_err(|_| DecodeError::InvalidValue)?;
950                 Ok(ret)
951         }
952 }
953
954 /// Represents a hostname for serialization purposes.
955 /// Only the character set and length will be validated.
956 /// The character set consists of ASCII alphanumeric characters, hyphens, and periods.
957 /// Its length is guaranteed to be representable by a single byte.
958 /// This serialization is used by BOLT 7 hostnames.
959 #[derive(Clone, Debug, PartialEq)]
960 pub struct Hostname(String);
961 impl Hostname {
962         /// Returns the length of the hostname.
963         pub fn len(&self) -> u8 {
964                 (&self.0).len() as u8
965         }
966 }
967 impl Deref for Hostname {
968         type Target = String;
969
970         fn deref(&self) -> &Self::Target {
971                 &self.0
972         }
973 }
974 impl From<Hostname> for String {
975         fn from(hostname: Hostname) -> Self {
976                 hostname.0
977         }
978 }
979 impl TryFrom<Vec<u8>> for Hostname {
980         type Error = ();
981
982         fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
983                 if let Ok(s) = String::from_utf8(bytes) {
984                         Hostname::try_from(s)
985                 } else {
986                         Err(())
987                 }
988         }
989 }
990 impl TryFrom<String> for Hostname {
991         type Error = ();
992
993         fn try_from(s: String) -> Result<Self, Self::Error> {
994                 if s.len() <= 255 && s.chars().all(|c|
995                         c.is_ascii_alphanumeric() ||
996                         c == '.' ||
997                         c == '-'
998                 ) {
999                         Ok(Hostname(s))
1000                 } else {
1001                         Err(())
1002                 }
1003         }
1004 }
1005 impl Writeable for Hostname {
1006         #[inline]
1007         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1008                 self.len().write(w)?;
1009                 w.write_all(self.as_bytes())
1010         }
1011 }
1012 impl Readable for Hostname {
1013         #[inline]
1014         fn read<R: Read>(r: &mut R) -> Result<Hostname, DecodeError> {
1015                 let len: u8 = Readable::read(r)?;
1016                 let mut vec = Vec::with_capacity(len.into());
1017                 vec.resize(len.into(), 0);
1018                 r.read_exact(&mut vec)?;
1019                 Hostname::try_from(vec).map_err(|_| DecodeError::InvalidValue)
1020         }
1021 }
1022
1023 impl Writeable for Duration {
1024         #[inline]
1025         fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1026                 self.as_secs().write(w)?;
1027                 self.subsec_nanos().write(w)
1028         }
1029 }
1030 impl Readable for Duration {
1031         #[inline]
1032         fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1033                 let secs = Readable::read(r)?;
1034                 let nanos = Readable::read(r)?;
1035                 Ok(Duration::new(secs, nanos))
1036         }
1037 }
1038
1039 #[cfg(test)]
1040 mod tests {
1041         use core::convert::TryFrom;
1042         use util::ser::{Readable, Hostname, Writeable};
1043
1044         #[test]
1045         fn hostname_conversion() {
1046                 assert_eq!(Hostname::try_from(String::from("a-test.com")).unwrap().as_str(), "a-test.com");
1047
1048                 assert!(Hostname::try_from(String::from("\"")).is_err());
1049                 assert!(Hostname::try_from(String::from("$")).is_err());
1050                 assert!(Hostname::try_from(String::from("⚡")).is_err());
1051                 let mut large_vec = Vec::with_capacity(256);
1052                 large_vec.resize(256, b'A');
1053                 assert!(Hostname::try_from(String::from_utf8(large_vec).unwrap()).is_err());
1054         }
1055
1056         #[test]
1057         fn hostname_serialization() {
1058                 let hostname = Hostname::try_from(String::from("test")).unwrap();
1059                 let mut buf: Vec<u8> = Vec::new();
1060                 hostname.write(&mut buf).unwrap();
1061                 assert_eq!(Hostname::read(&mut buf.as_slice()).unwrap().as_str(), "test");
1062         }
1063 }