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