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};
24 use bitcoin::secp256k1::ecdsa::Signature;
25 use bitcoin::blockdata::constants::ChainHash;
26 use bitcoin::blockdata::script::Script;
27 use bitcoin::blockdata::transaction::{OutPoint, Transaction, TxOut};
28 use bitcoin::consensus;
29 use bitcoin::consensus::Encodable;
30 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
31 use bitcoin::hash_types::{Txid, BlockHash};
32 use core::marker::Sized;
33 use core::time::Duration;
34 use crate::ln::msgs::DecodeError;
35 use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
37 use crate::util::byte_utils::{be48_to_array, slice_to_be48};
39 /// serialization buffer size
40 pub const MAX_BUF_SIZE: usize = 64 * 1024;
42 /// A simplified version of std::io::Write that exists largely for backwards compatibility.
43 /// An impl is provided for any type that also impls std::io::Write.
45 /// (C-not exported) as we only export serialization to/from byte arrays instead
47 /// Writes the given buf out. See std::io::Write::write_all for more
48 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error>;
51 impl<W: Write> Writer for W {
53 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
54 <Self as io::Write>::write_all(self, buf)
58 pub(crate) struct WriterWriteAdaptor<'a, W: Writer + 'a>(pub &'a mut W);
59 impl<'a, W: Writer + 'a> Write for WriterWriteAdaptor<'a, W> {
61 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
65 fn write(&mut self, buf: &[u8]) -> Result<usize, io::Error> {
66 self.0.write_all(buf)?;
70 fn flush(&mut self) -> Result<(), io::Error> {
75 pub(crate) struct VecWriter(pub Vec<u8>);
76 impl Writer for VecWriter {
78 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
79 self.0.extend_from_slice(buf);
84 /// Writer that only tracks the amount of data written - useful if you need to calculate the length
85 /// of some data when serialized but don't yet need the full data.
86 pub(crate) struct LengthCalculatingWriter(pub usize);
87 impl Writer for LengthCalculatingWriter {
89 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
95 /// Essentially std::io::Take but a bit simpler and with a method to walk the underlying stream
96 /// forward to ensure we always consume exactly the fixed length specified.
97 pub(crate) struct FixedLengthReader<R: Read> {
102 impl<R: Read> FixedLengthReader<R> {
103 pub fn new(read: R, total_bytes: u64) -> Self {
104 Self { read, bytes_read: 0, total_bytes }
108 pub fn bytes_remain(&mut self) -> bool {
109 self.bytes_read != self.total_bytes
113 pub fn eat_remaining(&mut self) -> Result<(), DecodeError> {
114 copy(self, &mut sink()).unwrap();
115 if self.bytes_read != self.total_bytes {
116 Err(DecodeError::ShortRead)
122 impl<R: Read> Read for FixedLengthReader<R> {
124 fn read(&mut self, dest: &mut [u8]) -> Result<usize, io::Error> {
125 if self.total_bytes == self.bytes_read {
128 let read_len = cmp::min(dest.len() as u64, self.total_bytes - self.bytes_read);
129 match self.read.read(&mut dest[0..(read_len as usize)]) {
131 self.bytes_read += v as u64;
140 impl<R: Read> LengthRead for FixedLengthReader<R> {
142 fn total_bytes(&self) -> u64 {
147 /// A Read which tracks whether any bytes have been read at all. This allows us to distinguish
148 /// between "EOF reached before we started" and "EOF reached mid-read".
149 pub(crate) struct ReadTrackingReader<R: Read> {
153 impl<R: Read> ReadTrackingReader<R> {
154 pub fn new(read: R) -> Self {
155 Self { read, have_read: false }
158 impl<R: Read> Read for ReadTrackingReader<R> {
160 fn read(&mut self, dest: &mut [u8]) -> Result<usize, io::Error> {
161 match self.read.read(dest) {
164 self.have_read = true;
172 /// A trait that various rust-lightning types implement allowing them to be written out to a Writer
174 /// (C-not exported) as we only export serialization to/from byte arrays instead
175 pub trait Writeable {
176 /// Writes self out to the given Writer
177 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error>;
179 /// Writes self out to a Vec<u8>
180 fn encode(&self) -> Vec<u8> {
181 let mut msg = VecWriter(Vec::new());
182 self.write(&mut msg).unwrap();
186 /// Writes self out to a Vec<u8>
188 fn encode_with_len(&self) -> Vec<u8> {
189 let mut msg = VecWriter(Vec::new());
190 0u16.write(&mut msg).unwrap();
191 self.write(&mut msg).unwrap();
192 let len = msg.0.len();
193 msg.0[..2].copy_from_slice(&(len as u16 - 2).to_be_bytes());
197 /// Gets the length of this object after it has been serialized. This can be overridden to
198 /// optimize cases where we prepend an object with its length.
199 // Note that LLVM optimizes this away in most cases! Check that it isn't before you override!
201 fn serialized_length(&self) -> usize {
202 let mut len_calc = LengthCalculatingWriter(0);
203 self.write(&mut len_calc).expect("No in-memory data may fail to serialize");
208 impl<'a, T: Writeable> Writeable for &'a T {
209 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { (*self).write(writer) }
212 /// A trait that various rust-lightning types implement allowing them to be read in from a Read
214 /// (C-not exported) as we only export serialization to/from byte arrays instead
218 /// Reads a Self in from the given Read
219 fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError>;
222 /// A trait that various rust-lightning types implement allowing them to be read in from a
224 pub(crate) trait SeekReadable where Self: Sized {
225 /// Reads a Self in from the given Read
226 fn read<R: Read + Seek>(reader: &mut R) -> Result<Self, DecodeError>;
229 /// A trait that various higher-level rust-lightning types implement allowing them to be read in
230 /// from a Read given some additional set of arguments which is required to deserialize.
232 /// (C-not exported) as we only export serialization to/from byte arrays instead
233 pub trait ReadableArgs<P>
236 /// Reads a Self in from the given Read
237 fn read<R: Read>(reader: &mut R, params: P) -> Result<Self, DecodeError>;
240 /// A std::io::Read that also provides the total bytes available to read.
241 pub(crate) trait LengthRead: Read {
242 /// The total number of bytes available to read.
243 fn total_bytes(&self) -> u64;
246 /// A trait that various higher-level rust-lightning types implement allowing them to be read in
247 /// from a Read given some additional set of arguments which is required to deserialize, requiring
248 /// the implementer to provide the total length of the read.
249 pub(crate) trait LengthReadableArgs<P> where Self: Sized
251 /// Reads a Self in from the given LengthRead
252 fn read<R: LengthRead>(reader: &mut R, params: P) -> Result<Self, DecodeError>;
255 /// A trait that various higher-level rust-lightning types implement allowing them to be read in
256 /// from a Read, requiring the implementer to provide the total length of the read.
257 pub(crate) trait LengthReadable where Self: Sized
259 /// Reads a Self in from the given LengthRead
260 fn read<R: LengthRead>(reader: &mut R) -> Result<Self, DecodeError>;
263 /// A trait that various rust-lightning types implement allowing them to (maybe) be read in from a Read
265 /// (C-not exported) as we only export serialization to/from byte arrays instead
266 pub trait MaybeReadable
269 /// Reads a Self in from the given Read
270 fn read<R: Read>(reader: &mut R) -> Result<Option<Self>, DecodeError>;
273 impl<T: Readable> MaybeReadable for T {
275 fn read<R: Read>(reader: &mut R) -> Result<Option<T>, DecodeError> {
276 Ok(Some(Readable::read(reader)?))
280 pub(crate) struct OptionDeserWrapper<T: Readable>(pub Option<T>);
281 impl<T: Readable> Readable for OptionDeserWrapper<T> {
283 fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
284 Ok(Self(Some(Readable::read(reader)?)))
287 /// When handling default_values, we want to map the default-value T directly
288 /// to a OptionDeserWrapper<T> in a way that works for `field: T = t;` as
289 /// well. Thus, we assume `Into<T> for T` does nothing and use that.
290 impl<T: Readable> From<T> for OptionDeserWrapper<T> {
291 fn from(t: T) -> OptionDeserWrapper<T> { OptionDeserWrapper(Some(t)) }
294 pub(crate) struct U48(pub u64);
295 impl Writeable for U48 {
297 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
298 writer.write_all(&be48_to_array(self.0))
301 impl Readable for U48 {
303 fn read<R: Read>(reader: &mut R) -> Result<U48, DecodeError> {
304 let mut buf = [0; 6];
305 reader.read_exact(&mut buf)?;
306 Ok(U48(slice_to_be48(&buf)))
310 /// Lightning TLV uses a custom variable-length integer called BigSize. It is similar to Bitcoin's
311 /// variable-length integers except that it is serialized in big-endian instead of little-endian.
313 /// Like Bitcoin's variable-length integer, it exhibits ambiguity in that certain values can be
314 /// encoded in several different ways, which we must check for at deserialization-time. Thus, if
315 /// you're looking for an example of a variable-length integer to use for your own project, move
316 /// along, this is a rather poor design.
317 pub struct BigSize(pub u64);
318 impl Writeable for BigSize {
320 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
323 (self.0 as u8).write(writer)
326 0xFDu8.write(writer)?;
327 (self.0 as u16).write(writer)
329 0x10000...0xFFFFFFFF => {
330 0xFEu8.write(writer)?;
331 (self.0 as u32).write(writer)
334 0xFFu8.write(writer)?;
335 (self.0 as u64).write(writer)
340 impl Readable for BigSize {
342 fn read<R: Read>(reader: &mut R) -> Result<BigSize, DecodeError> {
343 let n: u8 = Readable::read(reader)?;
346 let x: u64 = Readable::read(reader)?;
348 Err(DecodeError::InvalidValue)
354 let x: u32 = Readable::read(reader)?;
356 Err(DecodeError::InvalidValue)
358 Ok(BigSize(x as u64))
362 let x: u16 = Readable::read(reader)?;
364 Err(DecodeError::InvalidValue)
366 Ok(BigSize(x as u64))
369 n => Ok(BigSize(n as u64))
374 /// In TLV we occasionally send fields which only consist of, or potentially end with, a
375 /// variable-length integer which is simply truncated by skipping high zero bytes. This type
376 /// encapsulates such integers implementing Readable/Writeable for them.
377 #[cfg_attr(test, derive(PartialEq, Eq, Debug))]
378 pub(crate) struct HighZeroBytesDroppedBigSize<T>(pub T);
380 macro_rules! impl_writeable_primitive {
381 ($val_type:ty, $len: expr) => {
382 impl Writeable for $val_type {
384 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
385 writer.write_all(&self.to_be_bytes())
388 impl Writeable for HighZeroBytesDroppedBigSize<$val_type> {
390 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
391 // Skip any full leading 0 bytes when writing (in BE):
392 writer.write_all(&self.0.to_be_bytes()[(self.0.leading_zeros()/8) as usize..$len])
395 impl Readable for $val_type {
397 fn read<R: Read>(reader: &mut R) -> Result<$val_type, DecodeError> {
398 let mut buf = [0; $len];
399 reader.read_exact(&mut buf)?;
400 Ok(<$val_type>::from_be_bytes(buf))
403 impl Readable for HighZeroBytesDroppedBigSize<$val_type> {
405 fn read<R: Read>(reader: &mut R) -> Result<HighZeroBytesDroppedBigSize<$val_type>, DecodeError> {
406 // We need to accept short reads (read_len == 0) as "EOF" and handle them as simply
407 // the high bytes being dropped. To do so, we start reading into the middle of buf
408 // and then convert the appropriate number of bytes with extra high bytes out of
410 let mut buf = [0; $len*2];
411 let mut read_len = reader.read(&mut buf[$len..])?;
412 let mut total_read_len = read_len;
413 while read_len != 0 && total_read_len != $len {
414 read_len = reader.read(&mut buf[($len + total_read_len)..])?;
415 total_read_len += read_len;
417 if total_read_len == 0 || buf[$len] != 0 {
418 let first_byte = $len - ($len - total_read_len);
419 let mut bytes = [0; $len];
420 bytes.copy_from_slice(&buf[first_byte..first_byte + $len]);
421 Ok(HighZeroBytesDroppedBigSize(<$val_type>::from_be_bytes(bytes)))
423 // If the encoding had extra zero bytes, return a failure even though we know
424 // what they meant (as the TLV test vectors require this)
425 Err(DecodeError::InvalidValue)
429 impl From<$val_type> for HighZeroBytesDroppedBigSize<$val_type> {
430 fn from(val: $val_type) -> Self { Self(val) }
435 impl_writeable_primitive!(u128, 16);
436 impl_writeable_primitive!(u64, 8);
437 impl_writeable_primitive!(u32, 4);
438 impl_writeable_primitive!(u16, 2);
440 impl Writeable for u8 {
442 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
443 writer.write_all(&[*self])
446 impl Readable for u8 {
448 fn read<R: Read>(reader: &mut R) -> Result<u8, DecodeError> {
449 let mut buf = [0; 1];
450 reader.read_exact(&mut buf)?;
455 impl Writeable for bool {
457 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
458 writer.write_all(&[if *self {1} else {0}])
461 impl Readable for bool {
463 fn read<R: Read>(reader: &mut R) -> Result<bool, DecodeError> {
464 let mut buf = [0; 1];
465 reader.read_exact(&mut buf)?;
466 if buf[0] != 0 && buf[0] != 1 {
467 return Err(DecodeError::InvalidValue);
474 macro_rules! impl_array {
476 impl Writeable for [u8; $size]
479 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
484 impl Readable for [u8; $size]
487 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
488 let mut buf = [0u8; $size];
489 r.read_exact(&mut buf)?;
496 impl_array!(3); // for rgb, ISO 4712 code
497 impl_array!(4); // for IPv4
498 impl_array!(12); // for OnionV2
499 impl_array!(16); // for IPv6
500 impl_array!(32); // for channel id & hmac
501 impl_array!(PUBLIC_KEY_SIZE); // for PublicKey
502 impl_array!(COMPACT_SIGNATURE_SIZE); // for Signature
503 impl_array!(1300); // for OnionPacket.hop_data
505 impl Writeable for [u16; 8] {
507 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
508 for v in self.iter() {
509 w.write_all(&v.to_be_bytes())?
515 impl Readable for [u16; 8] {
517 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
518 let mut buf = [0u8; 16];
519 r.read_exact(&mut buf)?;
520 let mut res = [0u16; 8];
521 for (idx, v) in res.iter_mut().enumerate() {
522 *v = (buf[idx] as u16) << 8 | (buf[idx + 1] as u16)
528 /// For variable-length values within TLV record where the length is encoded as part of the record.
529 /// Used to prevent encoding the length twice.
530 pub(crate) struct WithoutLength<T>(pub T);
532 impl Writeable for WithoutLength<&String> {
534 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
535 w.write_all(self.0.as_bytes())
538 impl Readable for WithoutLength<String> {
540 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
541 let v: WithoutLength<Vec<u8>> = Readable::read(r)?;
542 Ok(Self(String::from_utf8(v.0).map_err(|_| DecodeError::InvalidValue)?))
545 impl<'a> From<&'a String> for WithoutLength<&'a String> {
546 fn from(s: &'a String) -> Self { Self(s) }
549 impl<'a, T: Writeable> Writeable for WithoutLength<&'a Vec<T>> {
551 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
552 for ref v in self.0.iter() {
559 impl<T: MaybeReadable> Readable for WithoutLength<Vec<T>> {
561 fn read<R: Read>(mut reader: &mut R) -> Result<Self, DecodeError> {
562 let mut values = Vec::new();
564 let mut track_read = ReadTrackingReader::new(&mut reader);
565 match MaybeReadable::read(&mut track_read) {
566 Ok(Some(v)) => { values.push(v); },
568 // If we failed to read any bytes at all, we reached the end of our TLV
569 // stream and have simply exhausted all entries.
570 Err(ref e) if e == &DecodeError::ShortRead && !track_read.have_read => break,
571 Err(e) => return Err(e),
577 impl<'a, T> From<&'a Vec<T>> for WithoutLength<&'a Vec<T>> {
578 fn from(v: &'a Vec<T>) -> Self { Self(v) }
582 impl<K, V> Writeable for HashMap<K, V>
583 where K: Writeable + Eq + Hash,
587 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
588 (self.len() as u16).write(w)?;
589 for (key, value) in self.iter() {
597 impl<K, V> Readable for HashMap<K, V>
598 where K: Readable + Eq + Hash,
602 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
603 let len: u16 = Readable::read(r)?;
604 let mut ret = HashMap::with_capacity(len as usize);
607 let v_opt = V::read(r)?;
608 if let Some(v) = v_opt {
609 if ret.insert(k, v).is_some() {
610 return Err(DecodeError::InvalidValue);
619 impl<T> Writeable for HashSet<T>
620 where T: Writeable + Eq + Hash
623 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
624 (self.len() as u16).write(w)?;
625 for item in self.iter() {
632 impl<T> Readable for HashSet<T>
633 where T: Readable + Eq + Hash
636 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
637 let len: u16 = Readable::read(r)?;
638 let mut ret = HashSet::with_capacity(len as usize);
640 if !ret.insert(T::read(r)?) {
641 return Err(DecodeError::InvalidValue)
649 impl Writeable for Vec<u8> {
651 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
652 (self.len() as u16).write(w)?;
657 impl Readable for Vec<u8> {
659 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
660 let len: u16 = Readable::read(r)?;
661 let mut ret = Vec::with_capacity(len as usize);
662 ret.resize(len as usize, 0);
663 r.read_exact(&mut ret)?;
667 impl Writeable for Vec<Signature> {
669 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
670 (self.len() as u16).write(w)?;
671 for e in self.iter() {
678 impl Readable for Vec<Signature> {
680 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
681 let len: u16 = Readable::read(r)?;
682 let byte_size = (len as usize)
683 .checked_mul(COMPACT_SIGNATURE_SIZE)
684 .ok_or(DecodeError::BadLengthDescriptor)?;
685 if byte_size > MAX_BUF_SIZE {
686 return Err(DecodeError::BadLengthDescriptor);
688 let mut ret = Vec::with_capacity(len as usize);
689 for _ in 0..len { ret.push(Readable::read(r)?); }
694 impl Writeable for Script {
695 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
696 (self.len() as u16).write(w)?;
697 w.write_all(self.as_bytes())
701 impl Readable for Script {
702 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
703 let len = <u16 as Readable>::read(r)? as usize;
704 let mut buf = vec![0; len];
705 r.read_exact(&mut buf)?;
706 Ok(Script::from(buf))
710 impl Writeable for PublicKey {
711 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
712 self.serialize().write(w)
715 fn serialized_length(&self) -> usize {
720 impl Readable for PublicKey {
721 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
722 let buf: [u8; PUBLIC_KEY_SIZE] = Readable::read(r)?;
723 match PublicKey::from_slice(&buf) {
725 Err(_) => return Err(DecodeError::InvalidValue),
730 impl Writeable for SecretKey {
731 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
732 let mut ser = [0; SECRET_KEY_SIZE];
733 ser.copy_from_slice(&self[..]);
737 fn serialized_length(&self) -> usize {
742 impl Readable for SecretKey {
743 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
744 let buf: [u8; SECRET_KEY_SIZE] = Readable::read(r)?;
745 match SecretKey::from_slice(&buf) {
747 Err(_) => return Err(DecodeError::InvalidValue),
752 impl Writeable for Sha256dHash {
753 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
754 w.write_all(&self[..])
758 impl Readable for Sha256dHash {
759 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
760 use bitcoin::hashes::Hash;
762 let buf: [u8; 32] = Readable::read(r)?;
763 Ok(Sha256dHash::from_slice(&buf[..]).unwrap())
767 impl Writeable for Signature {
768 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
769 self.serialize_compact().write(w)
772 fn serialized_length(&self) -> usize {
773 COMPACT_SIGNATURE_SIZE
777 impl Readable for Signature {
778 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
779 let buf: [u8; COMPACT_SIGNATURE_SIZE] = Readable::read(r)?;
780 match Signature::from_compact(&buf) {
782 Err(_) => return Err(DecodeError::InvalidValue),
787 impl Writeable for PaymentPreimage {
788 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
793 impl Readable for PaymentPreimage {
794 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
795 let buf: [u8; 32] = Readable::read(r)?;
796 Ok(PaymentPreimage(buf))
800 impl Writeable for PaymentHash {
801 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
806 impl Readable for PaymentHash {
807 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
808 let buf: [u8; 32] = Readable::read(r)?;
813 impl Writeable for PaymentSecret {
814 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
819 impl Readable for PaymentSecret {
820 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
821 let buf: [u8; 32] = Readable::read(r)?;
822 Ok(PaymentSecret(buf))
826 impl<T: Writeable> Writeable for Box<T> {
827 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
832 impl<T: Readable> Readable for Box<T> {
833 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
834 Ok(Box::new(Readable::read(r)?))
838 impl<T: Writeable> Writeable for Option<T> {
839 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
841 None => 0u8.write(w)?,
843 BigSize(data.serialized_length() as u64 + 1).write(w)?;
851 impl<T: Readable> Readable for Option<T>
853 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
854 let len: BigSize = Readable::read(r)?;
858 let mut reader = FixedLengthReader::new(r, len - 1);
859 Ok(Some(Readable::read(&mut reader)?))
865 impl Writeable for Txid {
866 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
867 w.write_all(&self[..])
871 impl Readable for Txid {
872 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
873 use bitcoin::hashes::Hash;
875 let buf: [u8; 32] = Readable::read(r)?;
876 Ok(Txid::from_slice(&buf[..]).unwrap())
880 impl Writeable for BlockHash {
881 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
882 w.write_all(&self[..])
886 impl Readable for BlockHash {
887 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
888 use bitcoin::hashes::Hash;
890 let buf: [u8; 32] = Readable::read(r)?;
891 Ok(BlockHash::from_slice(&buf[..]).unwrap())
895 impl Writeable for ChainHash {
896 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
897 w.write_all(self.as_bytes())
901 impl Readable for ChainHash {
902 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
903 let buf: [u8; 32] = Readable::read(r)?;
904 Ok(ChainHash::from(&buf[..]))
908 impl Writeable for OutPoint {
909 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
916 impl Readable for OutPoint {
917 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
918 let txid = Readable::read(r)?;
919 let vout = Readable::read(r)?;
927 macro_rules! impl_consensus_ser {
928 ($bitcoin_type: ty) => {
929 impl Writeable for $bitcoin_type {
930 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
931 match self.consensus_encode(&mut WriterWriteAdaptor(writer)) {
938 impl Readable for $bitcoin_type {
939 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
940 match consensus::encode::Decodable::consensus_decode(r) {
942 Err(consensus::encode::Error::Io(ref e)) if e.kind() == io::ErrorKind::UnexpectedEof => Err(DecodeError::ShortRead),
943 Err(consensus::encode::Error::Io(e)) => Err(DecodeError::Io(e.kind())),
944 Err(_) => Err(DecodeError::InvalidValue),
950 impl_consensus_ser!(Transaction);
951 impl_consensus_ser!(TxOut);
953 impl<T: Readable> Readable for Mutex<T> {
954 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
955 let t: T = Readable::read(r)?;
959 impl<T: Writeable> Writeable for Mutex<T> {
960 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
961 self.lock().unwrap().write(w)
965 impl<A: Readable, B: Readable> Readable for (A, B) {
966 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
967 let a: A = Readable::read(r)?;
968 let b: B = Readable::read(r)?;
972 impl<A: Writeable, B: Writeable> Writeable for (A, B) {
973 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
979 impl<A: Readable, B: Readable, C: Readable> Readable for (A, B, C) {
980 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
981 let a: A = Readable::read(r)?;
982 let b: B = Readable::read(r)?;
983 let c: C = Readable::read(r)?;
987 impl<A: Writeable, B: Writeable, C: Writeable> Writeable for (A, B, C) {
988 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
995 impl Writeable for () {
996 fn write<W: Writer>(&self, _: &mut W) -> Result<(), io::Error> {
1000 impl Readable for () {
1001 fn read<R: Read>(_r: &mut R) -> Result<Self, DecodeError> {
1006 impl Writeable for String {
1008 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1009 (self.len() as u16).write(w)?;
1010 w.write_all(self.as_bytes())
1013 impl Readable for String {
1015 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1016 let v: Vec<u8> = Readable::read(r)?;
1017 let ret = String::from_utf8(v).map_err(|_| DecodeError::InvalidValue)?;
1022 /// Represents a hostname for serialization purposes.
1023 /// Only the character set and length will be validated.
1024 /// The character set consists of ASCII alphanumeric characters, hyphens, and periods.
1025 /// Its length is guaranteed to be representable by a single byte.
1026 /// This serialization is used by BOLT 7 hostnames.
1027 #[derive(Clone, Debug, PartialEq, Eq)]
1028 pub struct Hostname(String);
1030 /// Returns the length of the hostname.
1031 pub fn len(&self) -> u8 {
1032 (&self.0).len() as u8
1035 impl Deref for Hostname {
1036 type Target = String;
1038 fn deref(&self) -> &Self::Target {
1042 impl From<Hostname> for String {
1043 fn from(hostname: Hostname) -> Self {
1047 impl TryFrom<Vec<u8>> for Hostname {
1050 fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
1051 if let Ok(s) = String::from_utf8(bytes) {
1052 Hostname::try_from(s)
1058 impl TryFrom<String> for Hostname {
1061 fn try_from(s: String) -> Result<Self, Self::Error> {
1062 if s.len() <= 255 && s.chars().all(|c|
1063 c.is_ascii_alphanumeric() ||
1073 impl Writeable for Hostname {
1075 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1076 self.len().write(w)?;
1077 w.write_all(self.as_bytes())
1080 impl Readable for Hostname {
1082 fn read<R: Read>(r: &mut R) -> Result<Hostname, DecodeError> {
1083 let len: u8 = Readable::read(r)?;
1084 let mut vec = Vec::with_capacity(len.into());
1085 vec.resize(len.into(), 0);
1086 r.read_exact(&mut vec)?;
1087 Hostname::try_from(vec).map_err(|_| DecodeError::InvalidValue)
1091 impl Writeable for Duration {
1093 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
1094 self.as_secs().write(w)?;
1095 self.subsec_nanos().write(w)
1098 impl Readable for Duration {
1100 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
1101 let secs = Readable::read(r)?;
1102 let nanos = Readable::read(r)?;
1103 Ok(Duration::new(secs, nanos))
1109 use core::convert::TryFrom;
1110 use crate::util::ser::{Readable, Hostname, Writeable};
1113 fn hostname_conversion() {
1114 assert_eq!(Hostname::try_from(String::from("a-test.com")).unwrap().as_str(), "a-test.com");
1116 assert!(Hostname::try_from(String::from("\"")).is_err());
1117 assert!(Hostname::try_from(String::from("$")).is_err());
1118 assert!(Hostname::try_from(String::from("⚡")).is_err());
1119 let mut large_vec = Vec::with_capacity(256);
1120 large_vec.resize(256, b'A');
1121 assert!(Hostname::try_from(String::from_utf8(large_vec).unwrap()).is_err());
1125 fn hostname_serialization() {
1126 let hostname = Hostname::try_from(String::from("test")).unwrap();
1127 let mut buf: Vec<u8> = Vec::new();
1128 hostname.write(&mut buf).unwrap();
1129 assert_eq!(Hostname::read(&mut buf.as_slice()).unwrap().as_str(), "test");