1 use std::result::Result;
3 use std::collections::HashMap;
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;
13 use util::byte_utils::{be64_to_array, be32_to_array, be16_to_array, slice_to_be16, slice_to_be32, slice_to_be64};
15 const MAX_BUF_SIZE: usize = 64 * 1024;
17 /// A trait that is similar to std::io::Write but has one extra function which can be used to size
18 /// buffers being written into.
19 /// An impl is provided for any type that also impls std::io::Write which simply ignores size
22 /// Writes the given buf out. See std::io::Write::write_all for more
23 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error>;
24 /// Hints that data of the given size is about the be written. This may not always be called
25 /// prior to data being written and may be safely ignored.
26 fn size_hint(&mut self, size: usize);
29 impl<W: ::std::io::Write> Writer for W {
31 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
32 <Self as ::std::io::Write>::write_all(self, buf)
35 fn size_hint(&mut self, _size: usize) { }
38 /// A trait that various rust-lightning types implement allowing them to be written out to a Writer
40 /// Writes self out to the given Writer
41 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error>;
44 /// A trait that various rust-lightning types implement allowing them to be read in from a Read
49 /// Reads a Self in from the given Read
50 fn read(reader: &mut R) -> Result<Self, DecodeError>;
53 macro_rules! impl_writeable_primitive {
54 ($val_type:ty, $meth_write:ident, $len: expr, $meth_read:ident) => {
55 impl Writeable for $val_type {
57 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
58 writer.write_all(&$meth_write(*self))
61 impl<R: Read> Readable<R> for $val_type {
63 fn read(reader: &mut R) -> Result<$val_type, DecodeError> {
64 let mut buf = [0; $len];
65 reader.read_exact(&mut buf)?;
72 impl_writeable_primitive!(u64, be64_to_array, 8, slice_to_be64);
73 impl_writeable_primitive!(u32, be32_to_array, 4, slice_to_be32);
74 impl_writeable_primitive!(u16, be16_to_array, 2, slice_to_be16);
76 impl Writeable for u8 {
78 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
79 writer.write_all(&[*self])
82 impl<R: Read> Readable<R> for u8 {
84 fn read(reader: &mut R) -> Result<u8, DecodeError> {
86 reader.read_exact(&mut buf)?;
91 impl Writeable for bool {
93 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
94 writer.write_all(&[if *self {1} else {0}])
97 impl<R: Read> Readable<R> for bool {
99 fn read(reader: &mut R) -> Result<bool, DecodeError> {
100 let mut buf = [0; 1];
101 reader.read_exact(&mut buf)?;
102 if buf[0] != 0 && buf[0] != 1 {
103 return Err(DecodeError::InvalidValue);
110 macro_rules! impl_array {
112 impl Writeable for [u8; $size]
115 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
120 impl<R: Read> Readable<R> for [u8; $size]
123 fn read(r: &mut R) -> Result<Self, DecodeError> {
124 let mut buf = [0u8; $size];
125 r.read_exact(&mut buf)?;
132 //TODO: performance issue with [u8; size] with impl_array!()
133 impl_array!(32); // for channel id & hmac
134 impl_array!(33); // for PublicKey
135 impl_array!(64); // for Signature
136 impl_array!(1300); // for OnionPacket.hop_data
139 impl<K, V> Writeable for HashMap<K, V>
140 where K: Writeable + Eq + Hash,
144 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
145 (self.len() as u16).write(w)?;
146 for (key, value) in self.iter() {
154 impl<R, K, V> Readable<R> for HashMap<K, V>
156 K: Readable<R> + Eq + Hash,
160 fn read(r: &mut R) -> Result<Self, DecodeError> {
161 let len: u16 = Readable::read(r)?;
162 let mut ret = HashMap::with_capacity(len as usize);
164 ret.insert(K::read(r)?, V::read(r)?);
171 impl Writeable for Vec<u8> {
173 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
174 (self.len() as u16).write(w)?;
179 impl<R: Read> Readable<R> for Vec<u8> {
181 fn read(r: &mut R) -> Result<Self, DecodeError> {
182 let len: u16 = Readable::read(r)?;
183 let mut ret = Vec::with_capacity(len as usize);
184 ret.resize(len as usize, 0);
185 r.read_exact(&mut ret)?;
189 impl Writeable for Vec<Signature> {
191 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
192 (self.len() as u16).write(w)?;
193 for e in self.iter() {
200 impl<R: Read> Readable<R> for Vec<Signature> {
202 fn read(r: &mut R) -> Result<Self, DecodeError> {
203 let len: u16 = Readable::read(r)?;
204 let byte_size = (len as usize)
206 .ok_or(DecodeError::BadLengthDescriptor)?;
207 if byte_size > MAX_BUF_SIZE {
208 return Err(DecodeError::BadLengthDescriptor);
210 let mut ret = Vec::with_capacity(len as usize);
211 for _ in 0..len { ret.push(Signature::read(r)?); }
216 impl Writeable for Script {
217 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
218 (self.len() as u16).write(w)?;
219 w.write_all(self.as_bytes())
223 impl<R: Read> Readable<R> for Script {
224 fn read(r: &mut R) -> Result<Self, DecodeError> {
225 let len = <u16 as Readable<R>>::read(r)? as usize;
226 let mut buf = vec![0; len];
227 r.read_exact(&mut buf)?;
228 Ok(Script::from(buf))
232 impl Writeable for Option<Script> {
233 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
234 if let &Some(ref script) = self {
241 impl<R: Read> Readable<R> for Option<Script> {
242 fn read(r: &mut R) -> Result<Self, DecodeError> {
243 match <u16 as Readable<R>>::read(r) {
245 let mut buf = vec![0; len as usize];
246 r.read_exact(&mut buf)?;
247 Ok(Some(Script::from(buf)))
249 Err(DecodeError::ShortRead) => Ok(None),
255 impl Writeable for PublicKey {
256 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
257 self.serialize().write(w)
261 impl<R: Read> Readable<R> for PublicKey {
262 fn read(r: &mut R) -> Result<Self, DecodeError> {
263 let buf: [u8; 33] = Readable::read(r)?;
264 match PublicKey::from_slice(&Secp256k1::without_caps(), &buf) {
266 Err(_) => return Err(DecodeError::BadPublicKey),
271 impl Writeable for Sha256dHash {
272 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
273 self.as_bytes().write(w)
277 impl<R: Read> Readable<R> for Sha256dHash {
278 fn read(r: &mut R) -> Result<Self, DecodeError> {
279 let buf: [u8; 32] = Readable::read(r)?;
280 Ok(From::from(&buf[..]))
284 impl Writeable for Signature {
285 fn write<W: Writer>(&self, w: &mut W) -> Result<(), ::std::io::Error> {
286 self.serialize_compact(&Secp256k1::without_caps()).write(w)
290 impl<R: Read> Readable<R> for Signature {
291 fn read(r: &mut R) -> Result<Self, DecodeError> {
292 let buf: [u8; 64] = Readable::read(r)?;
293 match Signature::from_compact(&Secp256k1::without_caps(), &buf) {
295 Err(_) => return Err(DecodeError::BadSignature),