Drop MsgEncodable in favor of default fns on Writeable
[rust-lightning] / src / util / ser.rs
1 use std::result::Result;
2 use std::io::Read;
3 use std::collections::HashMap;
4 use std::hash::Hash;
5
6 use secp256k1::{Secp256k1, Signature};
7 use secp256k1::key::PublicKey;
8 use bitcoin::util::hash::Sha256dHash;
9 use bitcoin::blockdata::script::Script;
10 use std::marker::Sized;
11 use ln::msgs::DecodeError;
12 use util::byte_utils;
13
14 use util::byte_utils::{be64_to_array, be32_to_array, be16_to_array, slice_to_be16, slice_to_be32, slice_to_be64};
15
16 const MAX_BUF_SIZE: usize = 64 * 1024;
17
18 /// A trait that is similar to std::io::Write but has one extra function which can be used to size
19 /// buffers being written into.
20 /// An impl is provided for any type that also impls std::io::Write which simply ignores size
21 /// hints.
22 pub trait Writer {
23         /// Writes the given buf out. See std::io::Write::write_all for more
24         fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error>;
25         /// Hints that data of the given size is about the be written. This may not always be called
26         /// prior to data being written and may be safely ignored.
27         fn size_hint(&mut self, size: usize);
28 }
29
30 impl<W: ::std::io::Write> Writer for W {
31         #[inline]
32         fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
33                 <Self as ::std::io::Write>::write_all(self, buf)
34         }
35         #[inline]
36         fn size_hint(&mut self, _size: usize) { }
37 }
38
39 struct VecWriter(Vec<u8>);
40 impl Writer for VecWriter {
41         fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
42                 self.0.extend_from_slice(buf);
43                 Ok(())
44         }
45         fn size_hint(&mut self, size: usize) {
46                 self.0.reserve_exact(size);
47         }
48 }
49
50 /// A trait that various rust-lightning types implement allowing them to be written out to a Writer
51 pub trait Writeable {
52         /// Writes self out to the given Writer
53         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error>;
54
55         /// Writes self out to a Vec<u8>
56         fn encode(&self) -> Vec<u8> {
57                 let mut msg = VecWriter(Vec::new());
58                 self.write(&mut msg).unwrap();
59                 msg.0
60         }
61
62         /// Writes self out to a Vec<u8>
63         fn encode_with_len(&self) -> Vec<u8> {
64                 let mut msg = VecWriter(Vec::new());
65                 0u16.write(&mut msg).unwrap();
66                 self.write(&mut msg).unwrap();
67                 let len = msg.0.len();
68                 msg.0[..2].copy_from_slice(&byte_utils::be16_to_array(len as u16 - 2));
69                 msg.0
70         }
71 }
72
73 /// A trait that various rust-lightning types implement allowing them to be read in from a Read
74 pub trait Readable<R>
75         where Self: Sized,
76               R: Read
77 {
78         /// Reads a Self in from the given Read
79         fn read(reader: &mut R) -> Result<Self, DecodeError>;
80 }
81
82 macro_rules! impl_writeable_primitive {
83         ($val_type:ty, $meth_write:ident, $len: expr, $meth_read:ident) => {
84                 impl Writeable for $val_type {
85                         #[inline]
86                         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
87                                 writer.write_all(&$meth_write(*self))
88                         }
89                 }
90                 impl<R: Read> Readable<R> for $val_type {
91                         #[inline]
92                         fn read(reader: &mut R) -> Result<$val_type, DecodeError> {
93                                 let mut buf = [0; $len];
94                                 reader.read_exact(&mut buf)?;
95                                 Ok($meth_read(&buf))
96                         }
97                 }
98         }
99 }
100
101 impl_writeable_primitive!(u64, be64_to_array, 8, slice_to_be64);
102 impl_writeable_primitive!(u32, be32_to_array, 4, slice_to_be32);
103 impl_writeable_primitive!(u16, be16_to_array, 2, slice_to_be16);
104
105 impl Writeable for u8 {
106         #[inline]
107         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
108                 writer.write_all(&[*self])
109         }
110 }
111 impl<R: Read> Readable<R> for u8 {
112         #[inline]
113         fn read(reader: &mut R) -> Result<u8, DecodeError> {
114                 let mut buf = [0; 1];
115                 reader.read_exact(&mut buf)?;
116                 Ok(buf[0])
117         }
118 }
119
120 impl Writeable for bool {
121         #[inline]
122         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
123                 writer.write_all(&[if *self {1} else {0}])
124         }
125 }
126 impl<R: Read> Readable<R> for bool {
127         #[inline]
128         fn read(reader: &mut R) -> Result<bool, DecodeError> {
129                 let mut buf = [0; 1];
130                 reader.read_exact(&mut buf)?;
131                 if buf[0] != 0 && buf[0] != 1 {
132                         return Err(DecodeError::InvalidValue);
133                 }
134                 Ok(buf[0] == 1)
135         }
136 }
137
138 // u8 arrays
139 macro_rules! impl_array {
140         ( $size:expr ) => (
141                 impl Writeable for [u8; $size]
142                 {
143                         #[inline]
144                         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
145                                 w.write_all(self)
146                         }
147                 }
148
149                 impl<R: Read> Readable<R> for [u8; $size]
150                 {
151                         #[inline]
152                         fn read(r: &mut R) -> Result<Self, DecodeError> {
153                                 let mut buf = [0u8; $size];
154                                 r.read_exact(&mut buf)?;
155                                 Ok(buf)
156                         }
157                 }
158         );
159 }
160
161 //TODO: performance issue with [u8; size] with impl_array!()
162 impl_array!(32); // for channel id & hmac
163 impl_array!(33); // for PublicKey
164 impl_array!(64); // for Signature
165 impl_array!(1300); // for OnionPacket.hop_data
166
167 // HashMap
168 impl<K, V> Writeable for HashMap<K, V>
169         where K: Writeable + Eq + Hash,
170               V: Writeable
171 {
172         #[inline]
173         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
174         (self.len() as u16).write(w)?;
175                 for (key, value) in self.iter() {
176                         key.write(w)?;
177                         value.write(w)?;
178                 }
179                 Ok(())
180         }
181 }
182
183 impl<R, K, V> Readable<R> for HashMap<K, V>
184         where R: Read,
185               K: Readable<R> + Eq + Hash,
186               V: Readable<R>
187 {
188         #[inline]
189         fn read(r: &mut R) -> Result<Self, DecodeError> {
190                 let len: u16 = Readable::read(r)?;
191                 let mut ret = HashMap::with_capacity(len as usize);
192                 for _ in 0..len {
193                         ret.insert(K::read(r)?, V::read(r)?);
194                 }
195                 Ok(ret)
196         }
197 }
198
199 // Vectors
200 impl Writeable for Vec<u8> {
201         #[inline]
202         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
203                 (self.len() as u16).write(w)?;
204                 w.write_all(&self)
205         }
206 }
207
208 impl<R: Read> Readable<R> for Vec<u8> {
209         #[inline]
210         fn read(r: &mut R) -> Result<Self, DecodeError> {
211                 let len: u16 = Readable::read(r)?;
212                 let mut ret = Vec::with_capacity(len as usize);
213                 ret.resize(len as usize, 0);
214                 r.read_exact(&mut ret)?;
215                 Ok(ret)
216         }
217 }
218 impl Writeable for Vec<Signature> {
219         #[inline]
220         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
221                 (self.len() as u16).write(w)?;
222                 for e in self.iter() {
223                         e.write(w)?;
224                 }
225                 Ok(())
226         }
227 }
228
229 impl<R: Read> Readable<R> for Vec<Signature> {
230         #[inline]
231         fn read(r: &mut R) -> Result<Self, DecodeError> {
232                 let len: u16 = Readable::read(r)?;
233                 let byte_size = (len as usize)
234                                 .checked_mul(33)
235                                 .ok_or(DecodeError::BadLengthDescriptor)?;
236                 if byte_size > MAX_BUF_SIZE {
237                         return Err(DecodeError::BadLengthDescriptor);
238                 }
239                 let mut ret = Vec::with_capacity(len as usize);
240                 for _ in 0..len { ret.push(Signature::read(r)?); }
241                 Ok(ret)
242         }
243 }
244
245 impl Writeable for Script {
246         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
247                 (self.len() as u16).write(w)?;
248                 w.write_all(self.as_bytes())
249         }
250 }
251
252 impl<R: Read> Readable<R> for Script {
253         fn read(r: &mut R) -> Result<Self, DecodeError> {
254                 let len = <u16 as Readable<R>>::read(r)? as usize;
255                 let mut buf = vec![0; len];
256                 r.read_exact(&mut buf)?;
257                 Ok(Script::from(buf))
258         }
259 }
260
261 impl Writeable for Option<Script> {
262         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
263                 if let &Some(ref script) = self {
264                         script.write(w)?;
265                 }
266                 Ok(())
267         }
268 }
269
270 impl<R: Read> Readable<R> for Option<Script> {
271         fn read(r: &mut R) -> Result<Self, DecodeError> {
272                 match <u16 as Readable<R>>::read(r) {
273                         Ok(len) => {
274                                 let mut buf = vec![0; len as usize];
275                                 r.read_exact(&mut buf)?;
276                                 Ok(Some(Script::from(buf)))
277                         },
278                         Err(DecodeError::ShortRead) => Ok(None),
279                         Err(e) => Err(e)
280                 }
281         }
282 }
283
284 impl Writeable for PublicKey {
285         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
286                 self.serialize().write(w)
287         }
288 }
289
290 impl<R: Read> Readable<R> for PublicKey {
291         fn read(r: &mut R) -> Result<Self, DecodeError> {
292                 let buf: [u8; 33] = Readable::read(r)?;
293                 match PublicKey::from_slice(&Secp256k1::without_caps(), &buf) {
294                         Ok(key) => Ok(key),
295                         Err(_) => return Err(DecodeError::BadPublicKey),
296                 }
297         }
298 }
299
300 impl Writeable for Sha256dHash {
301         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
302                 self.as_bytes().write(w)
303         }
304 }
305
306 impl<R: Read> Readable<R> for Sha256dHash {
307         fn read(r: &mut R) -> Result<Self, DecodeError> {
308                 let buf: [u8; 32] = Readable::read(r)?;
309                 Ok(From::from(&buf[..]))
310         }
311 }
312
313 impl Writeable for Signature {
314         fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
315                 self.serialize_compact(&Secp256k1::without_caps()).write(w)
316         }
317 }
318
319 impl<R: Read> Readable<R> for Signature {
320         fn read(r: &mut R) -> Result<Self, DecodeError> {
321                 let buf: [u8; 64] = Readable::read(r)?;
322                 match Signature::from_compact(&Secp256k1::without_caps(), &buf) {
323                         Ok(sig) => Ok(sig),
324                         Err(_) => return Err(DecodeError::BadSignature),
325                 }
326         }
327 }