Skip to content

Commit 455f23f

Browse files
committed
Implement writers/readers
issue #62
1 parent 03c6f84 commit 455f23f

File tree

1 file changed

+373
-0
lines changed

1 file changed

+373
-0
lines changed

src/util/ser.rs

Lines changed: 373 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,373 @@
1+
use std::result::Result;
2+
use std::io::{self, Read, Write};
3+
use std::fmt;
4+
use std::collections::HashMap;
5+
use std::hash::Hash;
6+
use std::mem;
7+
8+
use secp256k1::Secp256k1;
9+
use secp256k1::key::PublicKey;
10+
use bitcoin::blockdata::script::Script;
11+
use bitcoin::util::hash::Sha256dHash;
12+
use std::marker::Sized;
13+
14+
pub const MAX_VEC_SIZE: usize = 32 * 1024 * 1024;
15+
16+
pub enum Error {
17+
CorruptedData,
18+
BadPublicKey,
19+
IoError(io::Error),
20+
InvalidLength,
21+
InvalidValue,
22+
}
23+
24+
impl fmt::Debug for Error {
25+
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
26+
match *self {
27+
Error::CorruptedData => f.write_str("corrupted data"),
28+
Error::BadPublicKey => f.write_str("Bad public key"),
29+
Error::IoError(ref e) => write!(f, "{}", e),
30+
Error::InvalidLength => f.write_str("Invalid length"),
31+
Error::InvalidValue => f.write_str("Invalid value"),
32+
}
33+
}
34+
}
35+
36+
impl From<io::Error> for Error {
37+
fn from(e: io::Error) -> Self {
38+
Error::IoError(e)
39+
}
40+
}
41+
42+
pub struct Writer<W> { writer: W }
43+
pub struct Reader<R> { reader: R }
44+
45+
pub trait Writeable<W: Write> {
46+
fn write(&self, writer: &mut Writer<W>) -> Result<(), Error>;
47+
}
48+
49+
pub trait Readable<R>
50+
where Self: Sized,
51+
R: Read
52+
{
53+
fn read(reader: &mut Reader<R>) -> Result<Self, Error>;
54+
}
55+
56+
macro_rules! writer_fn {
57+
($name:ident, $val_type:ty, $convfn:ident) => {
58+
#[inline]
59+
fn $name(&mut self, v: $val_type) -> Result<(), Error> {
60+
Ok(self.writer.write_all(&$convfn(v))?)
61+
}
62+
}
63+
}
64+
65+
macro_rules! reader_fn {
66+
($name:ident, $val_type:ty, $val_size: expr, $convfn:ident) => {
67+
#[inline]
68+
fn $name(&mut self) -> Result<$val_type, Error> {
69+
let mut buf = [0; $val_size];
70+
self.reader.read_exact(&mut buf)?;
71+
Ok($convfn(&buf))
72+
}
73+
}
74+
}
75+
76+
use util::byte_utils::{be64_to_array, be32_to_array, be16_to_array, slice_to_be16, slice_to_be32, slice_to_be64};
77+
78+
impl<W: Write> Writer<W> {
79+
pub fn new(writer: W) -> Writer<W> {
80+
return Writer { writer }
81+
}
82+
pub fn into_inner(self) -> W { self.writer }
83+
pub fn get_ref(&self) -> &W { &self.writer }
84+
writer_fn!(write_u64, u64, be64_to_array);
85+
writer_fn!(write_u32, u32, be32_to_array);
86+
writer_fn!(write_u16, u16, be16_to_array);
87+
fn write_u8(&mut self, v: u8) -> Result<(), Error> {
88+
Ok(self.writer.write_all(&[v])?)
89+
}
90+
fn write_bool(&mut self, v: bool) -> Result<(), Error> {
91+
Ok(self.writer.write_all(&[if v {1} else {0}])?)
92+
}
93+
}
94+
95+
impl<R: Read> Reader<R> {
96+
pub fn new(reader: R) -> Reader<R> {
97+
return Reader { reader }
98+
}
99+
pub fn into_inner(self) -> R { self.reader }
100+
pub fn get_ref(&self) -> &R { &self.reader }
101+
102+
reader_fn!(read_u16, u16, 2, slice_to_be16);
103+
reader_fn!(read_u32, u32, 4, slice_to_be32);
104+
reader_fn!(read_u64, u64, 8, slice_to_be64);
105+
106+
fn read_u8(&mut self) -> Result<u8, Error> {
107+
let mut buf = [0; 1];
108+
self.reader.read_exact(&mut buf)?;
109+
Ok(buf[0])
110+
}
111+
fn read_bool(&mut self) -> Result<bool, Error> {
112+
let mut buf = [0; 1];
113+
self.reader.read_exact(&mut buf)?;
114+
if buf[0] != 0 && buf[0] != 1 {
115+
return Err(Error::InvalidValue);
116+
}
117+
Ok(buf[0] == 1)
118+
}
119+
fn read_fixed_size(&mut self, sz: usize) -> Result<Vec<u8>, Error> {
120+
let mut buf = vec![0; sz];
121+
self.reader.read_exact(&mut buf)?;
122+
Ok(buf)
123+
}
124+
}
125+
126+
macro_rules! impl_writeable_primitive {
127+
($val_type:ty, $meth_write:ident, $meth_read:ident) => {
128+
impl<W:Write> Writeable<W> for $val_type {
129+
#[inline]
130+
fn write(&self, writer: &mut Writer<W>) -> Result<(), Error> {
131+
writer.$meth_write(*self)
132+
}
133+
}
134+
impl<R:Read> Readable<R> for $val_type {
135+
#[inline]
136+
fn read(reader: &mut Reader<R>) -> Result<$val_type, Error> {
137+
reader.$meth_read()
138+
}
139+
}
140+
}
141+
}
142+
143+
impl_writeable_primitive!(u64, write_u64, read_u64);
144+
impl_writeable_primitive!(u32, write_u32, read_u32);
145+
impl_writeable_primitive!(u16, write_u16, read_u16);
146+
impl_writeable_primitive!(u8, write_u8, read_u8);
147+
impl_writeable_primitive!(bool, write_bool, read_bool);
148+
149+
// Arrays
150+
macro_rules! impl_array {
151+
( $size:expr ) => (
152+
impl<W, T> Writeable<W> for [T; $size]
153+
where W: Write,
154+
T: Writeable<W>,
155+
{
156+
#[inline]
157+
fn write(&self, w: &mut Writer<W>) -> Result<(), Error> {
158+
for i in self.iter() { i.write(w)?; }
159+
Ok(())
160+
}
161+
}
162+
163+
impl<R, T> Readable<R> for [T; $size]
164+
where R: Read,
165+
T: Readable<R> + Copy,
166+
{
167+
#[inline]
168+
fn read(r: &mut Reader<R>) -> Result<[T; $size], Error> {
169+
let mut ret = [T::read(r)?; $size];
170+
for item in ret.iter_mut().take($size).skip(1) { *item = T::read(r)?; }
171+
Ok(ret)
172+
}
173+
}
174+
);
175+
}
176+
177+
impl_array!(32);
178+
impl_array!(33);
179+
180+
// Tuples
181+
macro_rules! tuple_encode {
182+
($($x:ident),*) => (
183+
impl<W: Write, $($x: Writeable<W>),*> Writeable<W> for ($($x),*) {
184+
#[inline]
185+
#[allow(non_snake_case)]
186+
fn write(&self, w: &mut Writer<W>) -> Result<(), Error> {
187+
let &($(ref $x),*) = self;
188+
$( $x.write(w)?; )*
189+
Ok(())
190+
}
191+
}
192+
impl<R: Read, $($x: Readable<R>),*> Readable<R> for ($($x),*) {
193+
#[inline]
194+
#[allow(non_snake_case)]
195+
fn read(r: &mut Reader<R>) -> Result<($($x),*), Error> {
196+
Ok(($({let $x = $x::read(r)?; $x }),*))
197+
}
198+
}
199+
);
200+
}
201+
202+
tuple_encode!(T0, T1);
203+
tuple_encode!(T0, T1, T2, T3);
204+
tuple_encode!(T0, T1, T2, T3, T4, T5);
205+
tuple_encode!(T0, T1, T2, T3, T4, T5, T6, T7);
206+
207+
208+
// References
209+
impl<W: Write, T: Writeable<W>> Writeable<W> for Box<T> {
210+
#[inline]
211+
fn write(&self, w: &mut Writer<W>) -> Result<(), Error> { (**self).write(w) }
212+
}
213+
214+
impl<R: Read, T: Readable<R>> Readable<R> for Box<T> {
215+
#[inline]
216+
fn read(r: &mut Reader<R>) -> Result<Box<T>, Error> {
217+
Ok(Box::new(<T as Readable<R>>::read(r)?))
218+
}
219+
}
220+
221+
// HashMap
222+
impl<W, K, V> Writeable<W> for HashMap<K, V>
223+
where W: Write,
224+
K: Writeable<W> + Eq + Hash,
225+
V: Writeable<W>
226+
{
227+
#[inline]
228+
fn write(&self, w: &mut Writer<W>) -> Result<(), Error> {
229+
(self.len() as u16).write(w)?;
230+
for (key, value) in self.iter() {
231+
key.write(w)?;
232+
value.write(w)?;
233+
}
234+
Ok(())
235+
}
236+
}
237+
238+
impl<R, K, V> Readable<R> for HashMap<K, V>
239+
where R: Read,
240+
K: Readable<R> + Eq + Hash,
241+
V: Readable<R>
242+
{
243+
#[inline]
244+
fn read(r: &mut Reader<R>) -> Result<HashMap<K, V>, Error> {
245+
let len: u16 = Readable::read(r)?;
246+
let mut ret = HashMap::with_capacity(len as usize);
247+
for _ in 0..len {
248+
ret.insert(K::read(r)?, V::read(r)?);
249+
}
250+
Ok(ret)
251+
}
252+
}
253+
254+
impl<W: Write, T: Writeable<W>> Writeable<W> for [T] {
255+
#[inline]
256+
fn write(&self, w: &mut Writer<W>) -> Result<(), Error> {
257+
(self.len() as u16).write(w)?;
258+
for c in self.iter() { c.write(w)?; }
259+
Ok(())
260+
}
261+
}
262+
263+
// Vectors
264+
impl<W: Write, T: Writeable<W>> Writeable<W> for Vec<T> {
265+
#[inline]
266+
fn write(&self, w: &mut Writer<W>) -> Result<(), Error> {
267+
(&self[..]).write(w)
268+
}
269+
}
270+
271+
impl<R: Read, T: Readable<R>> Readable<R> for Vec<T> {
272+
#[inline]
273+
fn read(r: &mut Reader<R>) -> Result<Vec<T>, Error> {
274+
let len: u16 = Readable::read(r)?;
275+
let byte_size = (len as usize)
276+
.checked_mul(mem::size_of::<T>())
277+
.ok_or(Error::InvalidLength)?;
278+
if byte_size > MAX_VEC_SIZE {
279+
return Err(Error::InvalidLength);
280+
}
281+
let mut ret = Vec::with_capacity(len as usize);
282+
for _ in 0..len { ret.push(T::read(r)?); }
283+
Ok(ret)
284+
}
285+
}
286+
287+
impl<W: Write, T: Writeable<W>> Writeable<W> for Option<T> {
288+
#[inline]
289+
fn write(&self, w: &mut Writer<W>) -> Result<(), Error> {
290+
match self {
291+
Some(data) => {
292+
true.write(w)?;
293+
data.write(w)?;
294+
}
295+
None => { false.write(w)?; }
296+
}
297+
Ok(())
298+
}
299+
}
300+
301+
impl<R: Read, T:Readable<R>> Readable<R> for Option<T> {
302+
#[inline]
303+
fn read(r: &mut Reader<R>) -> Result<Option<T>, Error> {
304+
let f: bool = Readable::read(r)?;
305+
Ok(if f {
306+
Some(Readable::read(r)?)
307+
} else {
308+
None
309+
})
310+
}
311+
}
312+
313+
impl<W: Write> Writeable<W> for PublicKey {
314+
fn write(&self, w: &mut Writer<W>) -> Result<(), Error> {
315+
self.serialize().write(w)
316+
}
317+
}
318+
319+
impl<R: Read> Readable<R> for PublicKey {
320+
fn read(r: &mut Reader<R>) -> Result<PublicKey, Error> {
321+
let buf: [u8; 33] = Readable::read(r)?;
322+
match PublicKey::from_slice(&Secp256k1::without_caps(), &buf) {
323+
Ok(key) => Ok(key),
324+
Err(_) => return Err(Error::BadPublicKey),
325+
}
326+
}
327+
}
328+
329+
impl<W: Write> Writeable<W> for Sha256dHash {
330+
fn write(&self, w: &mut Writer<W>) -> Result<(), Error> {
331+
self.0.write(w);
332+
}
333+
}
334+
335+
impl<R: Read> Readable<R> for Sha256dHash {
336+
fn read(r: &mut Reader<R>) -> Result<Sha256dHash, Error> {
337+
let buf: [u8; 32] = Readable::read(r)?;
338+
Ok(buf)
339+
}
340+
}
341+
342+
impl<W: Write> Writeable<W> for Script {
343+
fn write(&self, w: &mut Writer<W>) -> Result<(), Error> {
344+
self[..].write(w)
345+
}
346+
}
347+
348+
impl<R: Read> Readable<R> for Script {
349+
fn read(r: &mut Reader<R>) -> Result<Script, Error> {
350+
let sz: u16 = Readable::read(r)?;
351+
let v = r.read_fixed_size(sz as usize)?;
352+
Ok(Script::from(v))
353+
}
354+
}
355+
356+
macro_rules! impl_writeable {
357+
($st:ident, {$($field:ident),*}) => {
358+
impl<W: Write> Writeable<W> for $st {
359+
fn write(&self, w: &mut Writer<W>) -> Result<(), Error> {
360+
$( self.$field.write(w)?; )*
361+
Ok(())
362+
}
363+
}
364+
365+
impl<R: Read> Readable<R> for $st {
366+
fn read(r: &mut Reader<R>) -> Result<Self, Error> {
367+
Ok(Self {
368+
$($field: Readable::read(r)?),*
369+
})
370+
}
371+
}
372+
}
373+
}

0 commit comments

Comments
 (0)