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 /// serialization buffer size
35 pub const MAX_BUF_SIZE: usize = 64 * 1024;
37 /// A trait that is similar to std::io::Write but has one extra function which can be used to size
38 /// buffers being written into.
39 /// An impl is provided for any type that also impls std::io::Write which simply ignores size
42 /// (C-not exported) as we only export serialization to/from byte arrays instead
44 /// Writes the given buf out. See std::io::Write::write_all for more
45 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error>;
46 /// Hints that data of the given size is about the be written. This may not always be called
47 /// prior to data being written and may be safely ignored.
48 fn size_hint(&mut self, size: usize);
51 impl<W: Write> Writer for W {
53 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
54 <Self as ::std::io::Write>::write_all(self, buf)
57 fn size_hint(&mut self, _size: usize) { }
60 pub(crate) struct WriterWriteAdaptor<'a, W: Writer + 'a>(pub &'a mut W);
61 impl<'a, W: Writer + 'a> Write for WriterWriteAdaptor<'a, W> {
62 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
65 fn write(&mut self, buf: &[u8]) -> Result<usize, ::std::io::Error> {
66 self.0.write_all(buf)?;
69 fn flush(&mut self) -> Result<(), ::std::io::Error> {
74 pub(crate) struct VecWriter(pub Vec<u8>);
75 impl Writer for VecWriter {
76 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
77 self.0.extend_from_slice(buf);
80 fn size_hint(&mut self, size: usize) {
81 self.0.reserve_exact(size);
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(crate) struct LengthCalculatingWriter(pub usize);
88 impl Writer for LengthCalculatingWriter {
90 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
95 fn size_hint(&mut self, _size: usize) {}
98 /// Essentially std::io::Take but a bit simpler and with a method to walk the underlying stream
99 /// forward to ensure we always consume exactly the fixed length specified.
100 pub(crate) struct FixedLengthReader<R: Read> {
105 impl<R: Read> FixedLengthReader<R> {
106 pub fn new(read: R, total_bytes: u64) -> Self {
107 Self { read, bytes_read: 0, total_bytes }
110 pub fn bytes_remain(&mut self) -> bool {
111 self.bytes_read != self.total_bytes
114 pub fn eat_remaining(&mut self) -> Result<(), DecodeError> {
115 ::std::io::copy(self, &mut ::std::io::sink()).unwrap();
116 if self.bytes_read != self.total_bytes {
117 Err(DecodeError::ShortRead)
123 impl<R: Read> Read for FixedLengthReader<R> {
124 fn read(&mut self, dest: &mut [u8]) -> Result<usize, ::std::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 /// A Read which tracks whether any bytes have been read at all. This allows us to distinguish
141 /// between "EOF reached before we started" and "EOF reached mid-read".
142 pub(crate) struct ReadTrackingReader<R: Read> {
146 impl<R: Read> ReadTrackingReader<R> {
147 pub fn new(read: R) -> Self {
148 Self { read, have_read: false }
151 impl<R: Read> Read for ReadTrackingReader<R> {
152 fn read(&mut self, dest: &mut [u8]) -> Result<usize, ::std::io::Error> {
153 match self.read.read(dest) {
156 self.have_read = true;
164 /// A trait that various rust-lightning types implement allowing them to be written out to a Writer
166 /// (C-not exported) as we only export serialization to/from byte arrays instead
167 pub trait Writeable {
168 /// Writes self out to the given Writer
169 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error>;
171 /// Writes self out to a Vec<u8>
172 fn encode(&self) -> Vec<u8> {
173 let mut msg = VecWriter(Vec::new());
174 self.write(&mut msg).unwrap();
178 /// Writes self out to a Vec<u8>
179 fn encode_with_len(&self) -> Vec<u8> {
180 let mut msg = VecWriter(Vec::new());
181 0u16.write(&mut msg).unwrap();
182 self.write(&mut msg).unwrap();
183 let len = msg.0.len();
184 msg.0[..2].copy_from_slice(&byte_utils::be16_to_array(len as u16 - 2));
189 impl<'a, T: Writeable> Writeable for &'a T {
190 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> { (*self).write(writer) }
193 /// A trait that various rust-lightning types implement allowing them to be read in from a Read
195 /// (C-not exported) as we only export serialization to/from byte arrays instead
199 /// Reads a Self in from the given Read
200 fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError>;
203 /// A trait that various higher-level rust-lightning types implement allowing them to be read in
204 /// from a Read given some additional set of arguments which is required to deserialize.
206 /// (C-not exported) as we only export serialization to/from byte arrays instead
207 pub trait ReadableArgs<P>
210 /// Reads a Self in from the given Read
211 fn read<R: Read>(reader: &mut R, params: P) -> Result<Self, DecodeError>;
214 /// A trait that various rust-lightning types implement allowing them to (maybe) be read in from a Read
216 /// (C-not exported) as we only export serialization to/from byte arrays instead
217 pub trait MaybeReadable
220 /// Reads a Self in from the given Read
221 fn read<R: Read>(reader: &mut R) -> Result<Option<Self>, DecodeError>;
224 pub(crate) struct U48(pub u64);
225 impl Writeable for U48 {
227 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
228 writer.write_all(&be48_to_array(self.0))
231 impl Readable for U48 {
233 fn read<R: Read>(reader: &mut R) -> Result<U48, DecodeError> {
234 let mut buf = [0; 6];
235 reader.read_exact(&mut buf)?;
236 Ok(U48(slice_to_be48(&buf)))
240 /// Lightning TLV uses a custom variable-length integer called BigSize. It is similar to Bitcoin's
241 /// variable-length integers except that it is serialized in big-endian instead of little-endian.
243 /// Like Bitcoin's variable-length integer, it exhibits ambiguity in that certain values can be
244 /// encoded in several different ways, which we must check for at deserialization-time. Thus, if
245 /// you're looking for an example of a variable-length integer to use for your own project, move
246 /// along, this is a rather poor design.
247 pub(crate) struct BigSize(pub u64);
248 impl Writeable for BigSize {
250 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
253 (self.0 as u8).write(writer)
256 0xFDu8.write(writer)?;
257 (self.0 as u16).write(writer)
259 0x10000...0xFFFFFFFF => {
260 0xFEu8.write(writer)?;
261 (self.0 as u32).write(writer)
264 0xFFu8.write(writer)?;
265 (self.0 as u64).write(writer)
270 impl Readable for BigSize {
272 fn read<R: Read>(reader: &mut R) -> Result<BigSize, DecodeError> {
273 let n: u8 = Readable::read(reader)?;
276 let x: u64 = Readable::read(reader)?;
278 Err(DecodeError::InvalidValue)
284 let x: u32 = Readable::read(reader)?;
286 Err(DecodeError::InvalidValue)
288 Ok(BigSize(x as u64))
292 let x: u16 = Readable::read(reader)?;
294 Err(DecodeError::InvalidValue)
296 Ok(BigSize(x as u64))
299 n => Ok(BigSize(n as u64))
304 /// In TLV we occasionally send fields which only consist of, or potentially end with, a
305 /// variable-length integer which is simply truncated by skipping high zero bytes. This type
306 /// encapsulates such integers implementing Readable/Writeable for them.
307 #[cfg_attr(test, derive(PartialEq, Debug))]
308 pub(crate) struct HighZeroBytesDroppedVarInt<T>(pub T);
310 macro_rules! impl_writeable_primitive {
311 ($val_type:ty, $meth_write:ident, $len: expr, $meth_read:ident) => {
312 impl Writeable for $val_type {
314 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
315 writer.write_all(&$meth_write(*self))
318 impl Writeable for HighZeroBytesDroppedVarInt<$val_type> {
320 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
321 // Skip any full leading 0 bytes when writing (in BE):
322 writer.write_all(&$meth_write(self.0)[(self.0.leading_zeros()/8) as usize..$len])
325 impl Readable for $val_type {
327 fn read<R: Read>(reader: &mut R) -> Result<$val_type, DecodeError> {
328 let mut buf = [0; $len];
329 reader.read_exact(&mut buf)?;
333 impl Readable for HighZeroBytesDroppedVarInt<$val_type> {
335 fn read<R: Read>(reader: &mut R) -> Result<HighZeroBytesDroppedVarInt<$val_type>, DecodeError> {
336 // We need to accept short reads (read_len == 0) as "EOF" and handle them as simply
337 // the high bytes being dropped. To do so, we start reading into the middle of buf
338 // and then convert the appropriate number of bytes with extra high bytes out of
340 let mut buf = [0; $len*2];
341 let mut read_len = reader.read(&mut buf[$len..])?;
342 let mut total_read_len = read_len;
343 while read_len != 0 && total_read_len != $len {
344 read_len = reader.read(&mut buf[($len + total_read_len)..])?;
345 total_read_len += read_len;
347 if total_read_len == 0 || buf[$len] != 0 {
348 let first_byte = $len - ($len - total_read_len);
349 Ok(HighZeroBytesDroppedVarInt($meth_read(&buf[first_byte..first_byte + $len])))
351 // If the encoding had extra zero bytes, return a failure even though we know
352 // what they meant (as the TLV test vectors require this)
353 Err(DecodeError::InvalidValue)
360 impl_writeable_primitive!(u64, be64_to_array, 8, slice_to_be64);
361 impl_writeable_primitive!(u32, be32_to_array, 4, slice_to_be32);
362 impl_writeable_primitive!(u16, be16_to_array, 2, slice_to_be16);
364 impl Writeable for u8 {
366 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
367 writer.write_all(&[*self])
370 impl Readable for u8 {
372 fn read<R: Read>(reader: &mut R) -> Result<u8, DecodeError> {
373 let mut buf = [0; 1];
374 reader.read_exact(&mut buf)?;
379 impl Writeable for bool {
381 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
382 writer.write_all(&[if *self {1} else {0}])
385 impl Readable for bool {
387 fn read<R: Read>(reader: &mut R) -> Result<bool, DecodeError> {
388 let mut buf = [0; 1];
389 reader.read_exact(&mut buf)?;
390 if buf[0] != 0 && buf[0] != 1 {
391 return Err(DecodeError::InvalidValue);
398 macro_rules! impl_array {
400 impl Writeable for [u8; $size]
403 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
408 impl Readable for [u8; $size]
411 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
412 let mut buf = [0u8; $size];
413 r.read_exact(&mut buf)?;
420 //TODO: performance issue with [u8; size] with impl_array!()
421 impl_array!(3); // for rgb
422 impl_array!(4); // for IPv4
423 impl_array!(10); // for OnionV2
424 impl_array!(16); // for IPv6
425 impl_array!(32); // for channel id & hmac
426 impl_array!(33); // for PublicKey
427 impl_array!(64); // for Signature
428 impl_array!(1300); // for OnionPacket.hop_data
431 impl<K, V> Writeable for HashMap<K, V>
432 where K: Writeable + Eq + Hash,
436 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
437 (self.len() as u16).write(w)?;
438 for (key, value) in self.iter() {
446 impl<K, V> Readable for HashMap<K, V>
447 where K: Readable + Eq + Hash,
451 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
452 let len: u16 = Readable::read(r)?;
453 let mut ret = HashMap::with_capacity(len as usize);
455 ret.insert(K::read(r)?, V::read(r)?);
462 impl Writeable for Vec<u8> {
464 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
465 (self.len() as u16).write(w)?;
470 impl Readable for Vec<u8> {
472 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
473 let len: u16 = Readable::read(r)?;
474 let mut ret = Vec::with_capacity(len as usize);
475 ret.resize(len as usize, 0);
476 r.read_exact(&mut ret)?;
480 impl Writeable for Vec<Signature> {
482 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
483 (self.len() as u16).write(w)?;
484 for e in self.iter() {
491 impl Readable for Vec<Signature> {
493 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
494 let len: u16 = Readable::read(r)?;
495 let byte_size = (len as usize)
497 .ok_or(DecodeError::BadLengthDescriptor)?;
498 if byte_size > MAX_BUF_SIZE {
499 return Err(DecodeError::BadLengthDescriptor);
501 let mut ret = Vec::with_capacity(len as usize);
502 for _ in 0..len { ret.push(Signature::read(r)?); }
507 impl Writeable for Script {
508 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
509 (self.len() as u16).write(w)?;
510 w.write_all(self.as_bytes())
514 impl Readable for Script {
515 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
516 let len = <u16 as Readable>::read(r)? as usize;
517 let mut buf = vec![0; len];
518 r.read_exact(&mut buf)?;
519 Ok(Script::from(buf))
523 impl Writeable for PublicKey {
524 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
525 self.serialize().write(w)
529 impl Readable for PublicKey {
530 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
531 let buf: [u8; 33] = Readable::read(r)?;
532 match PublicKey::from_slice(&buf) {
534 Err(_) => return Err(DecodeError::InvalidValue),
539 impl Writeable for SecretKey {
540 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
541 let mut ser = [0; 32];
542 ser.copy_from_slice(&self[..]);
547 impl Readable for SecretKey {
548 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
549 let buf: [u8; 32] = Readable::read(r)?;
550 match SecretKey::from_slice(&buf) {
552 Err(_) => return Err(DecodeError::InvalidValue),
557 impl Writeable for Sha256dHash {
558 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
559 w.write_all(&self[..])
563 impl Readable for Sha256dHash {
564 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
565 use bitcoin::hashes::Hash;
567 let buf: [u8; 32] = Readable::read(r)?;
568 Ok(Sha256dHash::from_slice(&buf[..]).unwrap())
572 impl Writeable for Signature {
573 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
574 self.serialize_compact().write(w)
578 impl Readable for Signature {
579 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
580 let buf: [u8; 64] = Readable::read(r)?;
581 match Signature::from_compact(&buf) {
583 Err(_) => return Err(DecodeError::InvalidValue),
588 impl Writeable for PaymentPreimage {
589 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
594 impl Readable for PaymentPreimage {
595 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
596 let buf: [u8; 32] = Readable::read(r)?;
597 Ok(PaymentPreimage(buf))
601 impl Writeable for PaymentHash {
602 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
607 impl Readable for PaymentHash {
608 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
609 let buf: [u8; 32] = Readable::read(r)?;
614 impl Writeable for PaymentSecret {
615 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
620 impl Readable for PaymentSecret {
621 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
622 let buf: [u8; 32] = Readable::read(r)?;
623 Ok(PaymentSecret(buf))
627 impl<T: Writeable> Writeable for Option<T> {
628 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
630 None => 0u8.write(w)?,
632 let mut len_calc = LengthCalculatingWriter(0);
633 data.write(&mut len_calc).expect("No in-memory data may fail to serialize");
634 BigSize(len_calc.0 as u64 + 1).write(w)?;
642 impl<T: Readable> Readable for Option<T>
644 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
645 match BigSize::read(r)?.0 {
648 let mut reader = FixedLengthReader::new(r, len - 1);
649 Ok(Some(Readable::read(&mut reader)?))
655 impl Writeable for Txid {
656 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
657 w.write_all(&self[..])
661 impl Readable for Txid {
662 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
663 use bitcoin::hashes::Hash;
665 let buf: [u8; 32] = Readable::read(r)?;
666 Ok(Txid::from_slice(&buf[..]).unwrap())
670 impl Writeable for BlockHash {
671 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
672 w.write_all(&self[..])
676 impl Readable for BlockHash {
677 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
678 use bitcoin::hashes::Hash;
680 let buf: [u8; 32] = Readable::read(r)?;
681 Ok(BlockHash::from_slice(&buf[..]).unwrap())
685 impl Writeable for OutPoint {
686 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
693 impl Readable for OutPoint {
694 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
695 let txid = Readable::read(r)?;
696 let vout = Readable::read(r)?;
704 macro_rules! impl_consensus_ser {
705 ($bitcoin_type: ty) => {
706 impl Writeable for $bitcoin_type {
707 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
708 match self.consensus_encode(WriterWriteAdaptor(writer)) {
710 Err(consensus::encode::Error::Io(e)) => Err(e),
711 Err(_) => panic!("We shouldn't get a consensus::encode::Error unless our Write generated an std::io::Error"),
716 impl Readable for $bitcoin_type {
717 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
718 match consensus::encode::Decodable::consensus_decode(r) {
720 Err(consensus::encode::Error::Io(ref e)) if e.kind() == ::std::io::ErrorKind::UnexpectedEof => Err(DecodeError::ShortRead),
721 Err(consensus::encode::Error::Io(e)) => Err(DecodeError::Io(e)),
722 Err(_) => Err(DecodeError::InvalidValue),
728 impl_consensus_ser!(Transaction);
729 impl_consensus_ser!(TxOut);
731 impl<T: Readable> Readable for Mutex<T> {
732 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
733 let t: T = Readable::read(r)?;
737 impl<T: Writeable> Writeable for Mutex<T> {
738 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
739 self.lock().unwrap().write(w)
743 impl<A: Readable, B: Readable> Readable for (A, B) {
744 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
745 let a: A = Readable::read(r)?;
746 let b: B = Readable::read(r)?;
750 impl<A: Writeable, B: Writeable> Writeable for (A, B) {
751 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {