2019-06-19 00:37:22 +00:00
|
|
|
from typing import Any
|
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 (
|
2019-06-19 00:37:22 +00:00
|
|
|
SSZType, SSZValue, uint, Container, Bytes, List, Bit,
|
2019-06-01 00:22:14 +00:00
|
|
|
Vector, BytesN
|
|
|
|
)
|
2019-04-07 13:36:05 +00:00
|
|
|
|
|
|
|
|
2019-06-19 00:37:22 +00:00
|
|
|
def decode(data: Any, typ: SSZType) -> SSZValue:
|
|
|
|
if issubclass(typ, (uint, Bit)):
|
|
|
|
return typ(data)
|
|
|
|
elif issubclass(typ, (List, Vector)):
|
|
|
|
return typ(decode(element, typ.elem_type) for element in data)
|
|
|
|
elif issubclass(typ, (Bytes, BytesN)):
|
|
|
|
return typ(bytes.fromhex(data[2:]))
|
|
|
|
elif issubclass(typ, Container):
|
2019-04-07 13:36:05 +00:00
|
|
|
temp = {}
|
2019-06-19 00:37:22 +00:00
|
|
|
for field_name, field_type in typ.get_fields().items():
|
|
|
|
temp[field_name] = decode(data[field_name], field_type)
|
|
|
|
if field_name + "_hash_tree_root" in data:
|
|
|
|
assert (data[field_name + "_hash_tree_root"][2:] ==
|
|
|
|
hash_tree_root(temp[field_name]).hex())
|
2019-04-07 13:36:05 +00:00
|
|
|
ret = typ(**temp)
|
2019-05-27 19:46:14 +00:00
|
|
|
if "hash_tree_root" in data:
|
2019-06-19 00:37:22 +00:00
|
|
|
assert (data["hash_tree_root"][2:] ==
|
|
|
|
hash_tree_root(ret).hex())
|
2019-04-07 13:36:05 +00:00
|
|
|
return ret
|
|
|
|
else:
|
2019-06-04 09:42:21 +00:00
|
|
|
raise Exception(f"Type not recognized: data={data}, typ={typ}")
|