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 std::io::{Read, Write};
14 use std::collections::HashMap;
19 use bitcoin::secp256k1::Signature;
20 use bitcoin::secp256k1::key::{PublicKey, SecretKey};
21 use bitcoin::blockdata::script::Script;
22 use bitcoin::blockdata::transaction::{OutPoint, Transaction, TxOut};
23 use bitcoin::consensus;
24 use bitcoin::consensus::Encodable;
25 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
26 use bitcoin::hash_types::{Txid, BlockHash};
27 use std::marker::Sized;
28 use ln::msgs::DecodeError;
29 use ln::channelmanager::{PaymentPreimage, PaymentHash, PaymentSecret};
32 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};
34 const MAX_BUF_SIZE: usize = 64 * 1024;
36 /// A trait that is similar to std::io::Write but has one extra function which can be used to size
37 /// buffers being written into.
38 /// An impl is provided for any type that also impls std::io::Write which simply ignores size
41 /// (C-not exported) as we only export serialization to/from byte arrays instead
43 /// Writes the given buf out. See std::io::Write::write_all for more
44 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error>;
45 /// Hints that data of the given size is about the be written. This may not always be called
46 /// prior to data being written and may be safely ignored.
47 fn size_hint(&mut self, size: usize);
50 impl<W: Write> Writer for W {
52 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
53 <Self as ::std::io::Write>::write_all(self, buf)
56 fn size_hint(&mut self, _size: usize) { }
59 pub(crate) struct WriterWriteAdaptor<'a, W: Writer + 'a>(pub &'a mut W);
60 impl<'a, W: Writer + 'a> Write for WriterWriteAdaptor<'a, W> {
61 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
64 fn write(&mut self, buf: &[u8]) -> Result<usize, ::std::io::Error> {
65 self.0.write_all(buf)?;
68 fn flush(&mut self) -> Result<(), ::std::io::Error> {
73 pub(crate) struct VecWriter(pub Vec<u8>);
74 impl Writer for VecWriter {
75 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
76 self.0.extend_from_slice(buf);
79 fn size_hint(&mut self, size: usize) {
80 self.0.reserve_exact(size);
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<(), ::std::io::Error> {
94 fn size_hint(&mut self, _size: usize) {}
97 /// Essentially std::io::Take but a bit simpler and with a method to walk the underlying stream
98 /// forward to ensure we always consume exactly the fixed length specified.
99 pub(crate) struct FixedLengthReader<R: Read> {
104 impl<R: Read> FixedLengthReader<R> {
105 pub fn new(read: R, total_bytes: u64) -> Self {
106 Self { read, bytes_read: 0, total_bytes }
109 pub fn bytes_remain(&mut self) -> bool {
110 self.bytes_read != self.total_bytes
113 pub fn eat_remaining(&mut self) -> Result<(), DecodeError> {
114 ::std::io::copy(self, &mut ::std::io::sink()).unwrap();
115 if self.bytes_read != self.total_bytes {
116 Err(DecodeError::ShortRead)
122 impl<R: Read> Read for FixedLengthReader<R> {
123 fn read(&mut self, dest: &mut [u8]) -> Result<usize, ::std::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 /// A Read which tracks whether any bytes have been read at all. This allows us to distinguish
140 /// between "EOF reached before we started" and "EOF reached mid-read".
141 pub(crate) struct ReadTrackingReader<R: Read> {
145 impl<R: Read> ReadTrackingReader<R> {
146 pub fn new(read: R) -> Self {
147 Self { read, have_read: false }
150 impl<R: Read> Read for ReadTrackingReader<R> {
151 fn read(&mut self, dest: &mut [u8]) -> Result<usize, ::std::io::Error> {
152 match self.read.read(dest) {
155 self.have_read = true;
163 /// A trait that various rust-lightning types implement allowing them to be written out to a Writer
165 /// (C-not exported) as we only export serialization to/from byte arrays instead
166 pub trait Writeable {
167 /// Writes self out to the given Writer
168 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error>;
170 /// Writes self out to a Vec<u8>
171 fn encode(&self) -> Vec<u8> {
172 let mut msg = VecWriter(Vec::new());
173 self.write(&mut msg).unwrap();
177 /// Writes self out to a Vec<u8>
178 fn encode_with_len(&self) -> Vec<u8> {
179 let mut msg = VecWriter(Vec::new());
180 0u16.write(&mut msg).unwrap();
181 self.write(&mut msg).unwrap();
182 let len = msg.0.len();
183 msg.0[..2].copy_from_slice(&byte_utils::be16_to_array(len as u16 - 2));
188 impl<'a, T: Writeable> Writeable for &'a T {
189 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> { (*self).write(writer) }
192 /// A trait that various rust-lightning types implement allowing them to be read in from a Read
194 /// (C-not exported) as we only export serialization to/from byte arrays instead
198 /// Reads a Self in from the given Read
199 fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError>;
202 /// A trait that various higher-level rust-lightning types implement allowing them to be read in
203 /// from a Read given some additional set of arguments which is required to deserialize.
205 /// (C-not exported) as we only export serialization to/from byte arrays instead
206 pub trait ReadableArgs<P>
209 /// Reads a Self in from the given Read
210 fn read<R: Read>(reader: &mut R, params: P) -> Result<Self, DecodeError>;
213 /// A trait that various rust-lightning types implement allowing them to (maybe) be read in from a Read
215 /// (C-not exported) as we only export serialization to/from byte arrays instead
216 pub trait MaybeReadable
219 /// Reads a Self in from the given Read
220 fn read<R: Read>(reader: &mut R) -> Result<Option<Self>, DecodeError>;
223 pub(crate) struct U48(pub u64);
224 impl Writeable for U48 {
226 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
227 writer.write_all(&be48_to_array(self.0))
230 impl Readable for U48 {
232 fn read<R: Read>(reader: &mut R) -> Result<U48, DecodeError> {
233 let mut buf = [0; 6];
234 reader.read_exact(&mut buf)?;
235 Ok(U48(slice_to_be48(&buf)))
239 /// Lightning TLV uses a custom variable-length integer called BigSize. It is similar to Bitcoin's
240 /// variable-length integers except that it is serialized in big-endian instead of little-endian.
242 /// Like Bitcoin's variable-length integer, it exhibits ambiguity in that certain values can be
243 /// encoded in several different ways, which we must check for at deserialization-time. Thus, if
244 /// you're looking for an example of a variable-length integer to use for your own project, move
245 /// along, this is a rather poor design.
246 pub(crate) struct BigSize(pub u64);
247 impl Writeable for BigSize {
249 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
252 (self.0 as u8).write(writer)
255 0xFDu8.write(writer)?;
256 (self.0 as u16).write(writer)
258 0x10000...0xFFFFFFFF => {
259 0xFEu8.write(writer)?;
260 (self.0 as u32).write(writer)
263 0xFFu8.write(writer)?;
264 (self.0 as u64).write(writer)
269 impl Readable for BigSize {
271 fn read<R: Read>(reader: &mut R) -> Result<BigSize, DecodeError> {
272 let n: u8 = Readable::read(reader)?;
275 let x: u64 = Readable::read(reader)?;
277 Err(DecodeError::InvalidValue)
283 let x: u32 = Readable::read(reader)?;
285 Err(DecodeError::InvalidValue)
287 Ok(BigSize(x as u64))
291 let x: u16 = Readable::read(reader)?;
293 Err(DecodeError::InvalidValue)
295 Ok(BigSize(x as u64))
298 n => Ok(BigSize(n as u64))
303 /// In TLV we occasionally send fields which only consist of, or potentially end with, a
304 /// variable-length integer which is simply truncated by skipping high zero bytes. This type
305 /// encapsulates such integers implementing Readable/Writeable for them.
306 #[cfg_attr(test, derive(PartialEq, Debug))]
307 pub(crate) struct HighZeroBytesDroppedVarInt<T>(pub T);
309 macro_rules! impl_writeable_primitive {
310 ($val_type:ty, $meth_write:ident, $len: expr, $meth_read:ident) => {
311 impl Writeable for $val_type {
313 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
314 writer.write_all(&$meth_write(*self))
317 impl Writeable for HighZeroBytesDroppedVarInt<$val_type> {
319 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
320 // Skip any full leading 0 bytes when writing (in BE):
321 writer.write_all(&$meth_write(self.0)[(self.0.leading_zeros()/8) as usize..$len])
324 impl Readable for $val_type {
326 fn read<R: Read>(reader: &mut R) -> Result<$val_type, DecodeError> {
327 let mut buf = [0; $len];
328 reader.read_exact(&mut buf)?;
332 impl Readable for HighZeroBytesDroppedVarInt<$val_type> {
334 fn read<R: Read>(reader: &mut R) -> Result<HighZeroBytesDroppedVarInt<$val_type>, DecodeError> {
335 // We need to accept short reads (read_len == 0) as "EOF" and handle them as simply
336 // the high bytes being dropped. To do so, we start reading into the middle of buf
337 // and then convert the appropriate number of bytes with extra high bytes out of
339 let mut buf = [0; $len*2];
340 let mut read_len = reader.read(&mut buf[$len..])?;
341 let mut total_read_len = read_len;
342 while read_len != 0 && total_read_len != $len {
343 read_len = reader.read(&mut buf[($len + total_read_len)..])?;
344 total_read_len += read_len;
346 if total_read_len == 0 || buf[$len] != 0 {
347 let first_byte = $len - ($len - total_read_len);
348 Ok(HighZeroBytesDroppedVarInt($meth_read(&buf[first_byte..first_byte + $len])))
350 // If the encoding had extra zero bytes, return a failure even though we know
351 // what they meant (as the TLV test vectors require this)
352 Err(DecodeError::InvalidValue)
359 impl_writeable_primitive!(u64, be64_to_array, 8, slice_to_be64);
360 impl_writeable_primitive!(u32, be32_to_array, 4, slice_to_be32);
361 impl_writeable_primitive!(u16, be16_to_array, 2, slice_to_be16);
363 impl Writeable for u8 {
365 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
366 writer.write_all(&[*self])
369 impl Readable for u8 {
371 fn read<R: Read>(reader: &mut R) -> Result<u8, DecodeError> {
372 let mut buf = [0; 1];
373 reader.read_exact(&mut buf)?;
378 impl Writeable for bool {
380 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
381 writer.write_all(&[if *self {1} else {0}])
384 impl Readable for bool {
386 fn read<R: Read>(reader: &mut R) -> Result<bool, DecodeError> {
387 let mut buf = [0; 1];
388 reader.read_exact(&mut buf)?;
389 if buf[0] != 0 && buf[0] != 1 {
390 return Err(DecodeError::InvalidValue);
397 macro_rules! impl_array {
399 impl Writeable for [u8; $size]
402 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
407 impl Readable for [u8; $size]
410 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
411 let mut buf = [0u8; $size];
412 r.read_exact(&mut buf)?;
419 //TODO: performance issue with [u8; size] with impl_array!()
420 impl_array!(3); // for rgb
421 impl_array!(4); // for IPv4
422 impl_array!(10); // for OnionV2
423 impl_array!(16); // for IPv6
424 impl_array!(32); // for channel id & hmac
425 impl_array!(33); // for PublicKey
426 impl_array!(64); // for Signature
427 impl_array!(1300); // for OnionPacket.hop_data
430 impl<K, V> Writeable for HashMap<K, V>
431 where K: Writeable + Eq + Hash,
435 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
436 (self.len() as u16).write(w)?;
437 for (key, value) in self.iter() {
445 impl<K, V> Readable for HashMap<K, V>
446 where K: Readable + Eq + Hash,
450 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
451 let len: u16 = Readable::read(r)?;
452 let mut ret = HashMap::with_capacity(len as usize);
454 ret.insert(K::read(r)?, V::read(r)?);
461 impl Writeable for Vec<u8> {
463 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
464 (self.len() as u16).write(w)?;
469 impl Readable for Vec<u8> {
471 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
472 let len: u16 = Readable::read(r)?;
473 let mut ret = Vec::with_capacity(len as usize);
474 ret.resize(len as usize, 0);
475 r.read_exact(&mut ret)?;
479 impl Writeable for Vec<Signature> {
481 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
482 (self.len() as u16).write(w)?;
483 for e in self.iter() {
490 impl Readable for Vec<Signature> {
492 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
493 let len: u16 = Readable::read(r)?;
494 let byte_size = (len as usize)
496 .ok_or(DecodeError::BadLengthDescriptor)?;
497 if byte_size > MAX_BUF_SIZE {
498 return Err(DecodeError::BadLengthDescriptor);
500 let mut ret = Vec::with_capacity(len as usize);
501 for _ in 0..len { ret.push(Signature::read(r)?); }
506 impl Writeable for Script {
507 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
508 (self.len() as u16).write(w)?;
509 w.write_all(self.as_bytes())
513 impl Readable for Script {
514 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
515 let len = <u16 as Readable>::read(r)? as usize;
516 let mut buf = vec![0; len];
517 r.read_exact(&mut buf)?;
518 Ok(Script::from(buf))
522 impl Writeable for PublicKey {
523 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
524 self.serialize().write(w)
528 impl Readable for PublicKey {
529 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
530 let buf: [u8; 33] = Readable::read(r)?;
531 match PublicKey::from_slice(&buf) {
533 Err(_) => return Err(DecodeError::InvalidValue),
538 impl Writeable for SecretKey {
539 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
540 let mut ser = [0; 32];
541 ser.copy_from_slice(&self[..]);
546 impl Readable for SecretKey {
547 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
548 let buf: [u8; 32] = Readable::read(r)?;
549 match SecretKey::from_slice(&buf) {
551 Err(_) => return Err(DecodeError::InvalidValue),
556 impl Writeable for Sha256dHash {
557 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
558 w.write_all(&self[..])
562 impl Readable for Sha256dHash {
563 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
564 use bitcoin::hashes::Hash;
566 let buf: [u8; 32] = Readable::read(r)?;
567 Ok(Sha256dHash::from_slice(&buf[..]).unwrap())
571 impl Writeable for Signature {
572 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
573 self.serialize_compact().write(w)
577 impl Readable for Signature {
578 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
579 let buf: [u8; 64] = Readable::read(r)?;
580 match Signature::from_compact(&buf) {
582 Err(_) => return Err(DecodeError::InvalidValue),
587 impl Writeable for PaymentPreimage {
588 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
593 impl Readable for PaymentPreimage {
594 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
595 let buf: [u8; 32] = Readable::read(r)?;
596 Ok(PaymentPreimage(buf))
600 impl Writeable for PaymentHash {
601 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
606 impl Readable for PaymentHash {
607 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
608 let buf: [u8; 32] = Readable::read(r)?;
613 impl Writeable for PaymentSecret {
614 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
619 impl Readable for PaymentSecret {
620 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
621 let buf: [u8; 32] = Readable::read(r)?;
622 Ok(PaymentSecret(buf))
626 impl<T: Writeable> Writeable for Option<T> {
627 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
629 None => 0u8.write(w)?,
631 let mut len_calc = LengthCalculatingWriter(0);
632 data.write(&mut len_calc).expect("No in-memory data may fail to serialize");
633 BigSize(len_calc.0 as u64 + 1).write(w)?;
641 impl<T: Readable> Readable for Option<T>
643 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
644 match BigSize::read(r)?.0 {
647 let mut reader = FixedLengthReader::new(r, len - 1);
648 Ok(Some(Readable::read(&mut reader)?))
654 impl Writeable for Txid {
655 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
656 w.write_all(&self[..])
660 impl Readable for Txid {
661 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
662 use bitcoin::hashes::Hash;
664 let buf: [u8; 32] = Readable::read(r)?;
665 Ok(Txid::from_slice(&buf[..]).unwrap())
669 impl Writeable for BlockHash {
670 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
671 w.write_all(&self[..])
675 impl Readable for BlockHash {
676 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
677 use bitcoin::hashes::Hash;
679 let buf: [u8; 32] = Readable::read(r)?;
680 Ok(BlockHash::from_slice(&buf[..]).unwrap())
684 impl Writeable for OutPoint {
685 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
692 impl Readable for OutPoint {
693 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
694 let txid = Readable::read(r)?;
695 let vout = Readable::read(r)?;
703 macro_rules! impl_consensus_ser {
704 ($bitcoin_type: ty) => {
705 impl Writeable for $bitcoin_type {
706 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
707 match self.consensus_encode(WriterWriteAdaptor(writer)) {
709 Err(consensus::encode::Error::Io(e)) => Err(e),
710 Err(_) => panic!("We shouldn't get a consensus::encode::Error unless our Write generated an std::io::Error"),
715 impl Readable for $bitcoin_type {
716 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
717 match consensus::encode::Decodable::consensus_decode(r) {
719 Err(consensus::encode::Error::Io(ref e)) if e.kind() == ::std::io::ErrorKind::UnexpectedEof => Err(DecodeError::ShortRead),
720 Err(consensus::encode::Error::Io(e)) => Err(DecodeError::Io(e)),
721 Err(_) => Err(DecodeError::InvalidValue),
727 impl_consensus_ser!(Transaction);
728 impl_consensus_ser!(TxOut);
730 impl<T: Readable> Readable for Mutex<T> {
731 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
732 let t: T = Readable::read(r)?;
736 impl<T: Writeable> Writeable for Mutex<T> {
737 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
738 self.lock().unwrap().write(w)
742 impl<A: Readable, B: Readable> Readable for (A, B) {
743 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
744 let a: A = Readable::read(r)?;
745 let b: B = Readable::read(r)?;
749 impl<A: Writeable, B: Writeable> Writeable for (A, B) {
750 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {