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::Signature;
10 use secp256k1::key::{PublicKey, SecretKey};
11 use bitcoin::blockdata::script::Script;
12 use bitcoin::blockdata::transaction::OutPoint;
13 use bitcoin_hashes::sha256d::Hash as Sha256dHash;
14 use std::marker::Sized;
15 use ln::msgs::DecodeError;
16 use ln::channelmanager::{PaymentPreimage, PaymentHash};
19 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};
21 const MAX_BUF_SIZE: usize = 64 * 1024;
23 /// A trait that is similar to std::io::Write but has one extra function which can be used to size
24 /// buffers being written into.
25 /// An impl is provided for any type that also impls std::io::Write which simply ignores size
28 /// Writes the given buf out. See std::io::Write::write_all for more
29 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error>;
30 /// Hints that data of the given size is about the be written. This may not always be called
31 /// prior to data being written and may be safely ignored.
32 fn size_hint(&mut self, size: usize);
35 impl<W: Write> Writer for W {
37 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
38 <Self as ::std::io::Write>::write_all(self, buf)
41 fn size_hint(&mut self, _size: usize) { }
44 pub(crate) struct WriterWriteAdaptor<'a, W: Writer + 'a>(pub &'a mut W);
45 impl<'a, W: Writer + 'a> Write for WriterWriteAdaptor<'a, W> {
46 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
49 fn write(&mut self, buf: &[u8]) -> Result<usize, ::std::io::Error> {
50 self.0.write_all(buf)?;
53 fn flush(&mut self) -> Result<(), ::std::io::Error> {
58 struct VecWriter(Vec<u8>);
59 impl Writer for VecWriter {
60 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
61 self.0.extend_from_slice(buf);
64 fn size_hint(&mut self, size: usize) {
65 self.0.reserve_exact(size);
69 /// A trait that various rust-lightning types implement allowing them to be written out to a Writer
71 /// Writes self out to the given Writer
72 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error>;
74 /// Writes self out to a Vec<u8>
75 fn encode(&self) -> Vec<u8> {
76 let mut msg = VecWriter(Vec::new());
77 self.write(&mut msg).unwrap();
81 /// Writes self out to a Vec<u8>
82 fn encode_with_len(&self) -> Vec<u8> {
83 let mut msg = VecWriter(Vec::new());
84 0u16.write(&mut msg).unwrap();
85 self.write(&mut msg).unwrap();
86 let len = msg.0.len();
87 msg.0[..2].copy_from_slice(&byte_utils::be16_to_array(len as u16 - 2));
92 /// A trait that various rust-lightning types implement allowing them to be read in from a Read
97 /// Reads a Self in from the given Read
98 fn read(reader: &mut R) -> Result<Self, DecodeError>;
101 /// A trait that various higher-level rust-lightning types implement allowing them to be read in
102 /// from a Read given some additional set of arguments which is required to deserialize.
103 pub trait ReadableArgs<R, P>
107 /// Reads a Self in from the given Read
108 fn read(reader: &mut R, params: P) -> Result<Self, DecodeError>;
111 pub(crate) struct U48(pub u64);
112 impl Writeable for U48 {
114 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
115 writer.write_all(&be48_to_array(self.0))
118 impl<R: Read> Readable<R> for U48 {
120 fn read(reader: &mut R) -> Result<U48, DecodeError> {
121 let mut buf = [0; 6];
122 reader.read_exact(&mut buf)?;
123 Ok(U48(slice_to_be48(&buf)))
127 macro_rules! impl_writeable_primitive {
128 ($val_type:ty, $meth_write:ident, $len: expr, $meth_read:ident) => {
129 impl Writeable for $val_type {
131 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
132 writer.write_all(&$meth_write(*self))
135 impl<R: Read> Readable<R> for $val_type {
137 fn read(reader: &mut R) -> Result<$val_type, DecodeError> {
138 let mut buf = [0; $len];
139 reader.read_exact(&mut buf)?;
146 impl_writeable_primitive!(u64, be64_to_array, 8, slice_to_be64);
147 impl_writeable_primitive!(u32, be32_to_array, 4, slice_to_be32);
148 impl_writeable_primitive!(u16, be16_to_array, 2, slice_to_be16);
150 impl Writeable for u8 {
152 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
153 writer.write_all(&[*self])
156 impl<R: Read> Readable<R> for u8 {
158 fn read(reader: &mut R) -> Result<u8, DecodeError> {
159 let mut buf = [0; 1];
160 reader.read_exact(&mut buf)?;
165 impl Writeable for bool {
167 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
168 writer.write_all(&[if *self {1} else {0}])
171 impl<R: Read> Readable<R> for bool {
173 fn read(reader: &mut R) -> Result<bool, DecodeError> {
174 let mut buf = [0; 1];
175 reader.read_exact(&mut buf)?;
176 if buf[0] != 0 && buf[0] != 1 {
177 return Err(DecodeError::InvalidValue);
184 macro_rules! impl_array {
186 impl Writeable for [u8; $size]
189 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
194 impl<R: Read> Readable<R> for [u8; $size]
197 fn read(r: &mut R) -> Result<Self, DecodeError> {
198 let mut buf = [0u8; $size];
199 r.read_exact(&mut buf)?;
206 //TODO: performance issue with [u8; size] with impl_array!()
207 impl_array!(3); // for rgb
208 impl_array!(4); // for IPv4
209 impl_array!(10); // for OnionV2
210 impl_array!(16); // for IPv6
211 impl_array!(32); // for channel id & hmac
212 impl_array!(33); // for PublicKey
213 impl_array!(64); // for Signature
214 impl_array!(1300); // for OnionPacket.hop_data
217 impl<K, V> Writeable for HashMap<K, V>
218 where K: Writeable + Eq + Hash,
222 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
223 (self.len() as u16).write(w)?;
224 for (key, value) in self.iter() {
232 impl<R, K, V> Readable<R> for HashMap<K, V>
234 K: Readable<R> + Eq + Hash,
238 fn read(r: &mut R) -> Result<Self, DecodeError> {
239 let len: u16 = Readable::read(r)?;
240 let mut ret = HashMap::with_capacity(len as usize);
242 ret.insert(K::read(r)?, V::read(r)?);
249 impl Writeable for Vec<u8> {
251 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
252 (self.len() as u16).write(w)?;
257 impl<R: Read> Readable<R> for Vec<u8> {
259 fn read(r: &mut R) -> Result<Self, DecodeError> {
260 let len: u16 = Readable::read(r)?;
261 let mut ret = Vec::with_capacity(len as usize);
262 ret.resize(len as usize, 0);
263 r.read_exact(&mut ret)?;
267 impl Writeable for Vec<Signature> {
269 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
270 (self.len() as u16).write(w)?;
271 for e in self.iter() {
278 impl<R: Read> Readable<R> for Vec<Signature> {
280 fn read(r: &mut R) -> Result<Self, DecodeError> {
281 let len: u16 = Readable::read(r)?;
282 let byte_size = (len as usize)
284 .ok_or(DecodeError::BadLengthDescriptor)?;
285 if byte_size > MAX_BUF_SIZE {
286 return Err(DecodeError::BadLengthDescriptor);
288 let mut ret = Vec::with_capacity(len as usize);
289 for _ in 0..len { ret.push(Signature::read(r)?); }
294 impl Writeable for Script {
295 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
296 (self.len() as u16).write(w)?;
297 w.write_all(self.as_bytes())
301 impl<R: Read> Readable<R> for Script {
302 fn read(r: &mut R) -> Result<Self, DecodeError> {
303 let len = <u16 as Readable<R>>::read(r)? as usize;
304 let mut buf = vec![0; len];
305 r.read_exact(&mut buf)?;
306 Ok(Script::from(buf))
310 impl Writeable for PublicKey {
311 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
312 self.serialize().write(w)
316 impl<R: Read> Readable<R> for PublicKey {
317 fn read(r: &mut R) -> Result<Self, DecodeError> {
318 let buf: [u8; 33] = Readable::read(r)?;
319 match PublicKey::from_slice(&buf) {
321 Err(_) => return Err(DecodeError::InvalidValue),
326 impl Writeable for SecretKey {
327 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
328 let mut ser = [0; 32];
329 ser.copy_from_slice(&self[..]);
334 impl<R: Read> Readable<R> for SecretKey {
335 fn read(r: &mut R) -> Result<Self, DecodeError> {
336 let buf: [u8; 32] = Readable::read(r)?;
337 match SecretKey::from_slice(&buf) {
339 Err(_) => return Err(DecodeError::InvalidValue),
344 impl Writeable for Sha256dHash {
345 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
346 w.write_all(&self[..])
350 impl<R: Read> Readable<R> for Sha256dHash {
351 fn read(r: &mut R) -> Result<Self, DecodeError> {
352 use bitcoin_hashes::Hash;
354 let buf: [u8; 32] = Readable::read(r)?;
355 Ok(Sha256dHash::from_slice(&buf[..]).unwrap())
359 impl Writeable for Signature {
360 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
361 self.serialize_compact().write(w)
365 impl<R: Read> Readable<R> for Signature {
366 fn read(r: &mut R) -> Result<Self, DecodeError> {
367 let buf: [u8; 64] = Readable::read(r)?;
368 match Signature::from_compact(&buf) {
370 Err(_) => return Err(DecodeError::InvalidValue),
375 impl Writeable for PaymentPreimage {
376 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
381 impl<R: Read> Readable<R> for PaymentPreimage {
382 fn read(r: &mut R) -> Result<Self, DecodeError> {
383 let buf: [u8; 32] = Readable::read(r)?;
384 Ok(PaymentPreimage(buf))
388 impl Writeable for PaymentHash {
389 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
394 impl<R: Read> Readable<R> for PaymentHash {
395 fn read(r: &mut R) -> Result<Self, DecodeError> {
396 let buf: [u8; 32] = Readable::read(r)?;
401 impl<T: Writeable> Writeable for Option<T> {
402 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
404 None => 0u8.write(w)?,
414 impl<R, T> Readable<R> for Option<T>
418 fn read(r: &mut R) -> Result<Self, DecodeError> {
419 match <u8 as Readable<R>>::read(r)? {
421 1 => Ok(Some(Readable::read(r)?)),
422 _ => return Err(DecodeError::InvalidValue),
427 impl Writeable for OutPoint {
428 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
435 impl<R: Read> Readable<R> for OutPoint {
436 fn read(r: &mut R) -> Result<Self, DecodeError> {
437 let txid = Readable::read(r)?;
438 let vout = Readable::read(r)?;