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