1 // This file is Copyright its original authors, visible in version control
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
10 //! A very simple serialization framework which is used to serialize/deserialize messages as well
11 //! as ChannelsManagers and ChannelMonitors.
14 use io::{self, Read, Write};
15 use io_extras::{copy, sink};
20 use bitcoin::secp256k1::{PublicKey, SecretKey};
21 use bitcoin::secp256k1::constants::{PUBLIC_KEY_SIZE, SECRET_KEY_SIZE, COMPACT_SIGNATURE_SIZE};
22 use bitcoin::secp256k1::ecdsa::Signature;
23 use bitcoin::blockdata::script::Script;
24 use bitcoin::blockdata::transaction::{OutPoint, Transaction, TxOut};
25 use bitcoin::consensus;
26 use bitcoin::consensus::Encodable;
27 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
28 use bitcoin::hash_types::{Txid, BlockHash};
29 use core::marker::Sized;
30 use core::time::Duration;
31 use ln::msgs::DecodeError;
32 use ln::{PaymentPreimage, PaymentHash, PaymentSecret};
34 use util::byte_utils::{be48_to_array, slice_to_be48};
36 /// serialization buffer size
37 pub const MAX_BUF_SIZE: usize = 64 * 1024;
39 /// A simplified version of std::io::Write that exists largely for backwards compatibility.
40 /// An impl is provided for any type that also impls std::io::Write.
42 /// (C-not exported) as we only export serialization to/from byte arrays instead
44 /// Writes the given buf out. See std::io::Write::write_all for more
45 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error>;
48 impl<W: Write> Writer for W {
50 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
51 <Self as io::Write>::write_all(self, buf)
55 pub(crate) struct WriterWriteAdaptor<'a, W: Writer + 'a>(pub &'a mut W);
56 impl<'a, W: Writer + 'a> Write for WriterWriteAdaptor<'a, W> {
58 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
62 fn write(&mut self, buf: &[u8]) -> Result<usize, io::Error> {
63 self.0.write_all(buf)?;
67 fn flush(&mut self) -> Result<(), io::Error> {
72 pub(crate) struct VecWriter(pub Vec<u8>);
73 impl Writer for VecWriter {
75 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
76 self.0.extend_from_slice(buf);
81 /// Writer that only tracks the amount of data written - useful if you need to calculate the length
82 /// of some data when serialized but don't yet need the full data.
83 pub(crate) struct LengthCalculatingWriter(pub usize);
84 impl Writer for LengthCalculatingWriter {
86 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
92 /// Essentially std::io::Take but a bit simpler and with a method to walk the underlying stream
93 /// forward to ensure we always consume exactly the fixed length specified.
94 pub(crate) struct FixedLengthReader<R: Read> {
99 impl<R: Read> FixedLengthReader<R> {
100 pub fn new(read: R, total_bytes: u64) -> Self {
101 Self { read, bytes_read: 0, total_bytes }
105 pub fn bytes_remain(&mut self) -> bool {
106 self.bytes_read != self.total_bytes
110 pub fn eat_remaining(&mut self) -> Result<(), DecodeError> {
111 copy(self, &mut sink()).unwrap();
112 if self.bytes_read != self.total_bytes {
113 Err(DecodeError::ShortRead)
119 impl<R: Read> Read for FixedLengthReader<R> {
121 fn read(&mut self, dest: &mut [u8]) -> Result<usize, io::Error> {
122 if self.total_bytes == self.bytes_read {
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)]) {
128 self.bytes_read += v as u64;
137 impl<R: Read> LengthRead for FixedLengthReader<R> {
139 fn total_bytes(&self) -> u64 {
144 /// A Read which tracks whether any bytes have been read at all. This allows us to distinguish
145 /// between "EOF reached before we started" and "EOF reached mid-read".
146 pub(crate) struct ReadTrackingReader<R: Read> {
150 impl<R: Read> ReadTrackingReader<R> {
151 pub fn new(read: R) -> Self {
152 Self { read, have_read: false }
155 impl<R: Read> Read for ReadTrackingReader<R> {
157 fn read(&mut self, dest: &mut [u8]) -> Result<usize, io::Error> {
158 match self.read.read(dest) {
161 self.have_read = true;
169 /// A trait that various rust-lightning types implement allowing them to be written out to a Writer
171 /// (C-not exported) as we only export serialization to/from byte arrays instead
172 pub trait Writeable {
173 /// Writes self out to the given Writer
174 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error>;
176 /// Writes self out to a Vec<u8>
177 fn encode(&self) -> Vec<u8> {
178 let mut msg = VecWriter(Vec::new());
179 self.write(&mut msg).unwrap();
183 /// Writes self out to a Vec<u8>
185 fn encode_with_len(&self) -> Vec<u8> {
186 let mut msg = VecWriter(Vec::new());
187 0u16.write(&mut msg).unwrap();
188 self.write(&mut msg).unwrap();
189 let len = msg.0.len();
190 msg.0[..2].copy_from_slice(&(len as u16 - 2).to_be_bytes());
194 /// Gets the length of this object after it has been serialized. This can be overridden to
195 /// optimize cases where we prepend an object with its length.
196 // Note that LLVM optimizes this away in most cases! Check that it isn't before you override!
198 fn serialized_length(&self) -> usize {
199 let mut len_calc = LengthCalculatingWriter(0);
200 self.write(&mut len_calc).expect("No in-memory data may fail to serialize");
205 impl<'a, T: Writeable> Writeable for &'a T {
206 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { (*self).write(writer) }
209 /// A trait that various rust-lightning types implement allowing them to be read in from a Read
211 /// (C-not exported) as we only export serialization to/from byte arrays instead
215 /// Reads a Self in from the given Read
216 fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError>;
219 /// A trait that various higher-level rust-lightning types implement allowing them to be read in
220 /// from a Read given some additional set of arguments which is required to deserialize.
222 /// (C-not exported) as we only export serialization to/from byte arrays instead
223 pub trait ReadableArgs<P>
226 /// Reads a Self in from the given Read
227 fn read<R: Read>(reader: &mut R, params: P) -> Result<Self, DecodeError>;
230 /// A std::io::Read that also provides the total bytes available to read.
231 pub(crate) trait LengthRead: Read {
232 /// The total number of bytes available to read.
233 fn total_bytes(&self) -> u64;
236 /// A trait that various higher-level rust-lightning types implement allowing them to be read in
237 /// from a Read given some additional set of arguments which is required to deserialize, requiring
238 /// the implementer to provide the total length of the read.
239 pub(crate) trait LengthReadableArgs<P> where Self: Sized
241 /// Reads a Self in from the given LengthRead
242 fn read<R: LengthRead>(reader: &mut R, params: P) -> Result<Self, DecodeError>;
245 /// A trait that various rust-lightning types implement allowing them to (maybe) be read in from a Read
247 /// (C-not exported) as we only export serialization to/from byte arrays instead
248 pub trait MaybeReadable
251 /// Reads a Self in from the given Read
252 fn read<R: Read>(reader: &mut R) -> Result<Option<Self>, DecodeError>;
255 impl<T: Readable> MaybeReadable for T {
257 fn read<R: Read>(reader: &mut R) -> Result<Option<T>, DecodeError> {
258 Ok(Some(Readable::read(reader)?))
262 pub(crate) struct OptionDeserWrapper<T: Readable>(pub Option<T>);
263 impl<T: Readable> Readable for OptionDeserWrapper<T> {
265 fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
266 Ok(Self(Some(Readable::read(reader)?)))
269 /// When handling default_values, we want to map the default-value T directly
270 /// to a OptionDeserWrapper<T> in a way that works for `field: T = t;` as
271 /// well. Thus, we assume `Into<T> for T` does nothing and use that.
272 impl<T: Readable> From<T> for OptionDeserWrapper<T> {
273 fn from(t: T) -> OptionDeserWrapper<T> { OptionDeserWrapper(Some(t)) }
276 /// Wrapper to write each element of a Vec with no length prefix
277 pub(crate) struct VecWriteWrapper<'a, T: Writeable>(pub &'a Vec<T>);
278 impl<'a, T: Writeable> Writeable for VecWriteWrapper<'a, T> {
280 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
281 for ref v in self.0.iter() {
288 /// Wrapper to read elements from a given stream until it reaches the end of the stream.
289 pub(crate) struct VecReadWrapper<T>(pub Vec<T>);
290 impl<T: MaybeReadable> Readable for VecReadWrapper<T> {
292 fn read<R: Read>(mut reader: &mut R) -> Result<Self, DecodeError> {
293 let mut values = Vec::new();
295 let mut track_read = ReadTrackingReader::new(&mut reader);
296 match MaybeReadable::read(&mut track_read) {
297 Ok(Some(v)) => { values.push(v); },
299 // If we failed to read any bytes at all, we reached the end of our TLV
300 // stream and have simply exhausted all entries.
301 Err(ref e) if e == &DecodeError::ShortRead && !track_read.have_read => break,
302 Err(e) => return Err(e),
309 pub(crate) struct U48(pub u64);
310 impl Writeable for U48 {
312 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
313 writer.write_all(&be48_to_array(self.0))
316 impl Readable for U48 {
318 fn read<R: Read>(reader: &mut R) -> Result<U48, DecodeError> {
319 let mut buf = [0; 6];
320 reader.read_exact(&mut buf)?;
321 Ok(U48(slice_to_be48(&buf)))
325 /// Lightning TLV uses a custom variable-length integer called BigSize. It is similar to Bitcoin's
326 /// variable-length integers except that it is serialized in big-endian instead of little-endian.
328 /// Like Bitcoin's variable-length integer, it exhibits ambiguity in that certain values can be
329 /// encoded in several different ways, which we must check for at deserialization-time. Thus, if
330 /// you're looking for an example of a variable-length integer to use for your own project, move
331 /// along, this is a rather poor design.
332 pub struct BigSize(pub u64);
333 impl Writeable for BigSize {
335 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
338 (self.0 as u8).write(writer)
341 0xFDu8.write(writer)?;
342 (self.0 as u16).write(writer)
344 0x10000...0xFFFFFFFF => {
345 0xFEu8.write(writer)?;
346 (self.0 as u32).write(writer)
349 0xFFu8.write(writer)?;
350 (self.0 as u64).write(writer)
355 impl Readable for BigSize {
357 fn read<R: Read>(reader: &mut R) -> Result<BigSize, DecodeError> {
358 let n: u8 = Readable::read(reader)?;
361 let x: u64 = Readable::read(reader)?;
363 Err(DecodeError::InvalidValue)
369 let x: u32 = Readable::read(reader)?;
371 Err(DecodeError::InvalidValue)
373 Ok(BigSize(x as u64))
377 let x: u16 = Readable::read(reader)?;
379 Err(DecodeError::InvalidValue)
381 Ok(BigSize(x as u64))
384 n => Ok(BigSize(n as u64))
389 /// In TLV we occasionally send fields which only consist of, or potentially end with, a
390 /// variable-length integer which is simply truncated by skipping high zero bytes. This type
391 /// encapsulates such integers implementing Readable/Writeable for them.
392 #[cfg_attr(test, derive(PartialEq, Debug))]
393 pub(crate) struct HighZeroBytesDroppedVarInt<T>(pub T);
395 macro_rules! impl_writeable_primitive {
396 ($val_type:ty, $len: expr) => {
397 impl Writeable for $val_type {
399 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
400 writer.write_all(&self.to_be_bytes())
403 impl Writeable for HighZeroBytesDroppedVarInt<$val_type> {
405 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
406 // Skip any full leading 0 bytes when writing (in BE):
407 writer.write_all(&self.0.to_be_bytes()[(self.0.leading_zeros()/8) as usize..$len])
410 impl Readable for $val_type {
412 fn read<R: Read>(reader: &mut R) -> Result<$val_type, DecodeError> {
413 let mut buf = [0; $len];
414 reader.read_exact(&mut buf)?;
415 Ok(<$val_type>::from_be_bytes(buf))
418 impl Readable for HighZeroBytesDroppedVarInt<$val_type> {
420 fn read<R: Read>(reader: &mut R) -> Result<HighZeroBytesDroppedVarInt<$val_type>, DecodeError> {
421 // We need to accept short reads (read_len == 0) as "EOF" and handle them as simply
422 // the high bytes being dropped. To do so, we start reading into the middle of buf
423 // and then convert the appropriate number of bytes with extra high bytes out of
425 let mut buf = [0; $len*2];
426 let mut read_len = reader.read(&mut buf[$len..])?;
427 let mut total_read_len = read_len;
428 while read_len != 0 && total_read_len != $len {
429 read_len = reader.read(&mut buf[($len + total_read_len)..])?;
430 total_read_len += read_len;
432 if total_read_len == 0 || buf[$len] != 0 {
433 let first_byte = $len - ($len - total_read_len);
434 let mut bytes = [0; $len];
435 bytes.copy_from_slice(&buf[first_byte..first_byte + $len]);
436 Ok(HighZeroBytesDroppedVarInt(<$val_type>::from_be_bytes(bytes)))
438 // If the encoding had extra zero bytes, return a failure even though we know
439 // what they meant (as the TLV test vectors require this)
440 Err(DecodeError::InvalidValue)
447 impl_writeable_primitive!(u64, 8);
448 impl_writeable_primitive!(u32, 4);
449 impl_writeable_primitive!(u16, 2);
451 impl Writeable for u8 {
453 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
454 writer.write_all(&[*self])
457 impl Readable for u8 {
459 fn read<R: Read>(reader: &mut R) -> Result<u8, DecodeError> {
460 let mut buf = [0; 1];
461 reader.read_exact(&mut buf)?;
466 impl Writeable for bool {
468 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
469 writer.write_all(&[if *self {1} else {0}])
472 impl Readable for bool {
474 fn read<R: Read>(reader: &mut R) -> Result<bool, DecodeError> {
475 let mut buf = [0; 1];
476 reader.read_exact(&mut buf)?;
477 if buf[0] != 0 && buf[0] != 1 {
478 return Err(DecodeError::InvalidValue);
485 macro_rules! impl_array {
487 impl Writeable for [u8; $size]
490 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
495 impl Readable for [u8; $size]
498 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
499 let mut buf = [0u8; $size];
500 r.read_exact(&mut buf)?;
507 impl_array!(3); // for rgb
508 impl_array!(4); // for IPv4
509 impl_array!(12); // for OnionV2
510 impl_array!(16); // for IPv6
511 impl_array!(32); // for channel id & hmac
512 impl_array!(PUBLIC_KEY_SIZE); // for PublicKey
513 impl_array!(COMPACT_SIGNATURE_SIZE); // for Signature
514 impl_array!(1300); // for OnionPacket.hop_data
517 impl<K, V> Writeable for HashMap<K, V>
518 where K: Writeable + Eq + Hash,
522 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
523 (self.len() as u16).write(w)?;
524 for (key, value) in self.iter() {
532 impl<K, V> Readable for HashMap<K, V>
533 where K: Readable + Eq + Hash,
537 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
538 let len: u16 = Readable::read(r)?;
539 let mut ret = HashMap::with_capacity(len as usize);
542 let v_opt = V::read(r)?;
543 if let Some(v) = v_opt {
544 if ret.insert(k, v).is_some() {
545 return Err(DecodeError::InvalidValue);
554 impl<T> Writeable for HashSet<T>
555 where T: Writeable + Eq + Hash
558 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
559 (self.len() as u16).write(w)?;
560 for item in self.iter() {
567 impl<T> Readable for HashSet<T>
568 where T: Readable + Eq + Hash
571 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
572 let len: u16 = Readable::read(r)?;
573 let mut ret = HashSet::with_capacity(len as usize);
575 if !ret.insert(T::read(r)?) {
576 return Err(DecodeError::InvalidValue)
584 impl Writeable for Vec<u8> {
586 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
587 (self.len() as u16).write(w)?;
592 impl Readable for Vec<u8> {
594 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
595 let len: u16 = Readable::read(r)?;
596 let mut ret = Vec::with_capacity(len as usize);
597 ret.resize(len as usize, 0);
598 r.read_exact(&mut ret)?;
602 impl Writeable for Vec<Signature> {
604 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
605 (self.len() as u16).write(w)?;
606 for e in self.iter() {
613 impl Readable for Vec<Signature> {
615 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
616 let len: u16 = Readable::read(r)?;
617 let byte_size = (len as usize)
618 .checked_mul(COMPACT_SIGNATURE_SIZE)
619 .ok_or(DecodeError::BadLengthDescriptor)?;
620 if byte_size > MAX_BUF_SIZE {
621 return Err(DecodeError::BadLengthDescriptor);
623 let mut ret = Vec::with_capacity(len as usize);
624 for _ in 0..len { ret.push(Readable::read(r)?); }
629 impl Writeable for Script {
630 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
631 (self.len() as u16).write(w)?;
632 w.write_all(self.as_bytes())
636 impl Readable for Script {
637 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
638 let len = <u16 as Readable>::read(r)? as usize;
639 let mut buf = vec![0; len];
640 r.read_exact(&mut buf)?;
641 Ok(Script::from(buf))
645 impl Writeable for PublicKey {
646 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
647 self.serialize().write(w)
650 fn serialized_length(&self) -> usize {
655 impl Readable for PublicKey {
656 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
657 let buf: [u8; PUBLIC_KEY_SIZE] = Readable::read(r)?;
658 match PublicKey::from_slice(&buf) {
660 Err(_) => return Err(DecodeError::InvalidValue),
665 impl Writeable for SecretKey {
666 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
667 let mut ser = [0; SECRET_KEY_SIZE];
668 ser.copy_from_slice(&self[..]);
672 fn serialized_length(&self) -> usize {
677 impl Readable for SecretKey {
678 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
679 let buf: [u8; SECRET_KEY_SIZE] = Readable::read(r)?;
680 match SecretKey::from_slice(&buf) {
682 Err(_) => return Err(DecodeError::InvalidValue),
687 impl Writeable for Sha256dHash {
688 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
689 w.write_all(&self[..])
693 impl Readable for Sha256dHash {
694 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
695 use bitcoin::hashes::Hash;
697 let buf: [u8; 32] = Readable::read(r)?;
698 Ok(Sha256dHash::from_slice(&buf[..]).unwrap())
702 impl Writeable for Signature {
703 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
704 self.serialize_compact().write(w)
707 fn serialized_length(&self) -> usize {
708 COMPACT_SIGNATURE_SIZE
712 impl Readable for Signature {
713 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
714 let buf: [u8; COMPACT_SIGNATURE_SIZE] = Readable::read(r)?;
715 match Signature::from_compact(&buf) {
717 Err(_) => return Err(DecodeError::InvalidValue),
722 impl Writeable for PaymentPreimage {
723 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
728 impl Readable for PaymentPreimage {
729 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
730 let buf: [u8; 32] = Readable::read(r)?;
731 Ok(PaymentPreimage(buf))
735 impl Writeable for PaymentHash {
736 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
741 impl Readable for PaymentHash {
742 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
743 let buf: [u8; 32] = Readable::read(r)?;
748 impl Writeable for PaymentSecret {
749 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
754 impl Readable for PaymentSecret {
755 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
756 let buf: [u8; 32] = Readable::read(r)?;
757 Ok(PaymentSecret(buf))
761 impl<T: Writeable> Writeable for Box<T> {
762 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
767 impl<T: Readable> Readable for Box<T> {
768 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
769 Ok(Box::new(Readable::read(r)?))
773 impl<T: Writeable> Writeable for Option<T> {
774 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
776 None => 0u8.write(w)?,
778 BigSize(data.serialized_length() as u64 + 1).write(w)?;
786 impl<T: Readable> Readable for Option<T>
788 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
789 let len: BigSize = Readable::read(r)?;
793 let mut reader = FixedLengthReader::new(r, len - 1);
794 Ok(Some(Readable::read(&mut reader)?))
800 impl Writeable for Txid {
801 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
802 w.write_all(&self[..])
806 impl Readable for Txid {
807 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
808 use bitcoin::hashes::Hash;
810 let buf: [u8; 32] = Readable::read(r)?;
811 Ok(Txid::from_slice(&buf[..]).unwrap())
815 impl Writeable for BlockHash {
816 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
817 w.write_all(&self[..])
821 impl Readable for BlockHash {
822 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
823 use bitcoin::hashes::Hash;
825 let buf: [u8; 32] = Readable::read(r)?;
826 Ok(BlockHash::from_slice(&buf[..]).unwrap())
830 impl Writeable for OutPoint {
831 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
838 impl Readable for OutPoint {
839 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
840 let txid = Readable::read(r)?;
841 let vout = Readable::read(r)?;
849 macro_rules! impl_consensus_ser {
850 ($bitcoin_type: ty) => {
851 impl Writeable for $bitcoin_type {
852 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
853 match self.consensus_encode(WriterWriteAdaptor(writer)) {
860 impl Readable for $bitcoin_type {
861 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
862 match consensus::encode::Decodable::consensus_decode(r) {
864 Err(consensus::encode::Error::Io(ref e)) if e.kind() == io::ErrorKind::UnexpectedEof => Err(DecodeError::ShortRead),
865 Err(consensus::encode::Error::Io(e)) => Err(DecodeError::Io(e.kind())),
866 Err(_) => Err(DecodeError::InvalidValue),
872 impl_consensus_ser!(Transaction);
873 impl_consensus_ser!(TxOut);
875 impl<T: Readable> Readable for Mutex<T> {
876 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
877 let t: T = Readable::read(r)?;
881 impl<T: Writeable> Writeable for Mutex<T> {
882 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
883 self.lock().unwrap().write(w)
887 impl<A: Readable, B: Readable> Readable for (A, B) {
888 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
889 let a: A = Readable::read(r)?;
890 let b: B = Readable::read(r)?;
894 impl<A: Writeable, B: Writeable> Writeable for (A, B) {
895 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
901 impl<A: Readable, B: Readable, C: Readable> Readable for (A, B, C) {
902 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
903 let a: A = Readable::read(r)?;
904 let b: B = Readable::read(r)?;
905 let c: C = Readable::read(r)?;
909 impl<A: Writeable, B: Writeable, C: Writeable> Writeable for (A, B, C) {
910 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
917 impl Writeable for () {
918 fn write<W: Writer>(&self, _: &mut W) -> Result<(), io::Error> {
922 impl Readable for () {
923 fn read<R: Read>(_r: &mut R) -> Result<Self, DecodeError> {
928 impl Writeable for String {
930 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
931 (self.len() as u16).write(w)?;
932 w.write_all(self.as_bytes())
935 impl Readable for String {
937 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
938 let v: Vec<u8> = Readable::read(r)?;
939 let ret = String::from_utf8(v).map_err(|_| DecodeError::InvalidValue)?;
944 impl Writeable for Duration {
946 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
947 self.as_secs().write(w)?;
948 self.subsec_nanos().write(w)
951 impl Readable for Duration {
953 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
954 let secs = Readable::read(r)?;
955 let nanos = Readable::read(r)?;
956 Ok(Duration::new(secs, nanos))