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