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