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 std::io::{Read, Write};
15 use std::collections::HashMap;
20 use bitcoin::secp256k1::Signature;
21 use bitcoin::secp256k1::key::{PublicKey, SecretKey};
22 use bitcoin::secp256k1::constants::{PUBLIC_KEY_SIZE, COMPACT_SIGNATURE_SIZE};
23 use bitcoin::blockdata::script::Script;
24 use bitcoin::blockdata::transaction::{OutPoint, Transaction, TxOut};
25 use bitcoin::consensus;
26 use bitcoin::consensus::Encodable;
27 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
28 use bitcoin::hash_types::{Txid, BlockHash};
29 use core::marker::Sized;
30 use ln::msgs::DecodeError;
31 use ln::{PaymentPreimage, PaymentHash, PaymentSecret};
34 use util::byte_utils::{be64_to_array, be48_to_array, be32_to_array, be16_to_array, slice_to_be16, slice_to_be32, slice_to_be48, slice_to_be64};
36 /// serialization buffer size
37 pub const MAX_BUF_SIZE: usize = 64 * 1024;
39 /// A trait that is similar to std::io::Write but has one extra function which can be used to size
40 /// buffers being written into.
41 /// An impl is provided for any type that also impls std::io::Write which simply ignores size
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<(), ::std::io::Error>;
48 /// Hints that data of the given size is about the be written. This may not always be called
49 /// prior to data being written and may be safely ignored.
50 fn size_hint(&mut self, size: usize);
53 impl<W: Write> Writer for W {
55 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
56 <Self as ::std::io::Write>::write_all(self, buf)
59 fn size_hint(&mut self, _size: usize) { }
62 pub(crate) struct WriterWriteAdaptor<'a, W: Writer + 'a>(pub &'a mut W);
63 impl<'a, W: Writer + 'a> Write for WriterWriteAdaptor<'a, W> {
64 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
67 fn write(&mut self, buf: &[u8]) -> Result<usize, ::std::io::Error> {
68 self.0.write_all(buf)?;
71 fn flush(&mut self) -> Result<(), ::std::io::Error> {
76 pub(crate) struct VecWriter(pub Vec<u8>);
77 impl Writer for VecWriter {
78 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
79 self.0.extend_from_slice(buf);
82 fn size_hint(&mut self, size: usize) {
83 self.0.reserve_exact(size);
87 /// Writer that only tracks the amount of data written - useful if you need to calculate the length
88 /// of some data when serialized but don't yet need the full data.
89 pub(crate) struct LengthCalculatingWriter(pub usize);
90 impl Writer for LengthCalculatingWriter {
92 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
97 fn size_hint(&mut self, _size: usize) {}
100 /// Essentially std::io::Take but a bit simpler and with a method to walk the underlying stream
101 /// forward to ensure we always consume exactly the fixed length specified.
102 pub(crate) struct FixedLengthReader<R: Read> {
107 impl<R: Read> FixedLengthReader<R> {
108 pub fn new(read: R, total_bytes: u64) -> Self {
109 Self { read, bytes_read: 0, total_bytes }
112 pub fn bytes_remain(&mut self) -> bool {
113 self.bytes_read != self.total_bytes
116 pub fn eat_remaining(&mut self) -> Result<(), DecodeError> {
117 ::std::io::copy(self, &mut ::std::io::sink()).unwrap();
118 if self.bytes_read != self.total_bytes {
119 Err(DecodeError::ShortRead)
125 impl<R: Read> Read for FixedLengthReader<R> {
126 fn read(&mut self, dest: &mut [u8]) -> Result<usize, ::std::io::Error> {
127 if self.total_bytes == self.bytes_read {
130 let read_len = cmp::min(dest.len() as u64, self.total_bytes - self.bytes_read);
131 match self.read.read(&mut dest[0..(read_len as usize)]) {
133 self.bytes_read += v as u64;
142 /// A Read which tracks whether any bytes have been read at all. This allows us to distinguish
143 /// between "EOF reached before we started" and "EOF reached mid-read".
144 pub(crate) struct ReadTrackingReader<R: Read> {
148 impl<R: Read> ReadTrackingReader<R> {
149 pub fn new(read: R) -> Self {
150 Self { read, have_read: false }
153 impl<R: Read> Read for ReadTrackingReader<R> {
154 fn read(&mut self, dest: &mut [u8]) -> Result<usize, ::std::io::Error> {
155 match self.read.read(dest) {
158 self.have_read = true;
166 /// A trait that various rust-lightning types implement allowing them to be written out to a Writer
168 /// (C-not exported) as we only export serialization to/from byte arrays instead
169 pub trait Writeable {
170 /// Writes self out to the given Writer
171 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error>;
173 /// Writes self out to a Vec<u8>
174 fn encode(&self) -> Vec<u8> {
175 let mut msg = VecWriter(Vec::new());
176 self.write(&mut msg).unwrap();
180 /// Writes self out to a Vec<u8>
181 fn encode_with_len(&self) -> Vec<u8> {
182 let mut msg = VecWriter(Vec::new());
183 0u16.write(&mut msg).unwrap();
184 self.write(&mut msg).unwrap();
185 let len = msg.0.len();
186 msg.0[..2].copy_from_slice(&byte_utils::be16_to_array(len as u16 - 2));
191 impl<'a, T: Writeable> Writeable for &'a T {
192 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> { (*self).write(writer) }
195 /// A trait that various rust-lightning types implement allowing them to be read in from a Read
197 /// (C-not exported) as we only export serialization to/from byte arrays instead
201 /// Reads a Self in from the given Read
202 fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError>;
205 /// A trait that various higher-level rust-lightning types implement allowing them to be read in
206 /// from a Read given some additional set of arguments which is required to deserialize.
208 /// (C-not exported) as we only export serialization to/from byte arrays instead
209 pub trait ReadableArgs<P>
212 /// Reads a Self in from the given Read
213 fn read<R: Read>(reader: &mut R, params: P) -> Result<Self, DecodeError>;
216 /// A trait that various rust-lightning types implement allowing them to (maybe) be read in from a Read
218 /// (C-not exported) as we only export serialization to/from byte arrays instead
219 pub trait MaybeReadable
222 /// Reads a Self in from the given Read
223 fn read<R: Read>(reader: &mut R) -> Result<Option<Self>, DecodeError>;
226 pub(crate) struct OptionDeserWrapper<T: Readable>(pub Option<T>);
227 impl<T: Readable> Readable for OptionDeserWrapper<T> {
228 fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
229 Ok(Self(Some(Readable::read(reader)?)))
233 const MAX_ALLOC_SIZE: u64 = 64*1024;
235 pub(crate) struct VecWriteWrapper<'a, T: Writeable>(pub &'a Vec<T>);
236 impl<'a, T: Writeable> Writeable for VecWriteWrapper<'a, T> {
237 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
238 (self.0.len() as u64).write(writer)?;
239 for ref v in self.0.iter() {
245 pub(crate) struct VecReadWrapper<T: Readable>(pub Vec<T>);
246 impl<T: Readable> Readable for VecReadWrapper<T> {
247 fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
248 let count: u64 = Readable::read(reader)?;
249 let mut values = Vec::with_capacity(cmp::min(count, MAX_ALLOC_SIZE / (core::mem::size_of::<T>() as u64)) as usize);
251 match Readable::read(reader) {
252 Ok(v) => { values.push(v); },
253 Err(e) => return Err(e),
260 pub(crate) struct U48(pub u64);
261 impl Writeable for U48 {
263 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
264 writer.write_all(&be48_to_array(self.0))
267 impl Readable for U48 {
269 fn read<R: Read>(reader: &mut R) -> Result<U48, DecodeError> {
270 let mut buf = [0; 6];
271 reader.read_exact(&mut buf)?;
272 Ok(U48(slice_to_be48(&buf)))
276 /// Lightning TLV uses a custom variable-length integer called BigSize. It is similar to Bitcoin's
277 /// variable-length integers except that it is serialized in big-endian instead of little-endian.
279 /// Like Bitcoin's variable-length integer, it exhibits ambiguity in that certain values can be
280 /// encoded in several different ways, which we must check for at deserialization-time. Thus, if
281 /// you're looking for an example of a variable-length integer to use for your own project, move
282 /// along, this is a rather poor design.
283 pub(crate) struct BigSize(pub u64);
284 impl Writeable for BigSize {
286 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
289 (self.0 as u8).write(writer)
292 0xFDu8.write(writer)?;
293 (self.0 as u16).write(writer)
295 0x10000...0xFFFFFFFF => {
296 0xFEu8.write(writer)?;
297 (self.0 as u32).write(writer)
300 0xFFu8.write(writer)?;
301 (self.0 as u64).write(writer)
306 impl Readable for BigSize {
308 fn read<R: Read>(reader: &mut R) -> Result<BigSize, DecodeError> {
309 let n: u8 = Readable::read(reader)?;
312 let x: u64 = Readable::read(reader)?;
314 Err(DecodeError::InvalidValue)
320 let x: u32 = Readable::read(reader)?;
322 Err(DecodeError::InvalidValue)
324 Ok(BigSize(x as u64))
328 let x: u16 = Readable::read(reader)?;
330 Err(DecodeError::InvalidValue)
332 Ok(BigSize(x as u64))
335 n => Ok(BigSize(n as u64))
340 /// In TLV we occasionally send fields which only consist of, or potentially end with, a
341 /// variable-length integer which is simply truncated by skipping high zero bytes. This type
342 /// encapsulates such integers implementing Readable/Writeable for them.
343 #[cfg_attr(test, derive(PartialEq, Debug))]
344 pub(crate) struct HighZeroBytesDroppedVarInt<T>(pub T);
346 macro_rules! impl_writeable_primitive {
347 ($val_type:ty, $meth_write:ident, $len: expr, $meth_read:ident) => {
348 impl Writeable for $val_type {
350 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
351 writer.write_all(&$meth_write(*self))
354 impl Writeable for HighZeroBytesDroppedVarInt<$val_type> {
356 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
357 // Skip any full leading 0 bytes when writing (in BE):
358 writer.write_all(&$meth_write(self.0)[(self.0.leading_zeros()/8) as usize..$len])
361 impl Readable for $val_type {
363 fn read<R: Read>(reader: &mut R) -> Result<$val_type, DecodeError> {
364 let mut buf = [0; $len];
365 reader.read_exact(&mut buf)?;
369 impl Readable for HighZeroBytesDroppedVarInt<$val_type> {
371 fn read<R: Read>(reader: &mut R) -> Result<HighZeroBytesDroppedVarInt<$val_type>, DecodeError> {
372 // We need to accept short reads (read_len == 0) as "EOF" and handle them as simply
373 // the high bytes being dropped. To do so, we start reading into the middle of buf
374 // and then convert the appropriate number of bytes with extra high bytes out of
376 let mut buf = [0; $len*2];
377 let mut read_len = reader.read(&mut buf[$len..])?;
378 let mut total_read_len = read_len;
379 while read_len != 0 && total_read_len != $len {
380 read_len = reader.read(&mut buf[($len + total_read_len)..])?;
381 total_read_len += read_len;
383 if total_read_len == 0 || buf[$len] != 0 {
384 let first_byte = $len - ($len - total_read_len);
385 Ok(HighZeroBytesDroppedVarInt($meth_read(&buf[first_byte..first_byte + $len])))
387 // If the encoding had extra zero bytes, return a failure even though we know
388 // what they meant (as the TLV test vectors require this)
389 Err(DecodeError::InvalidValue)
396 impl_writeable_primitive!(u64, be64_to_array, 8, slice_to_be64);
397 impl_writeable_primitive!(u32, be32_to_array, 4, slice_to_be32);
398 impl_writeable_primitive!(u16, be16_to_array, 2, slice_to_be16);
400 impl Writeable for u8 {
402 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
403 writer.write_all(&[*self])
406 impl Readable for u8 {
408 fn read<R: Read>(reader: &mut R) -> Result<u8, DecodeError> {
409 let mut buf = [0; 1];
410 reader.read_exact(&mut buf)?;
415 impl Writeable for bool {
417 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
418 writer.write_all(&[if *self {1} else {0}])
421 impl Readable for bool {
423 fn read<R: Read>(reader: &mut R) -> Result<bool, DecodeError> {
424 let mut buf = [0; 1];
425 reader.read_exact(&mut buf)?;
426 if buf[0] != 0 && buf[0] != 1 {
427 return Err(DecodeError::InvalidValue);
434 macro_rules! impl_array {
436 impl Writeable for [u8; $size]
439 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
444 impl Readable for [u8; $size]
447 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
448 let mut buf = [0u8; $size];
449 r.read_exact(&mut buf)?;
456 //TODO: performance issue with [u8; size] with impl_array!()
457 impl_array!(3); // for rgb
458 impl_array!(4); // for IPv4
459 impl_array!(10); // for OnionV2
460 impl_array!(16); // for IPv6
461 impl_array!(32); // for channel id & hmac
462 impl_array!(PUBLIC_KEY_SIZE); // for PublicKey
463 impl_array!(COMPACT_SIGNATURE_SIZE); // for Signature
464 impl_array!(1300); // for OnionPacket.hop_data
467 impl<K, V> Writeable for HashMap<K, V>
468 where K: Writeable + Eq + Hash,
472 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
473 (self.len() as u16).write(w)?;
474 for (key, value) in self.iter() {
482 impl<K, V> Readable for HashMap<K, V>
483 where K: Readable + Eq + Hash,
487 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
488 let len: u16 = Readable::read(r)?;
489 let mut ret = HashMap::with_capacity(len as usize);
491 ret.insert(K::read(r)?, V::read(r)?);
498 impl Writeable for Vec<u8> {
500 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
501 (self.len() as u16).write(w)?;
506 impl Readable for Vec<u8> {
508 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
509 let len: u16 = Readable::read(r)?;
510 let mut ret = Vec::with_capacity(len as usize);
511 ret.resize(len as usize, 0);
512 r.read_exact(&mut ret)?;
516 impl Writeable for Vec<Signature> {
518 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
519 (self.len() as u16).write(w)?;
520 for e in self.iter() {
527 impl Readable for Vec<Signature> {
529 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
530 let len: u16 = Readable::read(r)?;
531 let byte_size = (len as usize)
532 .checked_mul(COMPACT_SIGNATURE_SIZE)
533 .ok_or(DecodeError::BadLengthDescriptor)?;
534 if byte_size > MAX_BUF_SIZE {
535 return Err(DecodeError::BadLengthDescriptor);
537 let mut ret = Vec::with_capacity(len as usize);
538 for _ in 0..len { ret.push(Signature::read(r)?); }
543 impl Writeable for Script {
544 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
545 (self.len() as u16).write(w)?;
546 w.write_all(self.as_bytes())
550 impl Readable for Script {
551 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
552 let len = <u16 as Readable>::read(r)? as usize;
553 let mut buf = vec![0; len];
554 r.read_exact(&mut buf)?;
555 Ok(Script::from(buf))
559 impl Writeable for PublicKey {
560 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
561 self.serialize().write(w)
565 impl Readable for PublicKey {
566 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
567 let buf: [u8; PUBLIC_KEY_SIZE] = Readable::read(r)?;
568 match PublicKey::from_slice(&buf) {
570 Err(_) => return Err(DecodeError::InvalidValue),
575 impl Writeable for SecretKey {
576 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
577 let mut ser = [0; 32];
578 ser.copy_from_slice(&self[..]);
583 impl Readable for SecretKey {
584 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
585 let buf: [u8; 32] = Readable::read(r)?;
586 match SecretKey::from_slice(&buf) {
588 Err(_) => return Err(DecodeError::InvalidValue),
593 impl Writeable for Sha256dHash {
594 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
595 w.write_all(&self[..])
599 impl Readable for Sha256dHash {
600 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
601 use bitcoin::hashes::Hash;
603 let buf: [u8; 32] = Readable::read(r)?;
604 Ok(Sha256dHash::from_slice(&buf[..]).unwrap())
608 impl Writeable for Signature {
609 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
610 self.serialize_compact().write(w)
614 impl Readable for Signature {
615 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
616 let buf: [u8; COMPACT_SIGNATURE_SIZE] = Readable::read(r)?;
617 match Signature::from_compact(&buf) {
619 Err(_) => return Err(DecodeError::InvalidValue),
624 impl Writeable for PaymentPreimage {
625 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
630 impl Readable for PaymentPreimage {
631 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
632 let buf: [u8; 32] = Readable::read(r)?;
633 Ok(PaymentPreimage(buf))
637 impl Writeable for PaymentHash {
638 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
643 impl Readable for PaymentHash {
644 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
645 let buf: [u8; 32] = Readable::read(r)?;
650 impl Writeable for PaymentSecret {
651 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
656 impl Readable for PaymentSecret {
657 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
658 let buf: [u8; 32] = Readable::read(r)?;
659 Ok(PaymentSecret(buf))
663 impl<T: Writeable> Writeable for Option<T> {
664 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
666 None => 0u8.write(w)?,
668 let mut len_calc = LengthCalculatingWriter(0);
669 data.write(&mut len_calc).expect("No in-memory data may fail to serialize");
670 BigSize(len_calc.0 as u64 + 1).write(w)?;
678 impl<T: Readable> Readable for Option<T>
680 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
681 match BigSize::read(r)?.0 {
684 let mut reader = FixedLengthReader::new(r, len - 1);
685 Ok(Some(Readable::read(&mut reader)?))
691 impl Writeable for Txid {
692 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
693 w.write_all(&self[..])
697 impl Readable for Txid {
698 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
699 use bitcoin::hashes::Hash;
701 let buf: [u8; 32] = Readable::read(r)?;
702 Ok(Txid::from_slice(&buf[..]).unwrap())
706 impl Writeable for BlockHash {
707 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
708 w.write_all(&self[..])
712 impl Readable for BlockHash {
713 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
714 use bitcoin::hashes::Hash;
716 let buf: [u8; 32] = Readable::read(r)?;
717 Ok(BlockHash::from_slice(&buf[..]).unwrap())
721 impl Writeable for OutPoint {
722 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
729 impl Readable for OutPoint {
730 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
731 let txid = Readable::read(r)?;
732 let vout = Readable::read(r)?;
740 macro_rules! impl_consensus_ser {
741 ($bitcoin_type: ty) => {
742 impl Writeable for $bitcoin_type {
743 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
744 match self.consensus_encode(WriterWriteAdaptor(writer)) {
751 impl Readable for $bitcoin_type {
752 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
753 match consensus::encode::Decodable::consensus_decode(r) {
755 Err(consensus::encode::Error::Io(ref e)) if e.kind() == ::std::io::ErrorKind::UnexpectedEof => Err(DecodeError::ShortRead),
756 Err(consensus::encode::Error::Io(e)) => Err(DecodeError::Io(e.kind())),
757 Err(_) => Err(DecodeError::InvalidValue),
763 impl_consensus_ser!(Transaction);
764 impl_consensus_ser!(TxOut);
766 impl<T: Readable> Readable for Mutex<T> {
767 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
768 let t: T = Readable::read(r)?;
772 impl<T: Writeable> Writeable for Mutex<T> {
773 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
774 self.lock().unwrap().write(w)
778 impl<A: Readable, B: Readable> Readable for (A, B) {
779 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
780 let a: A = Readable::read(r)?;
781 let b: B = Readable::read(r)?;
785 impl<A: Writeable, B: Writeable> Writeable for (A, B) {
786 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {