Merge branch 'ssz-ints' into validate_block

This commit is contained in:
Paul Hauner 2018-09-22 12:16:35 +10:00
commit 2559c5458f
No known key found for this signature in database
GPG Key ID: 303E4494BB28068C
4 changed files with 59 additions and 11 deletions

View File

@ -13,7 +13,7 @@ bytes = ""
crypto-mac = "^0.6.2"
clap = "2.32.0"
dirs = "1.0.3"
ethereum-types = ""
ethereum-types = "0.4.0"
futures = "0.1.23"
network-libp2p = { path = "network-libp2p" }
rand = "0.3"

View File

@ -1,7 +1,10 @@
use super::ethereum_types::H256;
use super::{
DecodeError,
Decodable,
};
macro_rules! impl_decodable_for_uint {
($type: ident, $bit_size: expr) => {
impl Decodable for $type {
@ -33,14 +36,58 @@ impl_decodable_for_uint!(u32, 32);
impl_decodable_for_uint!(u64, 64);
impl_decodable_for_uint!(usize, 64);
impl Decodable for H256 {
fn ssz_decode(bytes: &[u8], index: usize)
-> Result<(Self, usize), DecodeError>
{
if bytes.len() < 32 {
return Err(DecodeError::TooShort)
}
else if bytes.len() - 32 < index {
return Err(DecodeError::TooShort)
}
else {
return Ok((H256::from(&bytes[index..(index + 32)]),
index + 32));
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use super::super::{
DecodeError,
decode_ssz,
};
#[test]
fn test_ssz_decode_h256() {
/*
* Input is exact length
*/
let input = vec![42_u8; 32];
let (decoded, i) = H256::ssz_decode(&input, 0).unwrap();
assert_eq!(decoded.to_vec(), input);
assert_eq!(i, 32);
/*
* Input is too long
*/
let mut input = vec![42_u8; 32];
input.push(12);
let (decoded, i) = H256::ssz_decode(&input, 0).unwrap();
assert_eq!(decoded.to_vec()[..], input[0..32]);
assert_eq!(i, 32);
/*
* Input is too short
*/
let input = vec![42_u8; 31];
let res = H256::ssz_decode(&input, 0);
assert_eq!(res, Err(DecodeError::TooShort));
}
#[test]
fn test_ssz_decode_u16() {
let ssz = vec![0, 0];

View File

@ -4,7 +4,7 @@ use super::{
Encodable,
SszStream
};
use super::ethereum_types::{ H256, U256 };
use super::ethereum_types::H256;
use self::bytes::{ BytesMut, BufMut };
/*
@ -49,15 +49,7 @@ impl_encodable_for_uint!(usize, 64);
impl Encodable for H256 {
fn ssz_append(&self, s: &mut SszStream) {
s.append_encoded_val(&self.to_vec());
}
}
impl Encodable for U256 {
fn ssz_append(&self, s: &mut SszStream) {
let mut a = [0; 32];
self.to_big_endian(&mut a);
s.append_encoded_val(&a.to_vec());
s.append_encoded_raw(&self.to_vec());
}
}
@ -66,6 +58,14 @@ impl Encodable for U256 {
mod tests {
use super::*;
#[test]
fn test_ssz_encode_h256() {
let h = H256::zero();
let mut ssz = SszStream::new();
ssz.append(&h);
assert_eq!(ssz.drain(), vec![0; 32]);
}
#[test]
fn test_ssz_encode_u8() {
let x: u8 = 0;

View File

@ -20,6 +20,7 @@ pub use decode::{
Decodable,
DecodeError,
decode_ssz,
decode_ssz_list,
};
pub use encode::{
Encodable,