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