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};
19 use core::convert::TryFrom;
22 use bitcoin::secp256k1::{PublicKey, SecretKey};
23 use bitcoin::secp256k1::constants::{PUBLIC_KEY_SIZE, SECRET_KEY_SIZE, COMPACT_SIGNATURE_SIZE};
24 use bitcoin::secp256k1::ecdsa::Signature;
25 use bitcoin::blockdata::script::Script;
26 use bitcoin::blockdata::transaction::{OutPoint, Transaction, TxOut};
27 use bitcoin::consensus;
28 use bitcoin::consensus::Encodable;
29 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
30 use bitcoin::hash_types::{Txid, BlockHash};
31 use core::marker::Sized;
32 use core::time::Duration;
33 use ln::msgs::DecodeError;
34 use ln::{PaymentPreimage, PaymentHash, PaymentSecret};
36 use util::byte_utils::{be48_to_array, slice_to_be48};
38 /// serialization buffer size
39 pub const MAX_BUF_SIZE: usize = 64 * 1024;
41 /// A simplified version of std::io::Write that exists largely for backwards compatibility.
42 /// An impl is provided for any type that also impls std::io::Write.
44 /// (C-not exported) as we only export serialization to/from byte arrays instead
46 /// Writes the given buf out. See std::io::Write::write_all for more
47 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error>;
50 impl<W: Write> Writer for W {
52 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
53 <Self as io::Write>::write_all(self, buf)
57 pub(crate) struct WriterWriteAdaptor<'a, W: Writer + 'a>(pub &'a mut W);
58 impl<'a, W: Writer + 'a> Write for WriterWriteAdaptor<'a, W> {
60 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
64 fn write(&mut self, buf: &[u8]) -> Result<usize, io::Error> {
65 self.0.write_all(buf)?;
69 fn flush(&mut self) -> Result<(), io::Error> {
74 pub(crate) struct VecWriter(pub Vec<u8>);
75 impl Writer for VecWriter {
77 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
78 self.0.extend_from_slice(buf);
83 /// Writer that only tracks the amount of data written - useful if you need to calculate the length
84 /// of some data when serialized but don't yet need the full data.
85 pub(crate) struct LengthCalculatingWriter(pub usize);
86 impl Writer for LengthCalculatingWriter {
88 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
94 /// Essentially std::io::Take but a bit simpler and with a method to walk the underlying stream
95 /// forward to ensure we always consume exactly the fixed length specified.
96 pub(crate) struct FixedLengthReader<R: Read> {
101 impl<R: Read> FixedLengthReader<R> {
102 pub fn new(read: R, total_bytes: u64) -> Self {
103 Self { read, bytes_read: 0, total_bytes }
107 pub fn bytes_remain(&mut self) -> bool {
108 self.bytes_read != self.total_bytes
112 pub fn eat_remaining(&mut self) -> Result<(), DecodeError> {
113 copy(self, &mut sink()).unwrap();
114 if self.bytes_read != self.total_bytes {
115 Err(DecodeError::ShortRead)
121 impl<R: Read> Read for FixedLengthReader<R> {
123 fn read(&mut self, dest: &mut [u8]) -> Result<usize, io::Error> {
124 if self.total_bytes == self.bytes_read {
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)]) {
130 self.bytes_read += v as u64;
139 impl<R: Read> LengthRead for FixedLengthReader<R> {
141 fn total_bytes(&self) -> u64 {
146 /// A Read which tracks whether any bytes have been read at all. This allows us to distinguish
147 /// between "EOF reached before we started" and "EOF reached mid-read".
148 pub(crate) struct ReadTrackingReader<R: Read> {
152 impl<R: Read> ReadTrackingReader<R> {
153 pub fn new(read: R) -> Self {
154 Self { read, have_read: false }
157 impl<R: Read> Read for ReadTrackingReader<R> {
159 fn read(&mut self, dest: &mut [u8]) -> Result<usize, io::Error> {
160 match self.read.read(dest) {
163 self.have_read = true;
171 /// A trait that various rust-lightning types implement allowing them to be written out to a Writer
173 /// (C-not exported) as we only export serialization to/from byte arrays instead
174 pub trait Writeable {
175 /// Writes self out to the given Writer
176 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error>;
178 /// Writes self out to a Vec<u8>
179 fn encode(&self) -> Vec<u8> {
180 let mut msg = VecWriter(Vec::new());
181 self.write(&mut msg).unwrap();
185 /// Writes self out to a Vec<u8>
187 fn encode_with_len(&self) -> Vec<u8> {
188 let mut msg = VecWriter(Vec::new());
189 0u16.write(&mut msg).unwrap();
190 self.write(&mut msg).unwrap();
191 let len = msg.0.len();
192 msg.0[..2].copy_from_slice(&(len as u16 - 2).to_be_bytes());
196 /// Gets the length of this object after it has been serialized. This can be overridden to
197 /// optimize cases where we prepend an object with its length.
198 // Note that LLVM optimizes this away in most cases! Check that it isn't before you override!
200 fn serialized_length(&self) -> usize {
201 let mut len_calc = LengthCalculatingWriter(0);
202 self.write(&mut len_calc).expect("No in-memory data may fail to serialize");
207 impl<'a, T: Writeable> Writeable for &'a T {
208 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { (*self).write(writer) }
211 /// A trait that various rust-lightning types implement allowing them to be read in from a Read
213 /// (C-not exported) as we only export serialization to/from byte arrays instead
217 /// Reads a Self in from the given Read
218 fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError>;
221 /// A trait that various higher-level rust-lightning types implement allowing them to be read in
222 /// from a Read given some additional set of arguments which is required to deserialize.
224 /// (C-not exported) as we only export serialization to/from byte arrays instead
225 pub trait ReadableArgs<P>
228 /// Reads a Self in from the given Read
229 fn read<R: Read>(reader: &mut R, params: P) -> Result<Self, DecodeError>;
232 /// A std::io::Read that also provides the total bytes available to read.
233 pub(crate) trait LengthRead: Read {
234 /// The total number of bytes available to read.
235 fn total_bytes(&self) -> u64;
238 /// A trait that various higher-level rust-lightning types implement allowing them to be read in
239 /// from a Read given some additional set of arguments which is required to deserialize, requiring
240 /// the implementer to provide the total length of the read.
241 pub(crate) trait LengthReadableArgs<P> where Self: Sized
243 /// Reads a Self in from the given LengthRead
244 fn read<R: LengthRead>(reader: &mut R, params: P) -> Result<Self, DecodeError>;
247 /// A trait that various rust-lightning types implement allowing them to (maybe) be read in from a Read
249 /// (C-not exported) as we only export serialization to/from byte arrays instead
250 pub trait MaybeReadable
253 /// Reads a Self in from the given Read
254 fn read<R: Read>(reader: &mut R) -> Result<Option<Self>, DecodeError>;
257 impl<T: Readable> MaybeReadable for T {
259 fn read<R: Read>(reader: &mut R) -> Result<Option<T>, DecodeError> {
260 Ok(Some(Readable::read(reader)?))
264 pub(crate) struct OptionDeserWrapper<T: Readable>(pub Option<T>);
265 impl<T: Readable> Readable for OptionDeserWrapper<T> {
267 fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
268 Ok(Self(Some(Readable::read(reader)?)))
271 /// When handling default_values, we want to map the default-value T directly
272 /// to a OptionDeserWrapper<T> in a way that works for `field: T = t;` as
273 /// well. Thus, we assume `Into<T> for T` does nothing and use that.
274 impl<T: Readable> From<T> for OptionDeserWrapper<T> {
275 fn from(t: T) -> OptionDeserWrapper<T> { OptionDeserWrapper(Some(t)) }
278 /// Wrapper to write each element of a Vec with no length prefix
279 pub(crate) struct VecWriteWrapper<'a, T: Writeable>(pub &'a Vec<T>);
280 impl<'a, T: Writeable> Writeable for VecWriteWrapper<'a, T> {
282 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
283 for ref v in self.0.iter() {
290 /// Wrapper to read elements from a given stream until it reaches the end of the stream.
291 pub(crate) struct VecReadWrapper<T>(pub Vec<T>);
292 impl<T: MaybeReadable> Readable for VecReadWrapper<T> {
294 fn read<R: Read>(mut reader: &mut R) -> Result<Self, DecodeError> {
295 let mut values = Vec::new();
297 let mut track_read = ReadTrackingReader::new(&mut reader);
298 match MaybeReadable::read(&mut track_read) {
299 Ok(Some(v)) => { values.push(v); },
301 // If we failed to read any bytes at all, we reached the end of our TLV
302 // stream and have simply exhausted all entries.
303 Err(ref e) if e == &DecodeError::ShortRead && !track_read.have_read => break,
304 Err(e) => return Err(e),
311 pub(crate) struct U48(pub u64);
312 impl Writeable for U48 {
314 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
315 writer.write_all(&be48_to_array(self.0))
318 impl Readable for U48 {
320 fn read<R: Read>(reader: &mut R) -> Result<U48, DecodeError> {
321 let mut buf = [0; 6];
322 reader.read_exact(&mut buf)?;
323 Ok(U48(slice_to_be48(&buf)))
327 /// Lightning TLV uses a custom variable-length integer called BigSize. It is similar to Bitcoin's
328 /// variable-length integers except that it is serialized in big-endian instead of little-endian.
330 /// Like Bitcoin's variable-length integer, it exhibits ambiguity in that certain values can be
331 /// encoded in several different ways, which we must check for at deserialization-time. Thus, if
332 /// you're looking for an example of a variable-length integer to use for your own project, move
333 /// along, this is a rather poor design.
334 pub struct BigSize(pub u64);
335 impl Writeable for BigSize {
337 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
340 (self.0 as u8).write(writer)
343 0xFDu8.write(writer)?;
344 (self.0 as u16).write(writer)
346 0x10000...0xFFFFFFFF => {
347 0xFEu8.write(writer)?;
348 (self.0 as u32).write(writer)
351 0xFFu8.write(writer)?;
352 (self.0 as u64).write(writer)
357 impl Readable for BigSize {
359 fn read<R: Read>(reader: &mut R) -> Result<BigSize, DecodeError> {
360 let n: u8 = Readable::read(reader)?;
363 let x: u64 = Readable::read(reader)?;
365 Err(DecodeError::InvalidValue)
371 let x: u32 = Readable::read(reader)?;
373 Err(DecodeError::InvalidValue)
375 Ok(BigSize(x as u64))
379 let x: u16 = Readable::read(reader)?;
381 Err(DecodeError::InvalidValue)
383 Ok(BigSize(x as u64))
386 n => Ok(BigSize(n as u64))
391 /// In TLV we occasionally send fields which only consist of, or potentially end with, a
392 /// variable-length integer which is simply truncated by skipping high zero bytes. This type
393 /// encapsulates such integers implementing Readable/Writeable for them.
394 #[cfg_attr(test, derive(PartialEq, Debug))]
395 pub(crate) struct HighZeroBytesDroppedVarInt<T>(pub T);
397 macro_rules! impl_writeable_primitive {
398 ($val_type:ty, $len: expr) => {
399 impl Writeable for $val_type {
401 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
402 writer.write_all(&self.to_be_bytes())
405 impl Writeable for HighZeroBytesDroppedVarInt<$val_type> {
407 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
408 // Skip any full leading 0 bytes when writing (in BE):
409 writer.write_all(&self.0.to_be_bytes()[(self.0.leading_zeros()/8) as usize..$len])
412 impl Readable for $val_type {
414 fn read<R: Read>(reader: &mut R) -> Result<$val_type, DecodeError> {
415 let mut buf = [0; $len];
416 reader.read_exact(&mut buf)?;
417 Ok(<$val_type>::from_be_bytes(buf))
420 impl Readable for HighZeroBytesDroppedVarInt<$val_type> {
422 fn read<R: Read>(reader: &mut R) -> Result<HighZeroBytesDroppedVarInt<$val_type>, DecodeError> {
423 // We need to accept short reads (read_len == 0) as "EOF" and handle them as simply
424 // the high bytes being dropped. To do so, we start reading into the middle of buf
425 // and then convert the appropriate number of bytes with extra high bytes out of
427 let mut buf = [0; $len*2];
428 let mut read_len = reader.read(&mut buf[$len..])?;
429 let mut total_read_len = read_len;
430 while read_len != 0 && total_read_len != $len {
431 read_len = reader.read(&mut buf[($len + total_read_len)..])?;
432 total_read_len += read_len;
434 if total_read_len == 0 || buf[$len] != 0 {
435 let first_byte = $len - ($len - total_read_len);
436 let mut bytes = [0; $len];
437 bytes.copy_from_slice(&buf[first_byte..first_byte + $len]);
438 Ok(HighZeroBytesDroppedVarInt(<$val_type>::from_be_bytes(bytes)))
440 // If the encoding had extra zero bytes, return a failure even though we know
441 // what they meant (as the TLV test vectors require this)
442 Err(DecodeError::InvalidValue)
449 impl_writeable_primitive!(u64, 8);
450 impl_writeable_primitive!(u32, 4);
451 impl_writeable_primitive!(u16, 2);
453 impl Writeable for u8 {
455 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
456 writer.write_all(&[*self])
459 impl Readable for u8 {
461 fn read<R: Read>(reader: &mut R) -> Result<u8, DecodeError> {
462 let mut buf = [0; 1];
463 reader.read_exact(&mut buf)?;
468 impl Writeable for bool {
470 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
471 writer.write_all(&[if *self {1} else {0}])
474 impl Readable for bool {
476 fn read<R: Read>(reader: &mut R) -> Result<bool, DecodeError> {
477 let mut buf = [0; 1];
478 reader.read_exact(&mut buf)?;
479 if buf[0] != 0 && buf[0] != 1 {
480 return Err(DecodeError::InvalidValue);
487 macro_rules! impl_array {
489 impl Writeable for [u8; $size]
492 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
497 impl Readable for [u8; $size]
500 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
501 let mut buf = [0u8; $size];
502 r.read_exact(&mut buf)?;
509 impl_array!(3); // for rgb
510 impl_array!(4); // for IPv4
511 impl_array!(12); // for OnionV2
512 impl_array!(16); // for IPv6
513 impl_array!(32); // for channel id & hmac
514 impl_array!(PUBLIC_KEY_SIZE); // for PublicKey
515 impl_array!(COMPACT_SIGNATURE_SIZE); // for Signature
516 impl_array!(1300); // for OnionPacket.hop_data
519 impl<K, V> Writeable for HashMap<K, V>
520 where K: Writeable + Eq + Hash,
524 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
525 (self.len() as u16).write(w)?;
526 for (key, value) in self.iter() {
534 impl<K, V> Readable for HashMap<K, V>
535 where K: Readable + Eq + Hash,
539 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
540 let len: u16 = Readable::read(r)?;
541 let mut ret = HashMap::with_capacity(len as usize);
544 let v_opt = V::read(r)?;
545 if let Some(v) = v_opt {
546 if ret.insert(k, v).is_some() {
547 return Err(DecodeError::InvalidValue);
556 impl<T> Writeable for HashSet<T>
557 where T: Writeable + Eq + Hash
560 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
561 (self.len() as u16).write(w)?;
562 for item in self.iter() {
569 impl<T> Readable for HashSet<T>
570 where T: Readable + Eq + Hash
573 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
574 let len: u16 = Readable::read(r)?;
575 let mut ret = HashSet::with_capacity(len as usize);
577 if !ret.insert(T::read(r)?) {
578 return Err(DecodeError::InvalidValue)
586 impl Writeable for Vec<u8> {
588 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
589 (self.len() as u16).write(w)?;
594 impl Readable for Vec<u8> {
596 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
597 let len: u16 = Readable::read(r)?;
598 let mut ret = Vec::with_capacity(len as usize);
599 ret.resize(len as usize, 0);
600 r.read_exact(&mut ret)?;
604 impl Writeable for Vec<Signature> {
606 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
607 (self.len() as u16).write(w)?;
608 for e in self.iter() {
615 impl Readable for Vec<Signature> {
617 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
618 let len: u16 = Readable::read(r)?;
619 let byte_size = (len as usize)
620 .checked_mul(COMPACT_SIGNATURE_SIZE)
621 .ok_or(DecodeError::BadLengthDescriptor)?;
622 if byte_size > MAX_BUF_SIZE {
623 return Err(DecodeError::BadLengthDescriptor);
625 let mut ret = Vec::with_capacity(len as usize);
626 for _ in 0..len { ret.push(Readable::read(r)?); }
631 impl Writeable for Script {
632 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
633 (self.len() as u16).write(w)?;
634 w.write_all(self.as_bytes())
638 impl Readable for Script {
639 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
640 let len = <u16 as Readable>::read(r)? as usize;
641 let mut buf = vec![0; len];
642 r.read_exact(&mut buf)?;
643 Ok(Script::from(buf))
647 impl Writeable for PublicKey {
648 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
649 self.serialize().write(w)
652 fn serialized_length(&self) -> usize {
657 impl Readable for PublicKey {
658 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
659 let buf: [u8; PUBLIC_KEY_SIZE] = Readable::read(r)?;
660 match PublicKey::from_slice(&buf) {
662 Err(_) => return Err(DecodeError::InvalidValue),
667 impl Writeable for SecretKey {
668 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
669 let mut ser = [0; SECRET_KEY_SIZE];
670 ser.copy_from_slice(&self[..]);
674 fn serialized_length(&self) -> usize {
679 impl Readable for SecretKey {
680 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
681 let buf: [u8; SECRET_KEY_SIZE] = Readable::read(r)?;
682 match SecretKey::from_slice(&buf) {
684 Err(_) => return Err(DecodeError::InvalidValue),
689 impl Writeable for Sha256dHash {
690 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
691 w.write_all(&self[..])
695 impl Readable for Sha256dHash {
696 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
697 use bitcoin::hashes::Hash;
699 let buf: [u8; 32] = Readable::read(r)?;
700 Ok(Sha256dHash::from_slice(&buf[..]).unwrap())
704 impl Writeable for Signature {
705 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
706 self.serialize_compact().write(w)
709 fn serialized_length(&self) -> usize {
710 COMPACT_SIGNATURE_SIZE
714 impl Readable for Signature {
715 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
716 let buf: [u8; COMPACT_SIGNATURE_SIZE] = Readable::read(r)?;
717 match Signature::from_compact(&buf) {
719 Err(_) => return Err(DecodeError::InvalidValue),
724 impl Writeable for PaymentPreimage {
725 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
730 impl Readable for PaymentPreimage {
731 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
732 let buf: [u8; 32] = Readable::read(r)?;
733 Ok(PaymentPreimage(buf))
737 impl Writeable for PaymentHash {
738 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
743 impl Readable for PaymentHash {
744 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
745 let buf: [u8; 32] = Readable::read(r)?;
750 impl Writeable for PaymentSecret {
751 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
756 impl Readable for PaymentSecret {
757 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
758 let buf: [u8; 32] = Readable::read(r)?;
759 Ok(PaymentSecret(buf))
763 impl<T: Writeable> Writeable for Box<T> {
764 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
769 impl<T: Readable> Readable for Box<T> {
770 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
771 Ok(Box::new(Readable::read(r)?))
775 impl<T: Writeable> Writeable for Option<T> {
776 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
778 None => 0u8.write(w)?,
780 BigSize(data.serialized_length() as u64 + 1).write(w)?;
788 impl<T: Readable> Readable for Option<T>
790 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
791 let len: BigSize = Readable::read(r)?;
795 let mut reader = FixedLengthReader::new(r, len - 1);
796 Ok(Some(Readable::read(&mut reader)?))
802 impl Writeable for Txid {
803 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
804 w.write_all(&self[..])
808 impl Readable for Txid {
809 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
810 use bitcoin::hashes::Hash;
812 let buf: [u8; 32] = Readable::read(r)?;
813 Ok(Txid::from_slice(&buf[..]).unwrap())
817 impl Writeable for BlockHash {
818 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
819 w.write_all(&self[..])
823 impl Readable for BlockHash {
824 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
825 use bitcoin::hashes::Hash;
827 let buf: [u8; 32] = Readable::read(r)?;
828 Ok(BlockHash::from_slice(&buf[..]).unwrap())
832 impl Writeable for OutPoint {
833 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
840 impl Readable for OutPoint {
841 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
842 let txid = Readable::read(r)?;
843 let vout = Readable::read(r)?;
851 macro_rules! impl_consensus_ser {
852 ($bitcoin_type: ty) => {
853 impl Writeable for $bitcoin_type {
854 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
855 match self.consensus_encode(WriterWriteAdaptor(writer)) {
862 impl Readable for $bitcoin_type {
863 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
864 match consensus::encode::Decodable::consensus_decode(r) {
866 Err(consensus::encode::Error::Io(ref e)) if e.kind() == io::ErrorKind::UnexpectedEof => Err(DecodeError::ShortRead),
867 Err(consensus::encode::Error::Io(e)) => Err(DecodeError::Io(e.kind())),
868 Err(_) => Err(DecodeError::InvalidValue),
874 impl_consensus_ser!(Transaction);
875 impl_consensus_ser!(TxOut);
877 impl<T: Readable> Readable for Mutex<T> {
878 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
879 let t: T = Readable::read(r)?;
883 impl<T: Writeable> Writeable for Mutex<T> {
884 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
885 self.lock().unwrap().write(w)
889 impl<A: Readable, B: Readable> Readable for (A, B) {
890 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
891 let a: A = Readable::read(r)?;
892 let b: B = Readable::read(r)?;
896 impl<A: Writeable, B: Writeable> Writeable for (A, B) {
897 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
903 impl<A: Readable, B: Readable, C: Readable> Readable for (A, B, C) {
904 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
905 let a: A = Readable::read(r)?;
906 let b: B = Readable::read(r)?;
907 let c: C = Readable::read(r)?;
911 impl<A: Writeable, B: Writeable, C: Writeable> Writeable for (A, B, C) {
912 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
919 impl Writeable for () {
920 fn write<W: Writer>(&self, _: &mut W) -> Result<(), io::Error> {
924 impl Readable for () {
925 fn read<R: Read>(_r: &mut R) -> Result<Self, DecodeError> {
930 impl Writeable for String {
932 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
933 (self.len() as u16).write(w)?;
934 w.write_all(self.as_bytes())
937 impl Readable for String {
939 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
940 let v: Vec<u8> = Readable::read(r)?;
941 let ret = String::from_utf8(v).map_err(|_| DecodeError::InvalidValue)?;
946 /// Represents a hostname for serialization purposes.
947 /// Only the character set and length will be validated.
948 /// The character set consists of ASCII alphanumeric characters, hyphens, and periods.
949 /// Its length is guaranteed to be representable by a single byte.
950 /// This serialization is used by BOLT 7 hostnames.
951 #[derive(Clone, Debug, PartialEq)]
952 pub struct Hostname(String);
954 /// Returns the length of the hostname.
955 pub fn len(&self) -> u8 {
956 (&self.0).len() as u8
959 impl Deref for Hostname {
960 type Target = String;
962 fn deref(&self) -> &Self::Target {
966 impl From<Hostname> for String {
967 fn from(hostname: Hostname) -> Self {
971 impl TryFrom<Vec<u8>> for Hostname {
974 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
975 if let Ok(s) = String::from_utf8(bytes) {
976 Hostname::try_from(s)
982 impl TryFrom<String> for Hostname {
985 fn try_from(s: String) -> Result<Self, Self::Error> {
986 if s.len() <= 255 && s.chars().all(|c|
987 c.is_ascii_alphanumeric() ||
997 impl Writeable for Hostname {
999 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1000 self.len().write(w)?;
1001 w.write_all(self.as_bytes())
1004 impl Readable for Hostname {
1006 fn read<R: Read>(r: &mut R) -> Result<Hostname, DecodeError> {
1007 let len: u8 = Readable::read(r)?;
1008 let mut vec = Vec::with_capacity(len.into());
1009 vec.resize(len.into(), 0);
1010 r.read_exact(&mut vec)?;
1011 Hostname::try_from(vec).map_err(|_| DecodeError::InvalidValue)
1015 impl Writeable for Duration {
1017 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1018 self.as_secs().write(w)?;
1019 self.subsec_nanos().write(w)
1022 impl Readable for Duration {
1024 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1025 let secs = Readable::read(r)?;
1026 let nanos = Readable::read(r)?;
1027 Ok(Duration::new(secs, nanos))
1033 use core::convert::TryFrom;
1034 use util::ser::{Readable, Hostname, Writeable};
1037 fn hostname_conversion() {
1038 assert_eq!(Hostname::try_from(String::from("a-test.com")).unwrap().as_str(), "a-test.com");
1040 assert!(Hostname::try_from(String::from("\"")).is_err());
1041 assert!(Hostname::try_from(String::from("$")).is_err());
1042 assert!(Hostname::try_from(String::from("⚡")).is_err());
1043 let mut large_vec = Vec::with_capacity(256);
1044 large_vec.resize(256, b'A');
1045 assert!(Hostname::try_from(String::from_utf8(large_vec).unwrap()).is_err());
1049 fn hostname_serialization() {
1050 let hostname = Hostname::try_from(String::from("test")).unwrap();
1051 let mut buf: Vec<u8> = Vec::new();
1052 hostname.write(&mut buf).unwrap();
1053 assert_eq!(Hostname::read(&mut buf.as_slice()).unwrap().as_str(), "test");