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, Seek, 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, SCHNORR_SIGNATURE_SIZE};
24 use bitcoin::secp256k1::ecdsa;
25 use bitcoin::secp256k1::schnorr;
26 use bitcoin::blockdata::constants::ChainHash;
27 use bitcoin::blockdata::script::Script;
28 use bitcoin::blockdata::transaction::{OutPoint, Transaction, TxOut};
29 use bitcoin::consensus;
30 use bitcoin::consensus::Encodable;
31 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
32 use bitcoin::hash_types::{Txid, BlockHash};
33 use core::marker::Sized;
34 use core::time::Duration;
35 use crate::ln::msgs::DecodeError;
36 use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
38 use crate::util::byte_utils::{be48_to_array, slice_to_be48};
40 /// serialization buffer size
41 pub const MAX_BUF_SIZE: usize = 64 * 1024;
43 /// A simplified version of std::io::Write that exists largely for backwards compatibility.
44 /// An impl is provided for any type that also impls std::io::Write.
46 /// (C-not exported) as we only export serialization to/from byte arrays instead
48 /// Writes the given buf out. See std::io::Write::write_all for more
49 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error>;
52 impl<W: Write> Writer for W {
54 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
55 <Self as io::Write>::write_all(self, buf)
59 pub(crate) struct WriterWriteAdaptor<'a, W: Writer + 'a>(pub &'a mut W);
60 impl<'a, W: Writer + 'a> Write for WriterWriteAdaptor<'a, W> {
62 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
66 fn write(&mut self, buf: &[u8]) -> Result<usize, io::Error> {
67 self.0.write_all(buf)?;
71 fn flush(&mut self) -> Result<(), io::Error> {
76 pub(crate) struct VecWriter(pub Vec<u8>);
77 impl Writer for VecWriter {
79 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
80 self.0.extend_from_slice(buf);
85 /// Writer that only tracks the amount of data written - useful if you need to calculate the length
86 /// of some data when serialized but don't yet need the full data.
87 pub struct LengthCalculatingWriter(pub usize);
88 impl Writer for LengthCalculatingWriter {
90 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
96 /// Essentially [`std::io::Take`] but a bit simpler and with a method to walk the underlying stream
97 /// forward to ensure we always consume exactly the fixed length specified.
98 pub struct FixedLengthReader<R: Read> {
103 impl<R: Read> FixedLengthReader<R> {
104 /// Returns a new [`FixedLengthReader`].
105 pub fn new(read: R, total_bytes: u64) -> Self {
106 Self { read, bytes_read: 0, total_bytes }
109 /// Returns whether some bytes are remaining or not.
111 pub fn bytes_remain(&mut self) -> bool {
112 self.bytes_read != self.total_bytes
115 /// Consumes the remaining bytes.
117 pub fn eat_remaining(&mut self) -> Result<(), DecodeError> {
118 copy(self, &mut sink()).unwrap();
119 if self.bytes_read != self.total_bytes {
120 Err(DecodeError::ShortRead)
126 impl<R: Read> Read for FixedLengthReader<R> {
128 fn read(&mut self, dest: &mut [u8]) -> Result<usize, io::Error> {
129 if self.total_bytes == self.bytes_read {
132 let read_len = cmp::min(dest.len() as u64, self.total_bytes - self.bytes_read);
133 match self.read.read(&mut dest[0..(read_len as usize)]) {
135 self.bytes_read += v as u64;
144 impl<R: Read> LengthRead for FixedLengthReader<R> {
146 fn total_bytes(&self) -> u64 {
151 /// A [`Read`] implementation which tracks whether any bytes have been read at all. This allows us to distinguish
152 /// between "EOF reached before we started" and "EOF reached mid-read".
153 pub struct ReadTrackingReader<R: Read> {
155 /// Returns whether we have read from this reader or not yet.
158 impl<R: Read> ReadTrackingReader<R> {
159 /// Returns a new [`ReadTrackingReader`].
160 pub fn new(read: R) -> Self {
161 Self { read, have_read: false }
164 impl<R: Read> Read for ReadTrackingReader<R> {
166 fn read(&mut self, dest: &mut [u8]) -> Result<usize, io::Error> {
167 match self.read.read(dest) {
170 self.have_read = true;
178 /// A trait that various rust-lightning types implement allowing them to be written out to a Writer
180 /// (C-not exported) as we only export serialization to/from byte arrays instead
181 pub trait Writeable {
182 /// Writes self out to the given Writer
183 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error>;
185 /// Writes self out to a Vec<u8>
186 fn encode(&self) -> Vec<u8> {
187 let mut msg = VecWriter(Vec::new());
188 self.write(&mut msg).unwrap();
192 /// Writes self out to a Vec<u8>
194 fn encode_with_len(&self) -> Vec<u8> {
195 let mut msg = VecWriter(Vec::new());
196 0u16.write(&mut msg).unwrap();
197 self.write(&mut msg).unwrap();
198 let len = msg.0.len();
199 msg.0[..2].copy_from_slice(&(len as u16 - 2).to_be_bytes());
203 /// Gets the length of this object after it has been serialized. This can be overridden to
204 /// optimize cases where we prepend an object with its length.
205 // Note that LLVM optimizes this away in most cases! Check that it isn't before you override!
207 fn serialized_length(&self) -> usize {
208 let mut len_calc = LengthCalculatingWriter(0);
209 self.write(&mut len_calc).expect("No in-memory data may fail to serialize");
214 impl<'a, T: Writeable> Writeable for &'a T {
215 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { (*self).write(writer) }
218 /// A trait that various rust-lightning types implement allowing them to be read in from a Read
220 /// (C-not exported) as we only export serialization to/from byte arrays instead
224 /// Reads a Self in from the given Read
225 fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError>;
228 /// A trait that various rust-lightning types implement allowing them to be read in from a
230 pub(crate) trait SeekReadable where Self: Sized {
231 /// Reads a Self in from the given Read
232 fn read<R: Read + Seek>(reader: &mut R) -> Result<Self, DecodeError>;
235 /// A trait that various higher-level rust-lightning types implement allowing them to be read in
236 /// from a Read given some additional set of arguments which is required to deserialize.
238 /// (C-not exported) as we only export serialization to/from byte arrays instead
239 pub trait ReadableArgs<P>
242 /// Reads a Self in from the given Read
243 fn read<R: Read>(reader: &mut R, params: P) -> Result<Self, DecodeError>;
246 /// A std::io::Read that also provides the total bytes available to read.
247 pub(crate) trait LengthRead: Read {
248 /// The total number of bytes available to read.
249 fn total_bytes(&self) -> u64;
252 /// A trait that various higher-level rust-lightning types implement allowing them to be read in
253 /// from a Read given some additional set of arguments which is required to deserialize, requiring
254 /// the implementer to provide the total length of the read.
255 pub(crate) trait LengthReadableArgs<P> where Self: Sized
257 /// Reads a Self in from the given LengthRead
258 fn read<R: LengthRead>(reader: &mut R, params: P) -> Result<Self, DecodeError>;
261 /// A trait that various higher-level rust-lightning types implement allowing them to be read in
262 /// from a Read, requiring the implementer to provide the total length of the read.
263 pub(crate) trait LengthReadable where Self: Sized
265 /// Reads a Self in from the given LengthRead
266 fn read<R: LengthRead>(reader: &mut R) -> Result<Self, DecodeError>;
269 /// A trait that various rust-lightning types implement allowing them to (maybe) be read in from a Read
271 /// (C-not exported) as we only export serialization to/from byte arrays instead
272 pub trait MaybeReadable
275 /// Reads a Self in from the given Read
276 fn read<R: Read>(reader: &mut R) -> Result<Option<Self>, DecodeError>;
279 impl<T: Readable> MaybeReadable for T {
281 fn read<R: Read>(reader: &mut R) -> Result<Option<T>, DecodeError> {
282 Ok(Some(Readable::read(reader)?))
286 /// Wrapper to read a required (non-optional) TLV record.
287 pub struct OptionDeserWrapper<T: Readable>(pub Option<T>);
288 impl<T: Readable> Readable for OptionDeserWrapper<T> {
290 fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
291 Ok(Self(Some(Readable::read(reader)?)))
294 /// When handling default_values, we want to map the default-value T directly
295 /// to a OptionDeserWrapper<T> in a way that works for `field: T = t;` as
296 /// well. Thus, we assume `Into<T> for T` does nothing and use that.
297 impl<T: Readable> From<T> for OptionDeserWrapper<T> {
298 fn from(t: T) -> OptionDeserWrapper<T> { OptionDeserWrapper(Some(t)) }
301 pub(crate) struct U48(pub u64);
302 impl Writeable for U48 {
304 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
305 writer.write_all(&be48_to_array(self.0))
308 impl Readable for U48 {
310 fn read<R: Read>(reader: &mut R) -> Result<U48, DecodeError> {
311 let mut buf = [0; 6];
312 reader.read_exact(&mut buf)?;
313 Ok(U48(slice_to_be48(&buf)))
317 /// Lightning TLV uses a custom variable-length integer called BigSize. It is similar to Bitcoin's
318 /// variable-length integers except that it is serialized in big-endian instead of little-endian.
320 /// Like Bitcoin's variable-length integer, it exhibits ambiguity in that certain values can be
321 /// encoded in several different ways, which we must check for at deserialization-time. Thus, if
322 /// you're looking for an example of a variable-length integer to use for your own project, move
323 /// along, this is a rather poor design.
324 pub struct BigSize(pub u64);
325 impl Writeable for BigSize {
327 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
330 (self.0 as u8).write(writer)
333 0xFDu8.write(writer)?;
334 (self.0 as u16).write(writer)
336 0x10000...0xFFFFFFFF => {
337 0xFEu8.write(writer)?;
338 (self.0 as u32).write(writer)
341 0xFFu8.write(writer)?;
342 (self.0 as u64).write(writer)
347 impl Readable for BigSize {
349 fn read<R: Read>(reader: &mut R) -> Result<BigSize, DecodeError> {
350 let n: u8 = Readable::read(reader)?;
353 let x: u64 = Readable::read(reader)?;
355 Err(DecodeError::InvalidValue)
361 let x: u32 = Readable::read(reader)?;
363 Err(DecodeError::InvalidValue)
365 Ok(BigSize(x as u64))
369 let x: u16 = Readable::read(reader)?;
371 Err(DecodeError::InvalidValue)
373 Ok(BigSize(x as u64))
376 n => Ok(BigSize(n as u64))
381 /// In TLV we occasionally send fields which only consist of, or potentially end with, a
382 /// variable-length integer which is simply truncated by skipping high zero bytes. This type
383 /// encapsulates such integers implementing Readable/Writeable for them.
384 #[cfg_attr(test, derive(PartialEq, Eq, Debug))]
385 pub(crate) struct HighZeroBytesDroppedBigSize<T>(pub T);
387 macro_rules! impl_writeable_primitive {
388 ($val_type:ty, $len: expr) => {
389 impl Writeable for $val_type {
391 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
392 writer.write_all(&self.to_be_bytes())
395 impl Writeable for HighZeroBytesDroppedBigSize<$val_type> {
397 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
398 // Skip any full leading 0 bytes when writing (in BE):
399 writer.write_all(&self.0.to_be_bytes()[(self.0.leading_zeros()/8) as usize..$len])
402 impl Readable for $val_type {
404 fn read<R: Read>(reader: &mut R) -> Result<$val_type, DecodeError> {
405 let mut buf = [0; $len];
406 reader.read_exact(&mut buf)?;
407 Ok(<$val_type>::from_be_bytes(buf))
410 impl Readable for HighZeroBytesDroppedBigSize<$val_type> {
412 fn read<R: Read>(reader: &mut R) -> Result<HighZeroBytesDroppedBigSize<$val_type>, DecodeError> {
413 // We need to accept short reads (read_len == 0) as "EOF" and handle them as simply
414 // the high bytes being dropped. To do so, we start reading into the middle of buf
415 // and then convert the appropriate number of bytes with extra high bytes out of
417 let mut buf = [0; $len*2];
418 let mut read_len = reader.read(&mut buf[$len..])?;
419 let mut total_read_len = read_len;
420 while read_len != 0 && total_read_len != $len {
421 read_len = reader.read(&mut buf[($len + total_read_len)..])?;
422 total_read_len += read_len;
424 if total_read_len == 0 || buf[$len] != 0 {
425 let first_byte = $len - ($len - total_read_len);
426 let mut bytes = [0; $len];
427 bytes.copy_from_slice(&buf[first_byte..first_byte + $len]);
428 Ok(HighZeroBytesDroppedBigSize(<$val_type>::from_be_bytes(bytes)))
430 // If the encoding had extra zero bytes, return a failure even though we know
431 // what they meant (as the TLV test vectors require this)
432 Err(DecodeError::InvalidValue)
436 impl From<$val_type> for HighZeroBytesDroppedBigSize<$val_type> {
437 fn from(val: $val_type) -> Self { Self(val) }
442 impl_writeable_primitive!(u128, 16);
443 impl_writeable_primitive!(u64, 8);
444 impl_writeable_primitive!(u32, 4);
445 impl_writeable_primitive!(u16, 2);
447 impl Writeable for u8 {
449 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
450 writer.write_all(&[*self])
453 impl Readable for u8 {
455 fn read<R: Read>(reader: &mut R) -> Result<u8, DecodeError> {
456 let mut buf = [0; 1];
457 reader.read_exact(&mut buf)?;
462 impl Writeable for bool {
464 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
465 writer.write_all(&[if *self {1} else {0}])
468 impl Readable for bool {
470 fn read<R: Read>(reader: &mut R) -> Result<bool, DecodeError> {
471 let mut buf = [0; 1];
472 reader.read_exact(&mut buf)?;
473 if buf[0] != 0 && buf[0] != 1 {
474 return Err(DecodeError::InvalidValue);
481 macro_rules! impl_array {
483 impl Writeable for [u8; $size]
486 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
491 impl Readable for [u8; $size]
494 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
495 let mut buf = [0u8; $size];
496 r.read_exact(&mut buf)?;
503 impl_array!(3); // for rgb, ISO 4712 code
504 impl_array!(4); // for IPv4
505 impl_array!(12); // for OnionV2
506 impl_array!(16); // for IPv6
507 impl_array!(32); // for channel id & hmac
508 impl_array!(PUBLIC_KEY_SIZE); // for PublicKey
509 impl_array!(64); // for ecdsa::Signature and schnorr::Signature
510 impl_array!(1300); // for OnionPacket.hop_data
512 impl Writeable for [u16; 8] {
514 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
515 for v in self.iter() {
516 w.write_all(&v.to_be_bytes())?
522 impl Readable for [u16; 8] {
524 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
525 let mut buf = [0u8; 16];
526 r.read_exact(&mut buf)?;
527 let mut res = [0u16; 8];
528 for (idx, v) in res.iter_mut().enumerate() {
529 *v = (buf[idx] as u16) << 8 | (buf[idx + 1] as u16)
535 /// For variable-length values within TLV record where the length is encoded as part of the record.
536 /// Used to prevent encoding the length twice.
537 pub struct WithoutLength<T>(pub T);
539 impl Writeable for WithoutLength<&String> {
541 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
542 w.write_all(self.0.as_bytes())
545 impl Readable for WithoutLength<String> {
547 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
548 let v: WithoutLength<Vec<u8>> = Readable::read(r)?;
549 Ok(Self(String::from_utf8(v.0).map_err(|_| DecodeError::InvalidValue)?))
552 impl<'a> From<&'a String> for WithoutLength<&'a String> {
553 fn from(s: &'a String) -> Self { Self(s) }
556 impl<'a, T: Writeable> Writeable for WithoutLength<&'a Vec<T>> {
558 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
559 for ref v in self.0.iter() {
566 impl<T: MaybeReadable> Readable for WithoutLength<Vec<T>> {
568 fn read<R: Read>(mut reader: &mut R) -> Result<Self, DecodeError> {
569 let mut values = Vec::new();
571 let mut track_read = ReadTrackingReader::new(&mut reader);
572 match MaybeReadable::read(&mut track_read) {
573 Ok(Some(v)) => { values.push(v); },
575 // If we failed to read any bytes at all, we reached the end of our TLV
576 // stream and have simply exhausted all entries.
577 Err(ref e) if e == &DecodeError::ShortRead && !track_read.have_read => break,
578 Err(e) => return Err(e),
584 impl<'a, T> From<&'a Vec<T>> for WithoutLength<&'a Vec<T>> {
585 fn from(v: &'a Vec<T>) -> Self { Self(v) }
589 impl<K, V> Writeable for HashMap<K, V>
590 where K: Writeable + Eq + Hash,
594 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
595 (self.len() as u16).write(w)?;
596 for (key, value) in self.iter() {
604 impl<K, V> Readable for HashMap<K, V>
605 where K: Readable + Eq + Hash,
609 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
610 let len: u16 = Readable::read(r)?;
611 let mut ret = HashMap::with_capacity(len as usize);
614 let v_opt = V::read(r)?;
615 if let Some(v) = v_opt {
616 if ret.insert(k, v).is_some() {
617 return Err(DecodeError::InvalidValue);
626 impl<T> Writeable for HashSet<T>
627 where T: Writeable + Eq + Hash
630 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
631 (self.len() as u16).write(w)?;
632 for item in self.iter() {
639 impl<T> Readable for HashSet<T>
640 where T: Readable + Eq + Hash
643 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
644 let len: u16 = Readable::read(r)?;
645 let mut ret = HashSet::with_capacity(len as usize);
647 if !ret.insert(T::read(r)?) {
648 return Err(DecodeError::InvalidValue)
656 impl Writeable for Vec<u8> {
658 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
659 (self.len() as u16).write(w)?;
664 impl Readable for Vec<u8> {
666 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
667 let len: u16 = Readable::read(r)?;
668 let mut ret = Vec::with_capacity(len as usize);
669 ret.resize(len as usize, 0);
670 r.read_exact(&mut ret)?;
674 impl Writeable for Vec<ecdsa::Signature> {
676 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
677 (self.len() as u16).write(w)?;
678 for e in self.iter() {
685 impl Readable for Vec<ecdsa::Signature> {
687 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
688 let len: u16 = Readable::read(r)?;
689 let byte_size = (len as usize)
690 .checked_mul(COMPACT_SIGNATURE_SIZE)
691 .ok_or(DecodeError::BadLengthDescriptor)?;
692 if byte_size > MAX_BUF_SIZE {
693 return Err(DecodeError::BadLengthDescriptor);
695 let mut ret = Vec::with_capacity(len as usize);
696 for _ in 0..len { ret.push(Readable::read(r)?); }
701 impl Writeable for Script {
702 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
703 (self.len() as u16).write(w)?;
704 w.write_all(self.as_bytes())
708 impl Readable for Script {
709 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
710 let len = <u16 as Readable>::read(r)? as usize;
711 let mut buf = vec![0; len];
712 r.read_exact(&mut buf)?;
713 Ok(Script::from(buf))
717 impl Writeable for PublicKey {
718 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
719 self.serialize().write(w)
722 fn serialized_length(&self) -> usize {
727 impl Readable for PublicKey {
728 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
729 let buf: [u8; PUBLIC_KEY_SIZE] = Readable::read(r)?;
730 match PublicKey::from_slice(&buf) {
732 Err(_) => return Err(DecodeError::InvalidValue),
737 impl Writeable for SecretKey {
738 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
739 let mut ser = [0; SECRET_KEY_SIZE];
740 ser.copy_from_slice(&self[..]);
744 fn serialized_length(&self) -> usize {
749 impl Readable for SecretKey {
750 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
751 let buf: [u8; SECRET_KEY_SIZE] = Readable::read(r)?;
752 match SecretKey::from_slice(&buf) {
754 Err(_) => return Err(DecodeError::InvalidValue),
759 impl Writeable for Sha256dHash {
760 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
761 w.write_all(&self[..])
765 impl Readable for Sha256dHash {
766 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
767 use bitcoin::hashes::Hash;
769 let buf: [u8; 32] = Readable::read(r)?;
770 Ok(Sha256dHash::from_slice(&buf[..]).unwrap())
774 impl Writeable for ecdsa::Signature {
775 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
776 self.serialize_compact().write(w)
780 impl Readable for ecdsa::Signature {
781 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
782 let buf: [u8; COMPACT_SIGNATURE_SIZE] = Readable::read(r)?;
783 match ecdsa::Signature::from_compact(&buf) {
785 Err(_) => return Err(DecodeError::InvalidValue),
790 impl Writeable for schnorr::Signature {
791 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
792 self.as_ref().write(w)
796 impl Readable for schnorr::Signature {
797 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
798 let buf: [u8; SCHNORR_SIGNATURE_SIZE] = Readable::read(r)?;
799 match schnorr::Signature::from_slice(&buf) {
801 Err(_) => return Err(DecodeError::InvalidValue),
806 impl Writeable for PaymentPreimage {
807 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
812 impl Readable for PaymentPreimage {
813 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
814 let buf: [u8; 32] = Readable::read(r)?;
815 Ok(PaymentPreimage(buf))
819 impl Writeable for PaymentHash {
820 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
825 impl Readable for PaymentHash {
826 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
827 let buf: [u8; 32] = Readable::read(r)?;
832 impl Writeable for PaymentSecret {
833 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
838 impl Readable for PaymentSecret {
839 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
840 let buf: [u8; 32] = Readable::read(r)?;
841 Ok(PaymentSecret(buf))
845 impl<T: Writeable> Writeable for Box<T> {
846 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
851 impl<T: Readable> Readable for Box<T> {
852 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
853 Ok(Box::new(Readable::read(r)?))
857 impl<T: Writeable> Writeable for Option<T> {
858 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
860 None => 0u8.write(w)?,
862 BigSize(data.serialized_length() as u64 + 1).write(w)?;
870 impl<T: Readable> Readable for Option<T>
872 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
873 let len: BigSize = Readable::read(r)?;
877 let mut reader = FixedLengthReader::new(r, len - 1);
878 Ok(Some(Readable::read(&mut reader)?))
884 impl Writeable for Txid {
885 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
886 w.write_all(&self[..])
890 impl Readable for Txid {
891 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
892 use bitcoin::hashes::Hash;
894 let buf: [u8; 32] = Readable::read(r)?;
895 Ok(Txid::from_slice(&buf[..]).unwrap())
899 impl Writeable for BlockHash {
900 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
901 w.write_all(&self[..])
905 impl Readable for BlockHash {
906 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
907 use bitcoin::hashes::Hash;
909 let buf: [u8; 32] = Readable::read(r)?;
910 Ok(BlockHash::from_slice(&buf[..]).unwrap())
914 impl Writeable for ChainHash {
915 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
916 w.write_all(self.as_bytes())
920 impl Readable for ChainHash {
921 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
922 let buf: [u8; 32] = Readable::read(r)?;
923 Ok(ChainHash::from(&buf[..]))
927 impl Writeable for OutPoint {
928 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
935 impl Readable for OutPoint {
936 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
937 let txid = Readable::read(r)?;
938 let vout = Readable::read(r)?;
946 macro_rules! impl_consensus_ser {
947 ($bitcoin_type: ty) => {
948 impl Writeable for $bitcoin_type {
949 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
950 match self.consensus_encode(&mut WriterWriteAdaptor(writer)) {
957 impl Readable for $bitcoin_type {
958 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
959 match consensus::encode::Decodable::consensus_decode(r) {
961 Err(consensus::encode::Error::Io(ref e)) if e.kind() == io::ErrorKind::UnexpectedEof => Err(DecodeError::ShortRead),
962 Err(consensus::encode::Error::Io(e)) => Err(DecodeError::Io(e.kind())),
963 Err(_) => Err(DecodeError::InvalidValue),
969 impl_consensus_ser!(Transaction);
970 impl_consensus_ser!(TxOut);
972 impl<T: Readable> Readable for Mutex<T> {
973 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
974 let t: T = Readable::read(r)?;
978 impl<T: Writeable> Writeable for Mutex<T> {
979 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
980 self.lock().unwrap().write(w)
984 impl<A: Readable, B: Readable> Readable for (A, B) {
985 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
986 let a: A = Readable::read(r)?;
987 let b: B = Readable::read(r)?;
991 impl<A: Writeable, B: Writeable> Writeable for (A, B) {
992 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
998 impl<A: Readable, B: Readable, C: Readable> Readable for (A, B, C) {
999 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1000 let a: A = Readable::read(r)?;
1001 let b: B = Readable::read(r)?;
1002 let c: C = Readable::read(r)?;
1006 impl<A: Writeable, B: Writeable, C: Writeable> Writeable for (A, B, C) {
1007 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1014 impl Writeable for () {
1015 fn write<W: Writer>(&self, _: &mut W) -> Result<(), io::Error> {
1019 impl Readable for () {
1020 fn read<R: Read>(_r: &mut R) -> Result<Self, DecodeError> {
1025 impl Writeable for String {
1027 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1028 (self.len() as u16).write(w)?;
1029 w.write_all(self.as_bytes())
1032 impl Readable for String {
1034 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1035 let v: Vec<u8> = Readable::read(r)?;
1036 let ret = String::from_utf8(v).map_err(|_| DecodeError::InvalidValue)?;
1041 /// Represents a hostname for serialization purposes.
1042 /// Only the character set and length will be validated.
1043 /// The character set consists of ASCII alphanumeric characters, hyphens, and periods.
1044 /// Its length is guaranteed to be representable by a single byte.
1045 /// This serialization is used by BOLT 7 hostnames.
1046 #[derive(Clone, Debug, PartialEq, Eq)]
1047 pub struct Hostname(String);
1049 /// Returns the length of the hostname.
1050 pub fn len(&self) -> u8 {
1051 (&self.0).len() as u8
1054 impl Deref for Hostname {
1055 type Target = String;
1057 fn deref(&self) -> &Self::Target {
1061 impl From<Hostname> for String {
1062 fn from(hostname: Hostname) -> Self {
1066 impl TryFrom<Vec<u8>> for Hostname {
1069 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
1070 if let Ok(s) = String::from_utf8(bytes) {
1071 Hostname::try_from(s)
1077 impl TryFrom<String> for Hostname {
1080 fn try_from(s: String) -> Result<Self, Self::Error> {
1081 if s.len() <= 255 && s.chars().all(|c|
1082 c.is_ascii_alphanumeric() ||
1092 impl Writeable for Hostname {
1094 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1095 self.len().write(w)?;
1096 w.write_all(self.as_bytes())
1099 impl Readable for Hostname {
1101 fn read<R: Read>(r: &mut R) -> Result<Hostname, DecodeError> {
1102 let len: u8 = Readable::read(r)?;
1103 let mut vec = Vec::with_capacity(len.into());
1104 vec.resize(len.into(), 0);
1105 r.read_exact(&mut vec)?;
1106 Hostname::try_from(vec).map_err(|_| DecodeError::InvalidValue)
1110 impl Writeable for Duration {
1112 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1113 self.as_secs().write(w)?;
1114 self.subsec_nanos().write(w)
1117 impl Readable for Duration {
1119 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1120 let secs = Readable::read(r)?;
1121 let nanos = Readable::read(r)?;
1122 Ok(Duration::new(secs, nanos))
1128 use core::convert::TryFrom;
1129 use crate::util::ser::{Readable, Hostname, Writeable};
1132 fn hostname_conversion() {
1133 assert_eq!(Hostname::try_from(String::from("a-test.com")).unwrap().as_str(), "a-test.com");
1135 assert!(Hostname::try_from(String::from("\"")).is_err());
1136 assert!(Hostname::try_from(String::from("$")).is_err());
1137 assert!(Hostname::try_from(String::from("⚡")).is_err());
1138 let mut large_vec = Vec::with_capacity(256);
1139 large_vec.resize(256, b'A');
1140 assert!(Hostname::try_from(String::from_utf8(large_vec).unwrap()).is_err());
1144 fn hostname_serialization() {
1145 let hostname = Hostname::try_from(String::from("test")).unwrap();
1146 let mut buf: Vec<u8> = Vec::new();
1147 hostname.write(&mut buf).unwrap();
1148 assert_eq!(Hostname::read(&mut buf.as_slice()).unwrap().as_str(), "test");