1 //! A very simple serialization framework which is used to serialize/deserialize messages as well
2 //! as ChannelsManagers and ChannelMonitors.
4 use std::result::Result;
5 use std::io::{Read, Write};
6 use std::collections::HashMap;
9 use secp256k1::{Secp256k1, Signature};
10 use secp256k1::key::{PublicKey, SecretKey};
11 use bitcoin::util::hash::Sha256dHash;
12 use bitcoin::blockdata::script::Script;
13 use std::marker::Sized;
14 use ln::msgs::DecodeError;
15 use ln::channelmanager::{PaymentPreimage, PaymentHash};
18 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};
20 const MAX_BUF_SIZE: usize = 64 * 1024;
22 /// A trait that is similar to std::io::Write but has one extra function which can be used to size
23 /// buffers being written into.
24 /// An impl is provided for any type that also impls std::io::Write which simply ignores size
27 /// Writes the given buf out. See std::io::Write::write_all for more
28 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error>;
29 /// Hints that data of the given size is about the be written. This may not always be called
30 /// prior to data being written and may be safely ignored.
31 fn size_hint(&mut self, size: usize);
34 impl<W: Write> Writer for W {
36 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
37 <Self as ::std::io::Write>::write_all(self, buf)
40 fn size_hint(&mut self, _size: usize) { }
43 pub(crate) struct WriterWriteAdaptor<'a, W: Writer + 'a>(pub &'a mut W);
44 impl<'a, W: Writer + 'a> Write for WriterWriteAdaptor<'a, W> {
45 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
48 fn write(&mut self, buf: &[u8]) -> Result<usize, ::std::io::Error> {
49 self.0.write_all(buf)?;
52 fn flush(&mut self) -> Result<(), ::std::io::Error> {
57 struct VecWriter(Vec<u8>);
58 impl Writer for VecWriter {
59 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
60 self.0.extend_from_slice(buf);
63 fn size_hint(&mut self, size: usize) {
64 self.0.reserve_exact(size);
68 /// A trait that various rust-lightning types implement allowing them to be written out to a Writer
70 /// Writes self out to the given Writer
71 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error>;
73 /// Writes self out to a Vec<u8>
74 fn encode(&self) -> Vec<u8> {
75 let mut msg = VecWriter(Vec::new());
76 self.write(&mut msg).unwrap();
80 /// Writes self out to a Vec<u8>
81 fn encode_with_len(&self) -> Vec<u8> {
82 let mut msg = VecWriter(Vec::new());
83 0u16.write(&mut msg).unwrap();
84 self.write(&mut msg).unwrap();
85 let len = msg.0.len();
86 msg.0[..2].copy_from_slice(&byte_utils::be16_to_array(len as u16 - 2));
91 /// A trait that various rust-lightning types implement allowing them to be read in from a Read
96 /// Reads a Self in from the given Read
97 fn read(reader: &mut R) -> Result<Self, DecodeError>;
100 /// A trait that various higher-level rust-lightning types implement allowing them to be read in
101 /// from a Read given some additional set of arguments which is required to deserialize.
102 pub trait ReadableArgs<R, P>
106 /// Reads a Self in from the given Read
107 fn read(reader: &mut R, params: P) -> Result<Self, DecodeError>;
110 pub(crate) struct U48(pub u64);
111 impl Writeable for U48 {
113 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
114 writer.write_all(&be48_to_array(self.0))
117 impl<R: Read> Readable<R> for U48 {
119 fn read(reader: &mut R) -> Result<U48, DecodeError> {
120 let mut buf = [0; 6];
121 reader.read_exact(&mut buf)?;
122 Ok(U48(slice_to_be48(&buf)))
126 macro_rules! impl_writeable_primitive {
127 ($val_type:ty, $meth_write:ident, $len: expr, $meth_read:ident) => {
128 impl Writeable for $val_type {
130 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
131 writer.write_all(&$meth_write(*self))
134 impl<R: Read> Readable<R> for $val_type {
136 fn read(reader: &mut R) -> Result<$val_type, DecodeError> {
137 let mut buf = [0; $len];
138 reader.read_exact(&mut buf)?;
145 impl_writeable_primitive!(u64, be64_to_array, 8, slice_to_be64);
146 impl_writeable_primitive!(u32, be32_to_array, 4, slice_to_be32);
147 impl_writeable_primitive!(u16, be16_to_array, 2, slice_to_be16);
149 impl Writeable for u8 {
151 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
152 writer.write_all(&[*self])
155 impl<R: Read> Readable<R> for u8 {
157 fn read(reader: &mut R) -> Result<u8, DecodeError> {
158 let mut buf = [0; 1];
159 reader.read_exact(&mut buf)?;
164 impl Writeable for bool {
166 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
167 writer.write_all(&[if *self {1} else {0}])
170 impl<R: Read> Readable<R> for bool {
172 fn read(reader: &mut R) -> Result<bool, DecodeError> {
173 let mut buf = [0; 1];
174 reader.read_exact(&mut buf)?;
175 if buf[0] != 0 && buf[0] != 1 {
176 return Err(DecodeError::InvalidValue);
183 macro_rules! impl_array {
185 impl Writeable for [u8; $size]
188 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
193 impl<R: Read> Readable<R> for [u8; $size]
196 fn read(r: &mut R) -> Result<Self, DecodeError> {
197 let mut buf = [0u8; $size];
198 r.read_exact(&mut buf)?;
205 //TODO: performance issue with [u8; size] with impl_array!()
206 impl_array!(32); // for channel id & hmac
207 impl_array!(33); // for PublicKey
208 impl_array!(64); // for Signature
209 impl_array!(1300); // for OnionPacket.hop_data
212 impl<K, V> Writeable for HashMap<K, V>
213 where K: Writeable + Eq + Hash,
217 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
218 (self.len() as u16).write(w)?;
219 for (key, value) in self.iter() {
227 impl<R, K, V> Readable<R> for HashMap<K, V>
229 K: Readable<R> + Eq + Hash,
233 fn read(r: &mut R) -> Result<Self, DecodeError> {
234 let len: u16 = Readable::read(r)?;
235 let mut ret = HashMap::with_capacity(len as usize);
237 ret.insert(K::read(r)?, V::read(r)?);
244 impl Writeable for Vec<u8> {
246 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
247 (self.len() as u16).write(w)?;
252 impl<R: Read> Readable<R> for Vec<u8> {
254 fn read(r: &mut R) -> Result<Self, DecodeError> {
255 let len: u16 = Readable::read(r)?;
256 let mut ret = Vec::with_capacity(len as usize);
257 ret.resize(len as usize, 0);
258 r.read_exact(&mut ret)?;
262 impl Writeable for Vec<Signature> {
264 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
265 (self.len() as u16).write(w)?;
266 for e in self.iter() {
273 impl<R: Read> Readable<R> for Vec<Signature> {
275 fn read(r: &mut R) -> Result<Self, DecodeError> {
276 let len: u16 = Readable::read(r)?;
277 let byte_size = (len as usize)
279 .ok_or(DecodeError::BadLengthDescriptor)?;
280 if byte_size > MAX_BUF_SIZE {
281 return Err(DecodeError::BadLengthDescriptor);
283 let mut ret = Vec::with_capacity(len as usize);
284 for _ in 0..len { ret.push(Signature::read(r)?); }
289 impl Writeable for Script {
290 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
291 (self.len() as u16).write(w)?;
292 w.write_all(self.as_bytes())
296 impl<R: Read> Readable<R> for Script {
297 fn read(r: &mut R) -> Result<Self, DecodeError> {
298 let len = <u16 as Readable<R>>::read(r)? as usize;
299 let mut buf = vec![0; len];
300 r.read_exact(&mut buf)?;
301 Ok(Script::from(buf))
305 impl Writeable for Option<Script> {
306 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
307 if let &Some(ref script) = self {
314 impl<R: Read> Readable<R> for Option<Script> {
315 fn read(r: &mut R) -> Result<Self, DecodeError> {
316 match <u16 as Readable<R>>::read(r) {
318 let mut buf = vec![0; len as usize];
319 r.read_exact(&mut buf)?;
320 Ok(Some(Script::from(buf)))
322 Err(DecodeError::ShortRead) => Ok(None),
328 impl Writeable for PublicKey {
329 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
330 self.serialize().write(w)
334 impl<R: Read> Readable<R> for PublicKey {
335 fn read(r: &mut R) -> Result<Self, DecodeError> {
336 let buf: [u8; 33] = Readable::read(r)?;
337 match PublicKey::from_slice(&Secp256k1::without_caps(), &buf) {
339 Err(_) => return Err(DecodeError::InvalidValue),
344 impl Writeable for SecretKey {
345 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
346 let mut ser = [0; 32];
347 ser.copy_from_slice(&self[..]);
352 impl<R: Read> Readable<R> for SecretKey {
353 fn read(r: &mut R) -> Result<Self, DecodeError> {
354 let buf: [u8; 32] = Readable::read(r)?;
355 match SecretKey::from_slice(&Secp256k1::without_caps(), &buf) {
357 Err(_) => return Err(DecodeError::InvalidValue),
362 impl Writeable for Sha256dHash {
363 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
364 self.as_bytes().write(w)
368 impl<R: Read> Readable<R> for Sha256dHash {
369 fn read(r: &mut R) -> Result<Self, DecodeError> {
370 let buf: [u8; 32] = Readable::read(r)?;
371 Ok(From::from(&buf[..]))
375 impl Writeable for Signature {
376 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
377 self.serialize_compact(&Secp256k1::without_caps()).write(w)
381 impl<R: Read> Readable<R> for Signature {
382 fn read(r: &mut R) -> Result<Self, DecodeError> {
383 let buf: [u8; 64] = Readable::read(r)?;
384 match Signature::from_compact(&Secp256k1::without_caps(), &buf) {
386 Err(_) => return Err(DecodeError::InvalidValue),
391 impl Writeable for PaymentPreimage {
392 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
397 impl<R: Read> Readable<R> for PaymentPreimage {
398 fn read(r: &mut R) -> Result<Self, DecodeError> {
399 let buf: [u8; 32] = Readable::read(r)?;
400 Ok(PaymentPreimage(buf))
404 impl Writeable for PaymentHash {
405 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
410 impl<R: Read> Readable<R> for PaymentHash {
411 fn read(r: &mut R) -> Result<Self, DecodeError> {
412 let buf: [u8; 32] = Readable::read(r)?;