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