Skip to content

Commit ab09e2e

Browse files
authored
Add debug tools for SSZ deserialization (#4729)
1 parent bb91d70 commit ab09e2e

File tree

1 file changed

+71
-0
lines changed
  • tests/core/pyspec/eth2spec/debug

1 file changed

+71
-0
lines changed
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
"""
2+
Helper functions to get SSZ objects from files and output them.
3+
"""
4+
5+
from pathlib import Path
6+
from typing import TypeVar
7+
8+
import snappy
9+
from ruamel.yaml import YAML
10+
11+
from eth2spec.debug.encode import encode
12+
from eth2spec.utils.ssz.ssz_impl import deserialize
13+
14+
SSZObject = TypeVar("SSZObject")
15+
16+
17+
def get_ssz_object_from_ssz_encoded(file_path: Path, typ: SSZObject) -> SSZObject:
18+
"""
19+
Get the SSZObject from an SSZ-encoded file.
20+
21+
Automatically detects whether the file is snappy-compressed based on the file extension:
22+
- .ssz_snappy: snappy-compressed
23+
- .ssz: uncompressed
24+
25+
Args:
26+
file_path: Path to the SSZ file (.ssz or .ssz_snappy)
27+
typ: The SSZ type to deserialize into
28+
29+
Returns:
30+
The deserialized SSZ object
31+
32+
Raises:
33+
ValueError: If the file extension is not .ssz or .ssz_snappy
34+
"""
35+
with open(file_path, "rb") as f:
36+
data = f.read()
37+
38+
# Determine if snappy-compressed based on file extension
39+
if file_path.suffix == ".ssz_snappy" or file_path.name.endswith(".ssz_snappy"):
40+
data = snappy.decompress(data)
41+
elif file_path.suffix == ".ssz":
42+
pass # No decompression needed
43+
else:
44+
raise ValueError(
45+
f"Unsupported file extension: {file_path.suffix}. Expected .ssz or .ssz_snappy"
46+
)
47+
48+
return deserialize(typ, data)
49+
50+
51+
def output_ssz_to_file(
52+
output_path: Path, obj: SSZObject, include_hash_tree_roots: bool = False
53+
) -> None:
54+
"""
55+
Output an SSZ object to a YAML file.
56+
57+
Args:
58+
output_path: Path where to save the YAML file
59+
obj: The SSZ object to encode
60+
include_hash_tree_roots: Whether to include hash tree roots in the output
61+
"""
62+
yaml = YAML()
63+
yaml.default_flow_style = False
64+
yaml.indent(mapping=2, sequence=2, offset=0)
65+
yaml.width = 4096
66+
67+
encoded = encode(obj, include_hash_tree_roots)
68+
69+
output_path.parent.mkdir(parents=True, exist_ok=True)
70+
with open(output_path, "w") as f:
71+
yaml.dump(encoded, f)

0 commit comments

Comments
 (0)