/ test_libs / pyspec / eth2spec / debug / encode.py
encode.py
 1  from eth2spec.utils.minimal_ssz import hash_tree_root
 2  
 3  
 4  def encode(value, typ, include_hash_tree_roots=False):
 5      if isinstance(typ, str) and typ[:4] == 'uint':
 6          if typ[4:] == '128' or typ[4:] == '256':
 7              return str(value)
 8          return value
 9      elif typ == 'bool':
10          assert value in (True, False)
11          return value
12      elif isinstance(typ, list):
13          return [encode(element, typ[0], include_hash_tree_roots) for element in value]
14      elif isinstance(typ, str) and typ[:4] == 'byte':
15          return '0x' + value.hex()
16      elif hasattr(typ, 'fields'):
17          ret = {}
18          for field, subtype in typ.fields.items():
19              ret[field] = encode(getattr(value, field), subtype, include_hash_tree_roots)
20              if include_hash_tree_roots:
21                  ret[field + "_hash_tree_root"] = '0x' + hash_tree_root(getattr(value, field), subtype).hex()
22          if include_hash_tree_roots:
23              ret["hash_tree_root"] = '0x' + hash_tree_root(value, typ).hex()
24          return ret
25      else:
26          print(value, typ)
27          raise Exception("Type not recognized")
28