2019-05-27 19:46:14 +00:00
|
|
|
from eth2spec.utils.ssz.ssz_impl import hash_tree_root
|
2019-06-01 00:22:14 +00:00
|
|
|
from eth2spec.utils.ssz.ssz_typing import (
|
|
|
|
is_uint_type, is_bool_type, is_list_type,
|
|
|
|
is_vector_type, is_bytes_type, is_bytesn_type, is_container_type,
|
|
|
|
read_vector_elem_type, read_list_elem_type,
|
|
|
|
Vector, BytesN
|
|
|
|
)
|
2019-04-07 13:36:05 +00:00
|
|
|
|
|
|
|
|
2019-05-27 19:46:14 +00:00
|
|
|
def decode(data, typ):
|
2019-05-27 20:19:18 +00:00
|
|
|
if is_uint_type(typ):
|
2019-05-27 19:46:14 +00:00
|
|
|
return data
|
|
|
|
elif is_bool_type(typ):
|
|
|
|
assert data in (True, False)
|
|
|
|
return data
|
2019-05-27 20:19:18 +00:00
|
|
|
elif is_list_type(typ):
|
|
|
|
elem_typ = read_list_elem_type(typ)
|
2019-05-27 19:46:14 +00:00
|
|
|
return [decode(element, elem_typ) for element in data]
|
2019-05-27 20:19:18 +00:00
|
|
|
elif is_vector_type(typ):
|
|
|
|
elem_typ = read_vector_elem_type(typ)
|
2019-05-27 19:46:14 +00:00
|
|
|
return Vector(decode(element, elem_typ) for element in data)
|
2019-05-27 20:19:18 +00:00
|
|
|
elif is_bytes_type(typ):
|
2019-05-27 19:46:14 +00:00
|
|
|
return bytes.fromhex(data[2:])
|
2019-05-27 20:19:18 +00:00
|
|
|
elif is_bytesn_type(typ):
|
2019-05-27 19:46:14 +00:00
|
|
|
return BytesN(bytes.fromhex(data[2:]))
|
2019-05-27 20:19:18 +00:00
|
|
|
elif is_container_type(typ):
|
2019-04-07 13:36:05 +00:00
|
|
|
temp = {}
|
2019-05-27 19:46:14 +00:00
|
|
|
for field, subtype in typ.get_fields():
|
|
|
|
temp[field] = decode(data[field], subtype)
|
|
|
|
if field + "_hash_tree_root" in data:
|
|
|
|
assert(data[field + "_hash_tree_root"][2:] ==
|
2019-04-07 13:36:05 +00:00
|
|
|
hash_tree_root(temp[field], subtype).hex())
|
|
|
|
ret = typ(**temp)
|
2019-05-27 19:46:14 +00:00
|
|
|
if "hash_tree_root" in data:
|
|
|
|
assert(data["hash_tree_root"][2:] ==
|
2019-04-07 13:36:05 +00:00
|
|
|
hash_tree_root(ret, typ).hex())
|
|
|
|
return ret
|
|
|
|
else:
|
2019-06-04 09:42:21 +00:00
|
|
|
raise Exception(f"Type not recognized: data={data}, typ={typ}")
|