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