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