2019-07-01 04:04:47 +00:00
|
|
|
from eth2spec.utils.ssz.ssz_impl import hash_tree_root, serialize
|
2019-06-01 00:22:14 +00:00
|
|
|
from eth2spec.utils.ssz.ssz_typing import (
|
2019-07-01 04:04:47 +00:00
|
|
|
uint, boolean,
|
2021-06-24 15:13:36 +00:00
|
|
|
Bitlist, Bitvector, Container, Vector, List, Union
|
2019-06-01 00:22:14 +00:00
|
|
|
)
|
2019-04-07 13:36:05 +00:00
|
|
|
|
|
|
|
|
2019-06-30 13:36:54 +00:00
|
|
|
def encode(value, include_hash_tree_roots=False):
|
2019-06-19 00:37:22 +00:00
|
|
|
if isinstance(value, uint):
|
2019-05-27 20:19:18 +00:00
|
|
|
# Larger uints are boxed and the class declares their byte length
|
2020-01-24 23:43:43 +00:00
|
|
|
if value.__class__.type_byte_length() > 8:
|
2019-06-22 19:49:42 +00:00
|
|
|
return str(int(value))
|
|
|
|
return int(value)
|
2019-06-27 08:51:06 +00:00
|
|
|
elif isinstance(value, boolean):
|
2019-06-22 18:04:17 +00:00
|
|
|
return value == 1
|
2019-07-01 04:04:47 +00:00
|
|
|
elif isinstance(value, (Bitlist, Bitvector)):
|
|
|
|
return '0x' + serialize(value).hex()
|
2020-01-24 23:43:43 +00:00
|
|
|
elif isinstance(value, list): # normal python lists
|
2019-06-19 00:37:22 +00:00
|
|
|
return [encode(element, include_hash_tree_roots) for element in value]
|
2020-01-24 23:43:43 +00:00
|
|
|
elif isinstance(value, (List, Vector)):
|
|
|
|
return [encode(element, include_hash_tree_roots) for element in value]
|
|
|
|
elif isinstance(value, bytes): # bytes, ByteList, ByteVector
|
2019-04-07 13:36:05 +00:00
|
|
|
return '0x' + value.hex()
|
2019-06-19 00:37:22 +00:00
|
|
|
elif isinstance(value, Container):
|
2019-04-07 13:36:05 +00:00
|
|
|
ret = {}
|
2020-01-24 23:43:43 +00:00
|
|
|
for field_name in value.fields().keys():
|
|
|
|
field_value = getattr(value, field_name)
|
2019-06-19 00:37:22 +00:00
|
|
|
ret[field_name] = encode(field_value, include_hash_tree_roots)
|
2019-04-07 13:36:05 +00:00
|
|
|
if include_hash_tree_roots:
|
2019-06-19 00:37:22 +00:00
|
|
|
ret[field_name + "_hash_tree_root"] = '0x' + hash_tree_root(field_value).hex()
|
2019-04-07 13:36:05 +00:00
|
|
|
if include_hash_tree_roots:
|
2019-06-19 00:37:22 +00:00
|
|
|
ret["hash_tree_root"] = '0x' + hash_tree_root(value).hex()
|
2019-04-07 13:36:05 +00:00
|
|
|
return ret
|
2021-06-24 15:13:36 +00:00
|
|
|
elif isinstance(value, Union):
|
|
|
|
inner_value = value.value()
|
|
|
|
return {
|
|
|
|
'selector': int(value.selector()),
|
|
|
|
'value': None if inner_value is None else encode(inner_value, include_hash_tree_roots)
|
|
|
|
}
|
2019-04-07 13:36:05 +00:00
|
|
|
else:
|
2019-07-26 22:26:05 +00:00
|
|
|
raise Exception(f"Type not recognized: value={value}, typ={type(value)}")
|