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.
13 use crate::prelude::*;
14 use crate::io::{self, Read, Write};
15 use crate::io_extras::{copy, sink};
17 use crate::sync::Mutex;
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 crate::ln::msgs::DecodeError;
34 use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
36 use crate::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 higher-level rust-lightning types implement allowing them to be read in
248 /// from a Read, requiring the implementer to provide the total length of the read.
249 pub(crate) trait LengthReadable where Self: Sized
251 /// Reads a Self in from the given LengthRead
252 fn read<R: LengthRead>(reader: &mut R) -> Result<Self, DecodeError>;
255 /// A trait that various rust-lightning types implement allowing them to (maybe) be read in from a Read
257 /// (C-not exported) as we only export serialization to/from byte arrays instead
258 pub trait MaybeReadable
261 /// Reads a Self in from the given Read
262 fn read<R: Read>(reader: &mut R) -> Result<Option<Self>, DecodeError>;
265 impl<T: Readable> MaybeReadable for T {
267 fn read<R: Read>(reader: &mut R) -> Result<Option<T>, DecodeError> {
268 Ok(Some(Readable::read(reader)?))
272 pub(crate) struct OptionDeserWrapper<T: Readable>(pub Option<T>);
273 impl<T: Readable> Readable for OptionDeserWrapper<T> {
275 fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
276 Ok(Self(Some(Readable::read(reader)?)))
279 /// When handling default_values, we want to map the default-value T directly
280 /// to a OptionDeserWrapper<T> in a way that works for `field: T = t;` as
281 /// well. Thus, we assume `Into<T> for T` does nothing and use that.
282 impl<T: Readable> From<T> for OptionDeserWrapper<T> {
283 fn from(t: T) -> OptionDeserWrapper<T> { OptionDeserWrapper(Some(t)) }
286 pub(crate) struct U48(pub u64);
287 impl Writeable for U48 {
289 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
290 writer.write_all(&be48_to_array(self.0))
293 impl Readable for U48 {
295 fn read<R: Read>(reader: &mut R) -> Result<U48, DecodeError> {
296 let mut buf = [0; 6];
297 reader.read_exact(&mut buf)?;
298 Ok(U48(slice_to_be48(&buf)))
302 /// Lightning TLV uses a custom variable-length integer called BigSize. It is similar to Bitcoin's
303 /// variable-length integers except that it is serialized in big-endian instead of little-endian.
305 /// Like Bitcoin's variable-length integer, it exhibits ambiguity in that certain values can be
306 /// encoded in several different ways, which we must check for at deserialization-time. Thus, if
307 /// you're looking for an example of a variable-length integer to use for your own project, move
308 /// along, this is a rather poor design.
309 pub struct BigSize(pub u64);
310 impl Writeable for BigSize {
312 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
315 (self.0 as u8).write(writer)
318 0xFDu8.write(writer)?;
319 (self.0 as u16).write(writer)
321 0x10000...0xFFFFFFFF => {
322 0xFEu8.write(writer)?;
323 (self.0 as u32).write(writer)
326 0xFFu8.write(writer)?;
327 (self.0 as u64).write(writer)
332 impl Readable for BigSize {
334 fn read<R: Read>(reader: &mut R) -> Result<BigSize, DecodeError> {
335 let n: u8 = Readable::read(reader)?;
338 let x: u64 = Readable::read(reader)?;
340 Err(DecodeError::InvalidValue)
346 let x: u32 = Readable::read(reader)?;
348 Err(DecodeError::InvalidValue)
350 Ok(BigSize(x as u64))
354 let x: u16 = Readable::read(reader)?;
356 Err(DecodeError::InvalidValue)
358 Ok(BigSize(x as u64))
361 n => Ok(BigSize(n as u64))
366 /// In TLV we occasionally send fields which only consist of, or potentially end with, a
367 /// variable-length integer which is simply truncated by skipping high zero bytes. This type
368 /// encapsulates such integers implementing Readable/Writeable for them.
369 #[cfg_attr(test, derive(PartialEq, Eq))]
370 #[derive(Clone, Debug)]
371 pub(crate) struct HighZeroBytesDroppedBigSize<T>(pub T);
373 macro_rules! impl_writeable_primitive {
374 ($val_type:ty, $len: expr) => {
375 impl Writeable for $val_type {
377 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
378 writer.write_all(&self.to_be_bytes())
381 impl Writeable for HighZeroBytesDroppedBigSize<$val_type> {
383 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
384 // Skip any full leading 0 bytes when writing (in BE):
385 writer.write_all(&self.0.to_be_bytes()[(self.0.leading_zeros()/8) as usize..$len])
388 impl Readable for $val_type {
390 fn read<R: Read>(reader: &mut R) -> Result<$val_type, DecodeError> {
391 let mut buf = [0; $len];
392 reader.read_exact(&mut buf)?;
393 Ok(<$val_type>::from_be_bytes(buf))
396 impl Readable for HighZeroBytesDroppedBigSize<$val_type> {
398 fn read<R: Read>(reader: &mut R) -> Result<HighZeroBytesDroppedBigSize<$val_type>, DecodeError> {
399 // We need to accept short reads (read_len == 0) as "EOF" and handle them as simply
400 // the high bytes being dropped. To do so, we start reading into the middle of buf
401 // and then convert the appropriate number of bytes with extra high bytes out of
403 let mut buf = [0; $len*2];
404 let mut read_len = reader.read(&mut buf[$len..])?;
405 let mut total_read_len = read_len;
406 while read_len != 0 && total_read_len != $len {
407 read_len = reader.read(&mut buf[($len + total_read_len)..])?;
408 total_read_len += read_len;
410 if total_read_len == 0 || buf[$len] != 0 {
411 let first_byte = $len - ($len - total_read_len);
412 let mut bytes = [0; $len];
413 bytes.copy_from_slice(&buf[first_byte..first_byte + $len]);
414 Ok(HighZeroBytesDroppedBigSize(<$val_type>::from_be_bytes(bytes)))
416 // If the encoding had extra zero bytes, return a failure even though we know
417 // what they meant (as the TLV test vectors require this)
418 Err(DecodeError::InvalidValue)
422 impl From<$val_type> for HighZeroBytesDroppedBigSize<$val_type> {
423 fn from(val: $val_type) -> Self { Self(val) }
428 impl_writeable_primitive!(u64, 8);
429 impl_writeable_primitive!(u32, 4);
430 impl_writeable_primitive!(u16, 2);
432 impl Writeable for u8 {
434 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
435 writer.write_all(&[*self])
438 impl Readable for u8 {
440 fn read<R: Read>(reader: &mut R) -> Result<u8, DecodeError> {
441 let mut buf = [0; 1];
442 reader.read_exact(&mut buf)?;
447 impl Writeable for bool {
449 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
450 writer.write_all(&[if *self {1} else {0}])
453 impl Readable for bool {
455 fn read<R: Read>(reader: &mut R) -> Result<bool, DecodeError> {
456 let mut buf = [0; 1];
457 reader.read_exact(&mut buf)?;
458 if buf[0] != 0 && buf[0] != 1 {
459 return Err(DecodeError::InvalidValue);
466 macro_rules! impl_array {
468 impl Writeable for [u8; $size]
471 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
476 impl Readable for [u8; $size]
479 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
480 let mut buf = [0u8; $size];
481 r.read_exact(&mut buf)?;
488 impl_array!(3); // for rgb
489 impl_array!(4); // for IPv4
490 impl_array!(12); // for OnionV2
491 impl_array!(16); // for IPv6
492 impl_array!(32); // for channel id & hmac
493 impl_array!(PUBLIC_KEY_SIZE); // for PublicKey
494 impl_array!(COMPACT_SIGNATURE_SIZE); // for Signature
495 impl_array!(1300); // for OnionPacket.hop_data
497 impl Writeable for [u16; 8] {
499 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
500 for v in self.iter() {
501 w.write_all(&v.to_be_bytes())?
507 impl Readable for [u16; 8] {
509 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
510 let mut buf = [0u8; 16];
511 r.read_exact(&mut buf)?;
512 let mut res = [0u16; 8];
513 for (idx, v) in res.iter_mut().enumerate() {
514 *v = (buf[idx] as u16) << 8 | (buf[idx + 1] as u16)
520 /// For variable-length values within TLV record where the length is encoded as part of the record.
521 /// Used to prevent encoding the length twice.
522 pub(crate) struct WithoutLength<T>(pub T);
524 impl Writeable for WithoutLength<&String> {
526 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
527 w.write_all(self.0.as_bytes())
530 impl Readable for WithoutLength<String> {
532 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
533 let v: WithoutLength<Vec<u8>> = Readable::read(r)?;
534 Ok(Self(String::from_utf8(v.0).map_err(|_| DecodeError::InvalidValue)?))
537 impl<'a> From<&'a String> for WithoutLength<&'a String> {
538 fn from(s: &'a String) -> Self { Self(s) }
541 impl<'a, T: Writeable> Writeable for WithoutLength<&'a Vec<T>> {
543 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
544 for ref v in self.0.iter() {
551 impl<T: MaybeReadable> Readable for WithoutLength<Vec<T>> {
553 fn read<R: Read>(mut reader: &mut R) -> Result<Self, DecodeError> {
554 let mut values = Vec::new();
556 let mut track_read = ReadTrackingReader::new(&mut reader);
557 match MaybeReadable::read(&mut track_read) {
558 Ok(Some(v)) => { values.push(v); },
560 // If we failed to read any bytes at all, we reached the end of our TLV
561 // stream and have simply exhausted all entries.
562 Err(ref e) if e == &DecodeError::ShortRead && !track_read.have_read => break,
563 Err(e) => return Err(e),
569 impl<'a, T> From<&'a Vec<T>> for WithoutLength<&'a Vec<T>> {
570 fn from(v: &'a Vec<T>) -> Self { Self(v) }
574 impl<K, V> Writeable for HashMap<K, V>
575 where K: Writeable + Eq + Hash,
579 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
580 (self.len() as u16).write(w)?;
581 for (key, value) in self.iter() {
589 impl<K, V> Readable for HashMap<K, V>
590 where K: Readable + Eq + Hash,
594 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
595 let len: u16 = Readable::read(r)?;
596 let mut ret = HashMap::with_capacity(len as usize);
599 let v_opt = V::read(r)?;
600 if let Some(v) = v_opt {
601 if ret.insert(k, v).is_some() {
602 return Err(DecodeError::InvalidValue);
611 impl<T> Writeable for HashSet<T>
612 where T: Writeable + Eq + Hash
615 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
616 (self.len() as u16).write(w)?;
617 for item in self.iter() {
624 impl<T> Readable for HashSet<T>
625 where T: Readable + Eq + Hash
628 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
629 let len: u16 = Readable::read(r)?;
630 let mut ret = HashSet::with_capacity(len as usize);
632 if !ret.insert(T::read(r)?) {
633 return Err(DecodeError::InvalidValue)
641 impl Writeable for Vec<u8> {
643 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
644 (self.len() as u16).write(w)?;
649 impl Readable for Vec<u8> {
651 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
652 let len: u16 = Readable::read(r)?;
653 let mut ret = Vec::with_capacity(len as usize);
654 ret.resize(len as usize, 0);
655 r.read_exact(&mut ret)?;
659 impl Writeable for Vec<Signature> {
661 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
662 (self.len() as u16).write(w)?;
663 for e in self.iter() {
670 impl Readable for Vec<Signature> {
672 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
673 let len: u16 = Readable::read(r)?;
674 let byte_size = (len as usize)
675 .checked_mul(COMPACT_SIGNATURE_SIZE)
676 .ok_or(DecodeError::BadLengthDescriptor)?;
677 if byte_size > MAX_BUF_SIZE {
678 return Err(DecodeError::BadLengthDescriptor);
680 let mut ret = Vec::with_capacity(len as usize);
681 for _ in 0..len { ret.push(Readable::read(r)?); }
686 impl Writeable for Script {
687 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
688 (self.len() as u16).write(w)?;
689 w.write_all(self.as_bytes())
693 impl Readable for Script {
694 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
695 let len = <u16 as Readable>::read(r)? as usize;
696 let mut buf = vec![0; len];
697 r.read_exact(&mut buf)?;
698 Ok(Script::from(buf))
702 impl Writeable for PublicKey {
703 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
704 self.serialize().write(w)
707 fn serialized_length(&self) -> usize {
712 impl Readable for PublicKey {
713 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
714 let buf: [u8; PUBLIC_KEY_SIZE] = Readable::read(r)?;
715 match PublicKey::from_slice(&buf) {
717 Err(_) => return Err(DecodeError::InvalidValue),
722 impl Writeable for SecretKey {
723 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
724 let mut ser = [0; SECRET_KEY_SIZE];
725 ser.copy_from_slice(&self[..]);
729 fn serialized_length(&self) -> usize {
734 impl Readable for SecretKey {
735 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
736 let buf: [u8; SECRET_KEY_SIZE] = Readable::read(r)?;
737 match SecretKey::from_slice(&buf) {
739 Err(_) => return Err(DecodeError::InvalidValue),
744 impl Writeable for Sha256dHash {
745 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
746 w.write_all(&self[..])
750 impl Readable for Sha256dHash {
751 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
752 use bitcoin::hashes::Hash;
754 let buf: [u8; 32] = Readable::read(r)?;
755 Ok(Sha256dHash::from_slice(&buf[..]).unwrap())
759 impl Writeable for Signature {
760 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
761 self.serialize_compact().write(w)
764 fn serialized_length(&self) -> usize {
765 COMPACT_SIGNATURE_SIZE
769 impl Readable for Signature {
770 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
771 let buf: [u8; COMPACT_SIGNATURE_SIZE] = Readable::read(r)?;
772 match Signature::from_compact(&buf) {
774 Err(_) => return Err(DecodeError::InvalidValue),
779 impl Writeable for PaymentPreimage {
780 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
785 impl Readable for PaymentPreimage {
786 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
787 let buf: [u8; 32] = Readable::read(r)?;
788 Ok(PaymentPreimage(buf))
792 impl Writeable for PaymentHash {
793 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
798 impl Readable for PaymentHash {
799 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
800 let buf: [u8; 32] = Readable::read(r)?;
805 impl Writeable for PaymentSecret {
806 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
811 impl Readable for PaymentSecret {
812 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
813 let buf: [u8; 32] = Readable::read(r)?;
814 Ok(PaymentSecret(buf))
818 impl<T: Writeable> Writeable for Box<T> {
819 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
824 impl<T: Readable> Readable for Box<T> {
825 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
826 Ok(Box::new(Readable::read(r)?))
830 impl<T: Writeable> Writeable for Option<T> {
831 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
833 None => 0u8.write(w)?,
835 BigSize(data.serialized_length() as u64 + 1).write(w)?;
843 impl<T: Readable> Readable for Option<T>
845 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
846 let len: BigSize = Readable::read(r)?;
850 let mut reader = FixedLengthReader::new(r, len - 1);
851 Ok(Some(Readable::read(&mut reader)?))
857 impl Writeable for Txid {
858 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
859 w.write_all(&self[..])
863 impl Readable for Txid {
864 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
865 use bitcoin::hashes::Hash;
867 let buf: [u8; 32] = Readable::read(r)?;
868 Ok(Txid::from_slice(&buf[..]).unwrap())
872 impl Writeable for BlockHash {
873 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
874 w.write_all(&self[..])
878 impl Readable for BlockHash {
879 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
880 use bitcoin::hashes::Hash;
882 let buf: [u8; 32] = Readable::read(r)?;
883 Ok(BlockHash::from_slice(&buf[..]).unwrap())
887 impl Writeable for OutPoint {
888 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
895 impl Readable for OutPoint {
896 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
897 let txid = Readable::read(r)?;
898 let vout = Readable::read(r)?;
906 macro_rules! impl_consensus_ser {
907 ($bitcoin_type: ty) => {
908 impl Writeable for $bitcoin_type {
909 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
910 match self.consensus_encode(&mut WriterWriteAdaptor(writer)) {
917 impl Readable for $bitcoin_type {
918 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
919 match consensus::encode::Decodable::consensus_decode(r) {
921 Err(consensus::encode::Error::Io(ref e)) if e.kind() == io::ErrorKind::UnexpectedEof => Err(DecodeError::ShortRead),
922 Err(consensus::encode::Error::Io(e)) => Err(DecodeError::Io(e.kind())),
923 Err(_) => Err(DecodeError::InvalidValue),
929 impl_consensus_ser!(Transaction);
930 impl_consensus_ser!(TxOut);
932 impl<T: Readable> Readable for Mutex<T> {
933 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
934 let t: T = Readable::read(r)?;
938 impl<T: Writeable> Writeable for Mutex<T> {
939 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
940 self.lock().unwrap().write(w)
944 impl<A: Readable, B: Readable> Readable for (A, B) {
945 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
946 let a: A = Readable::read(r)?;
947 let b: B = Readable::read(r)?;
951 impl<A: Writeable, B: Writeable> Writeable for (A, B) {
952 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
958 impl<A: Readable, B: Readable, C: Readable> Readable for (A, B, C) {
959 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
960 let a: A = Readable::read(r)?;
961 let b: B = Readable::read(r)?;
962 let c: C = Readable::read(r)?;
966 impl<A: Writeable, B: Writeable, C: Writeable> Writeable for (A, B, C) {
967 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
974 impl Writeable for () {
975 fn write<W: Writer>(&self, _: &mut W) -> Result<(), io::Error> {
979 impl Readable for () {
980 fn read<R: Read>(_r: &mut R) -> Result<Self, DecodeError> {
985 impl Writeable for String {
987 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
988 (self.len() as u16).write(w)?;
989 w.write_all(self.as_bytes())
992 impl Readable for String {
994 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
995 let v: Vec<u8> = Readable::read(r)?;
996 let ret = String::from_utf8(v).map_err(|_| DecodeError::InvalidValue)?;
1001 /// Represents a hostname for serialization purposes.
1002 /// Only the character set and length will be validated.
1003 /// The character set consists of ASCII alphanumeric characters, hyphens, and periods.
1004 /// Its length is guaranteed to be representable by a single byte.
1005 /// This serialization is used by BOLT 7 hostnames.
1006 #[derive(Clone, Debug, PartialEq, Eq)]
1007 pub struct Hostname(String);
1009 /// Returns the length of the hostname.
1010 pub fn len(&self) -> u8 {
1011 (&self.0).len() as u8
1014 impl Deref for Hostname {
1015 type Target = String;
1017 fn deref(&self) -> &Self::Target {
1021 impl From<Hostname> for String {
1022 fn from(hostname: Hostname) -> Self {
1026 impl TryFrom<Vec<u8>> for Hostname {
1029 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
1030 if let Ok(s) = String::from_utf8(bytes) {
1031 Hostname::try_from(s)
1037 impl TryFrom<String> for Hostname {
1040 fn try_from(s: String) -> Result<Self, Self::Error> {
1041 if s.len() <= 255 && s.chars().all(|c|
1042 c.is_ascii_alphanumeric() ||
1052 impl Writeable for Hostname {
1054 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1055 self.len().write(w)?;
1056 w.write_all(self.as_bytes())
1059 impl Readable for Hostname {
1061 fn read<R: Read>(r: &mut R) -> Result<Hostname, DecodeError> {
1062 let len: u8 = Readable::read(r)?;
1063 let mut vec = Vec::with_capacity(len.into());
1064 vec.resize(len.into(), 0);
1065 r.read_exact(&mut vec)?;
1066 Hostname::try_from(vec).map_err(|_| DecodeError::InvalidValue)
1070 impl Writeable for Duration {
1072 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1073 self.as_secs().write(w)?;
1074 self.subsec_nanos().write(w)
1077 impl Readable for Duration {
1079 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1080 let secs = Readable::read(r)?;
1081 let nanos = Readable::read(r)?;
1082 Ok(Duration::new(secs, nanos))
1088 use core::convert::TryFrom;
1089 use crate::util::ser::{Readable, Hostname, Writeable};
1092 fn hostname_conversion() {
1093 assert_eq!(Hostname::try_from(String::from("a-test.com")).unwrap().as_str(), "a-test.com");
1095 assert!(Hostname::try_from(String::from("\"")).is_err());
1096 assert!(Hostname::try_from(String::from("$")).is_err());
1097 assert!(Hostname::try_from(String::from("⚡")).is_err());
1098 let mut large_vec = Vec::with_capacity(256);
1099 large_vec.resize(256, b'A');
1100 assert!(Hostname::try_from(String::from_utf8(large_vec).unwrap()).is_err());
1104 fn hostname_serialization() {
1105 let hostname = Hostname::try_from(String::from("test")).unwrap();
1106 let mut buf: Vec<u8> = Vec::new();
1107 hostname.write(&mut buf).unwrap();
1108 assert_eq!(Hostname::read(&mut buf.as_slice()).unwrap().as_str(), "test");