-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathmitm_addon.py
More file actions
1816 lines (1557 loc) · 69.7 KB
/
mitm_addon.py
File metadata and controls
1816 lines (1557 loc) · 69.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import base64
import hmac
import hashlib
import json
import os
import pathlib
import re
import shutil
import threading
import subprocess
import time
import uuid
from datetime import datetime
from time import perf_counter
from typing import Any, Dict, List, Optional, Tuple
from urllib.parse import urlparse
from mitmproxy import http, ctx
# ---------------------------------------------------------------------------
# Configuration & Globals
# ---------------------------------------------------------------------------
_CFG_PATH = os.environ.get("MITM_ADDON_CONFIG", "mitm_config.json")
with open(_CFG_PATH, "r", encoding="utf-8") as _f:
_CFG = json.load(_f)
RPC_DIRECT: str = _CFG["rpc_direct"]
ENGINE_URL: str = _CFG["engine_url"]
JWT_HEX_PATH: str = _CFG["jwt_hex_path"]
FINALIZED_BLOCK: str = _CFG.get("finalized_block") or ""
HOOK_BLOCK: str = _CFG.get("hook_block") or ""
SKIP_CLEANUP: bool = bool(_CFG.get("skip_cleanup"))
DISABLE_OVERLAY_RESTORE: bool = bool(_CFG.get("disable_overlay_restore"))
OVERLAY_RESTORE_TRIGGER_ADDRESS: str = _CFG.get("overlay_restore_trigger_address", "0x86cf016fb873d50a7b8f31eb154c9234dd31b058").lower()
REUSE_GLOBALS: bool = bool(_CFG.get("reuse_globals"))
FORK: str = str(_CFG.get("fork") or "Prague")
def _cfg_bool(value: Any, default: bool = False) -> bool:
if value is None:
return default
if isinstance(value, bool):
return value
if isinstance(value, (int, float)):
return bool(value)
if isinstance(value, str):
return value.strip().lower() in {"1", "true", "yes", "y", "on"}
return default
EEST_STATEFUL_TESTING: bool = _cfg_bool(_CFG.get("eest_stateful_testing"), False)
_TESTING_BUILDBLOCK_TIMESTAMP_HACK: bool = _cfg_bool(_CFG.get("testing_buildblock_timestamp_hack"), False)
def _newpayload_method_for_fork(fork: str) -> str:
if fork.lower() in ("amsterdam",):
return "engine_newPayloadV5"
return "engine_newPayloadV4"
_NEWPAYLOAD_METHOD = _newpayload_method_for_fork(FORK)
_IS_AMSTERDAM: bool = FORK.lower() in ("amsterdam",)
_SLOT_COUNTER: int = int(_CFG.get("slot_counter_start") or 0)
def _next_slot() -> str:
global _SLOT_COUNTER
_SLOT_COUNTER += 1
return hex(_SLOT_COUNTER)
_DYN_FINALIZED: str = FINALIZED_BLOCK
_u = urlparse(ENGINE_URL)
_ENGINE_HOST = _u.hostname or "127.0.0.1"
_ENGINE_PORT = _u.port or (443 if (_u.scheme == "https") else 80)
_ENGINE_PATH = _u.path or "/"
_LOG_FILE_RAW = _CFG.get("mitm_log_path") or _CFG.get("log_file")
_LOG_FILE_PATH = pathlib.Path(_LOG_FILE_RAW).expanduser() if _LOG_FILE_RAW else pathlib.Path("/root/mitm_logs.log")
if not _LOG_FILE_PATH.is_absolute():
_LOG_FILE_PATH = _LOG_FILE_PATH.resolve()
_LOG_FILE = str(_LOG_FILE_PATH)
_FULL_LOG_RAW = _CFG.get("mitm_full_log_path") or _CFG.get("full_log_path")
_FULL_LOG_PATH = pathlib.Path(_FULL_LOG_RAW).expanduser() if _FULL_LOG_RAW else _LOG_FILE_PATH.with_name("mitm_full.log")
if not _FULL_LOG_PATH.is_absolute():
_FULL_LOG_PATH = _FULL_LOG_PATH.resolve()
if "mitm_full_log" in _CFG:
_FULL_LOG_ENABLED = _cfg_bool(_CFG.get("mitm_full_log"), False)
elif "full_log" in _CFG:
_FULL_LOG_ENABLED = _cfg_bool(_CFG.get("full_log"), False)
else:
_FULL_LOG_ENABLED = bool(_FULL_LOG_RAW)
_MERGED_LOG_RAW = _CFG.get("merged_log_path")
_MERGED_LOG_PATH = pathlib.Path(_MERGED_LOG_RAW).expanduser() if _MERGED_LOG_RAW else _LOG_FILE_PATH.with_name("mitm_nethermind.log")
if not _MERGED_LOG_PATH.is_absolute():
_MERGED_LOG_PATH = _MERGED_LOG_PATH.resolve()
_NETHERMIND_CONTAINER = _CFG.get("nethermind_container") or "eest-nethermind"
_LIGHT_LOG = bool(_CFG.get("light_logs", True))
_MITM_QUIET = bool(_CFG.get("mitm_quiet", True))
_MITM_TERMLOG_VERBOSITY = _CFG.get("mitm_termlog_verbosity", "error")
_MITM_EVENTLOG_VERBOSITY = _CFG.get("mitm_eventlog_verbosity", "error")
_MITM_FLOWLIST_VERBOSITY = _CFG.get("mitm_flowlist_verbosity", "error")
_MITM_FLOW_DETAIL = _CFG.get("mitm_flow_detail", 0)
try:
_MITM_FLOW_DETAIL = int(_MITM_FLOW_DETAIL)
except Exception:
_MITM_FLOW_DETAIL = 0
_LIGHT_PREFIX_KEEP = ("[MITM]", "[NM]", "[SENDRAW]", "ERROR", "WARN", "overlay", "PAUSE", "RESUME")
_NM_LAST_TS: Optional[str] = None
# Synchronization / state
_GROUP_LOCK = threading.Lock()
_ACTIVE_GRP: Optional[Tuple[str, str, str]] = None # (file_base, test_name, phase)
_LAST_SENDRAW_TS: float = 0.0 # timestamp of the last buffered sendRawTransaction (diagnostic only)
_PENDING: bool = False
_STAGE: Dict[Tuple[str, str, str], int] = {}
_BUF: List[Tuple[str, Any, Optional[str], Optional[int]]] = [] # list of (txrlp_hex, original_id, extra_data_label, tx_index)
_STOP: bool = False
_LIFECYCLE_TS: Optional[int] = None
# Per-scenario bookkeeping
_SEEN_SCENARIOS: set[str] = set()
_TESTING_SEEN_COUNT: Dict[str, int] = {}
# Scenario ordering (stable numbering for later replay)
_SCENARIO_INDEX: Dict[str, int] = {}
_SCENARIO_SEQUENCE: List[Dict[str, Any]] = []
def _write_scenario_order() -> None:
if _SCENARIO_ORDER_FILE is None:
return
try:
_SCENARIO_ORDER_FILE.parent.mkdir(parents=True, exist_ok=True)
_SCENARIO_ORDER_FILE.write_text(json.dumps(_SCENARIO_SEQUENCE, indent=2), encoding="utf-8")
except Exception as e:
_log(f"scenario order write failed: {e}")
def _register_scenario(name: str) -> int:
idx = _SCENARIO_INDEX.get(name)
if idx is not None:
return idx
idx = len(_SCENARIO_INDEX) + 1
_SCENARIO_INDEX[name] = idx
_SCENARIO_SEQUENCE.append({"index": idx, "name": name})
_write_scenario_order()
return idx
# --- Test lifecycle + global no-phase bookkeeping ---
_TESTS_STARTED: bool = False # flipped True on first phased test sendraw (setup/testing/cleanup)
# Base paths
# Allow overriding payload directory via config (defaults to repo-relative path)
_PAYLOADS_DIR = pathlib.Path(_CFG.get("payload_dir", "eest_stateful")).expanduser()
if not _PAYLOADS_DIR.is_absolute():
_PAYLOADS_DIR = _PAYLOADS_DIR.resolve()
_SETUP_DIR = _PAYLOADS_DIR / "setup"
_TESTING_DIR = _PAYLOADS_DIR / "testing"
_CLEANUP_DIR = _PAYLOADS_DIR / "cleanup"
_PHASE_BASE_DIRS: Dict[str, pathlib.Path] = {
"setup": _SETUP_DIR,
"testing": _TESTING_DIR,
"cleanup": _CLEANUP_DIR,
}
_CONTROL_DIR = _PAYLOADS_DIR / "_control"
_PAUSE_FILE = _CONTROL_DIR / "pause.json"
_RESUME_FILE = _CONTROL_DIR / "resume.json"
_PAUSE_LOCK = threading.Lock()
_PAUSE_EVENT = threading.Event()
_PAUSE_EVENT.set()
_PAUSE_TOKEN: Optional[str] = None
_PAUSE_SCENARIO: Optional[str] = None
_CONTROL_THREAD: Optional[threading.Thread] = None
_PENDING_OVERLAY: Optional[Tuple[str, int, Optional[str]]] = None # (scenario, stage, block)
_PENDING_TX_HASHES: set = set() # tx hashes awaiting eth_getTransactionByHash confirmation
_PENDING_TX_LOCK = threading.Lock()
_ALL_TX_CONFIRMED_EVENT = threading.Event()
_ALL_TX_CONFIRMED_EVENT.set() # initially set (no pending txs)
_SEPARATOR_READY_FOR_NEXT_SETUP: bool = False
_PENDING_SEPARATOR_PAIR: Optional[Tuple[Dict[str, Any], Dict[str, Any]]] = None
_LEGACY_PHASE_DIRS_CLEANED: bool = False
_OVERLAY_PRIMED: bool = False
def _scenario_file_path(phase: str, scenario: str) -> pathlib.Path:
base = _PHASE_BASE_DIRS.get(phase.lower())
if base is None:
raise ValueError(f"unknown phase '{phase}'")
_register_scenario(scenario)
base.mkdir(parents=True, exist_ok=True)
return base / f"{scenario}.txt"
_SCENARIO_ORDER_FILE_RAW = _CFG.get("scenario_order_file")
if isinstance(_SCENARIO_ORDER_FILE_RAW, str) and _SCENARIO_ORDER_FILE_RAW.strip():
_SCENARIO_ORDER_FILE = pathlib.Path(_SCENARIO_ORDER_FILE_RAW).expanduser()
if not _SCENARIO_ORDER_FILE.is_absolute():
_SCENARIO_ORDER_FILE = (_PAYLOADS_DIR / _SCENARIO_ORDER_FILE).resolve()
else:
_SCENARIO_ORDER_FILE = _SCENARIO_ORDER_FILE.resolve()
elif _SCENARIO_ORDER_FILE_RAW:
_SCENARIO_ORDER_FILE = pathlib.Path(_SCENARIO_ORDER_FILE_RAW).expanduser().resolve()
else:
_SCENARIO_ORDER_FILE = None
# Legacy/unknown helpers
_GLOBAL_SETUP_FILE = _PAYLOADS_DIR / "global-setup.txt" # only used for one-time migration on load
_UNKNOWN_FILE = _PAYLOADS_DIR / "unknown.txt"
# Global no-phase lifecycle files (root of payloads/)
_SETUP_GLOBAL_FILE = _PAYLOADS_DIR / "setup-global-test.txt"
_MIDDLE_GLOBAL_FILE = _PAYLOADS_DIR / "middle-global-tests.txt"
_CURRENT_LAST_FILE = _PAYLOADS_DIR / "current-last-global-test.txt"
# ---------------------------------------------------------------------------
# Utilities
# ---------------------------------------------------------------------------
def _append_lines(path: pathlib.Path, lines: List[str]) -> None:
try:
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("a", encoding="utf-8") as f:
for ln in lines:
f.write(ln + "\n")
except Exception:
pass
def _now_ts() -> str:
return datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
def _log(msg: str, *, to_merged: bool = False) -> None:
try:
line = f"{_now_ts()} {msg}"
if _FULL_LOG_ENABLED:
_append_lines(_FULL_LOG_PATH, [line])
if _LIGHT_LOG and not to_merged:
if not msg.startswith(_LIGHT_PREFIX_KEEP):
return
_append_lines(_LOG_FILE_PATH, [line])
if to_merged:
_append_lines(_MERGED_LOG_PATH, [line])
except Exception:
pass
def _should_log_verbose() -> bool:
return _FULL_LOG_ENABLED or not _LIGHT_LOG
def _set_mitm_option(name: str, value: Any) -> None:
try:
if hasattr(ctx.options, name):
setattr(ctx.options, name, value)
except Exception:
pass
def _apply_mitm_quiet_options() -> None:
if not _MITM_QUIET:
return
_set_mitm_option("termlog_verbosity", _MITM_TERMLOG_VERBOSITY)
_set_mitm_option("console_eventlog_verbosity", _MITM_EVENTLOG_VERBOSITY)
_set_mitm_option("console_flowlist_verbosity", _MITM_FLOWLIST_VERBOSITY)
_set_mitm_option("flow_detail", _MITM_FLOW_DETAIL)
def _capture_nethermind_logs() -> List[str]:
global _NM_LAST_TS
since_args: List[str] = ["--since", _NM_LAST_TS] if _NM_LAST_TS else ["--tail", "200"]
try:
cp = subprocess.run(
["docker", "logs", "--timestamps", *since_args, _NETHERMIND_CONTAINER],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
check=False,
)
if cp.returncode != 0:
_log(f"[NM] docker logs rc={cp.returncode} out={cp.stdout[-200:]} err={cp.stderr or ''}")
return []
lines = [ln for ln in cp.stdout.splitlines() if ln.strip()]
if lines:
first = lines[-1]
ts_part = first.split(" ", 1)[0]
if ts_part:
_NM_LAST_TS = ts_part
return lines
except Exception as e:
_log(f"[NM] docker logs error: {e}")
return []
def _emit_newpayload_event(exec_payload: Dict[str, Any], parent_hash: str) -> None:
block_hash = exec_payload.get("blockHash") or "unknown"
txs = exec_payload.get("transactions") or []
block_number = exec_payload.get("blockNumber") or "unknown"
summary = f"[MITM][NP] block={block_hash} blockNumber={block_number} parent={parent_hash} txs={len(txs)}"
_log(summary, to_merged=True)
nm_lines = _capture_nethermind_logs()
if nm_lines:
ts_prefix = _now_ts()
prefixed = [f"{ts_prefix} [NM] {ln}" for ln in nm_lines]
_append_lines(_MERGED_LOG_PATH, prefixed)
_append_lines(_LOG_FILE_PATH, prefixed)
if _FULL_LOG_ENABLED:
_append_lines(_FULL_LOG_PATH, prefixed)
def _insert_empty_hook_separator(reason: str, scenario: str) -> None:
global _SEPARATOR_READY_FOR_NEXT_SETUP, _PENDING_SEPARATOR_PAIR
hook_block_hash = _read_hook_block_for_first_setup()
if not hook_block_hash:
_log(f"WARN cannot insert empty separator ({reason}): missing hook block")
return
hook_block = _rpc("eth_getBlockByHash", [hook_block_hash, False])
if not isinstance(hook_block, dict):
_log(f"WARN cannot insert empty separator ({reason}): hook block {hook_block_hash} not found")
return
parent_hash = hook_block.get("hash")
if not isinstance(parent_hash, str) or not parent_hash:
_log(f"WARN cannot insert empty separator ({reason}): hook parent missing hash")
return
parent_ts_hex = hook_block.get("timestamp")
try:
parent_ts = int(parent_ts_hex, 16) if isinstance(parent_ts_hex, str) else int(parent_ts_hex or 0)
except Exception:
parent_ts = int(time.time())
separator_ts = _next_lifecycle_timestamp(parent_ts)
extra_data = "0x4e65746865726d696e642076312e33372e3061"
separator_attrs = {
"timestamp": hex(separator_ts),
"prevRandao": parent_hash,
"suggestedFeeRecipient": "0x0000000000000000000000000000000000000000",
"withdrawals": [],
"parentBeaconBlockRoot": parent_hash,
}
if _IS_AMSTERDAM:
separator_attrs["slotNumber"] = _next_slot()
_log(
f"inserting empty hook separator ({reason}) scenario={scenario} parent={parent_hash} "
f"timestamp={separator_attrs['timestamp']}"
)
sep_raw = _engine("testing_buildBlockV1", [parent_hash, separator_attrs, [], extra_data])
sep_payload = sep_raw if isinstance(sep_raw, dict) else {}
sep_exec = sep_payload.get("executionPayload", sep_payload)
if not isinstance(sep_exec, dict):
_log(f"WARN failed to insert empty separator ({reason}): non-dict payload")
return
sep_parent_hash = sep_exec.get("parentHash") or parent_hash
sep_blob_hashes = _extract_blob_versioned_hashes(sep_payload, sep_exec)
sep_exec_requests = _extract_execution_requests(sep_payload)
_engine(_NEWPAYLOAD_METHOD, [sep_exec, sep_blob_hashes, separator_attrs["parentBeaconBlockRoot"], sep_exec_requests])
_emit_newpayload_event(sep_exec, sep_parent_hash)
sep_hash = sep_exec.get("blockHash")
sep_dyn_final = _DYN_FINALIZED or FINALIZED_BLOCK or sep_hash
sep_fcs = {
"headBlockHash": sep_hash,
"safeBlockHash": sep_dyn_final,
"finalizedBlockHash": sep_dyn_final,
}
_engine("engine_forkchoiceUpdatedV3", [sep_fcs, None])
np_body = {
"jsonrpc": "2.0",
"id": int(time.time()),
"method": _NEWPAYLOAD_METHOD,
"params": [sep_exec, sep_blob_hashes, separator_attrs["parentBeaconBlockRoot"], sep_exec_requests],
}
fcu_body = {
"jsonrpc": "2.0",
"id": int(time.time()),
"method": "engine_forkchoiceUpdatedV3",
"params": [sep_fcs, None],
}
_PENDING_SEPARATOR_PAIR = (np_body, fcu_body)
_SEPARATOR_READY_FOR_NEXT_SETUP = True
_log(f"inserted empty hook separator ({reason}) hash={sep_hash}")
def _http_post_json(url: str, obj: Any, timeout: int = 90, headers: Optional[Dict[str, str]] = None) -> Any:
try:
import requests # type: ignore
r = requests.post(url, json=obj, timeout=timeout, headers=headers or {})
r.raise_for_status()
return r.json()
except Exception:
import urllib.request
data = json.dumps(obj).encode("utf-8")
req = urllib.request.Request(
url, data=data, headers={"Content-Type": "application/json", **(headers or {})}
)
with urllib.request.urlopen(req, timeout=timeout) as resp: # noqa: S310
return json.loads(resp.read().decode("utf-8"))
def _b64url(b: bytes) -> bytes:
return base64.urlsafe_b64encode(b).rstrip(b"=")
def _jwt_from_file() -> str:
secret_hex = open(JWT_HEX_PATH, "r").read().strip().replace("0x", "")
secret = bytes.fromhex(secret_hex)
header = _b64url(b'{"alg":"HS256","typ":"JWT"}')
payload = _b64url(json.dumps({"iat": int(time.time())}).encode())
unsigned = header + b"." + payload
sig = hmac.new(secret, unsigned, hashlib.sha256).digest()
return (unsigned + b"." + _b64url(sig)).decode()
def _engine(method: str, params: List[Any]) -> Any:
token = _jwt_from_file()
body = {"jsonrpc": "2.0", "id": int(time.time()), "method": method, "params": params}
if _should_log_verbose():
# Log with redacted Authorization
eng_hdrs = {"Content-Type": "application/json", "Authorization": "Bearer <redacted>"}
_log(
f"REQ POST {_ENGINE_HOST}:{_ENGINE_PORT}{_ENGINE_PATH} "
f"headers={json.dumps(eng_hdrs)} body_preview={json.dumps(body)}"
)
j = _http_post_json(ENGINE_URL, body, timeout=90, headers={"Authorization": f"Bearer {token}"})
if _should_log_verbose():
try:
_log(
f"RESP POST {_ENGINE_HOST}:{_ENGINE_PORT}{_ENGINE_PATH} "
f"status=200 headers={json.dumps({'Content-Type':'application/json'})} "
f"body_preview={json.dumps(j)}"
)
except Exception:
_log(f"RESP POST {_ENGINE_HOST}:{_ENGINE_PORT}{_ENGINE_PATH} status=200 <non-json>")
if "error" in j:
_log(f"ERROR engine call {method} failed: {j['error']}")
raise RuntimeError(str(j["error"]))
return j["result"]
def _rpc(method: str, params: Optional[List[Any]] = None) -> Any:
try:
j = _http_post_json(
RPC_DIRECT,
{"jsonrpc": "2.0", "id": int(time.time()), "method": method, "params": params or []},
timeout=30,
)
return j.get("result")
except Exception as e:
_log(f"rpc {method} failed: {e}")
return None
def _sanitize_filename_component(s: str) -> str:
# Keep name readable; only neutralize path separators and control chars.
s = s.replace(os.sep, "_").replace("\\", "_").replace("/", "_")
s = s.replace("\x00", "").replace("\n", " ").replace("\r", " ").replace("\t", " ")
s = s.strip()
return s or "unknown"
def _parse_id_json(id_obj: Any) -> Optional[Dict[str, Any]]:
if isinstance(id_obj, str):
try:
id_obj = json.loads(id_obj)
except Exception:
return None
if isinstance(id_obj, dict):
return {"testId": id_obj.get("testId"), "phase": id_obj.get("phase"), "txIndex": id_obj.get("txIndex")}
return None
def _parse_header_json(hdr_str: Optional[str]) -> Optional[Dict[str, Any]]:
if not hdr_str:
return None
try:
j = json.loads(hdr_str)
if isinstance(j, dict):
return {"testId": j.get("testId"), "phase": j.get("phase"), "txIndex": j.get("txIndex")}
except Exception:
return None
return None
def _derive_group_from_meta(meta: Optional[Dict[str, Any]]) -> Tuple[str, str, str]:
test_id = (meta or {}).get("testId") or "unknown"
if "::" in test_id:
file_path_str, test_name = test_id.split("::", 1)
else:
file_path_str, test_name = test_id, "unknown_test"
file_base = _sanitize_filename_component(os.path.basename(file_path_str))
test_name = _sanitize_filename_component(test_name)
phase = _sanitize_filename_component((meta or {}).get("phase") or "unknown")
return (file_base, test_name, phase)
def _extra_data_label_from_meta(meta: Optional[Dict[str, Any]]) -> Optional[str]:
if not isinstance(meta, dict):
return None
test_id = meta.get("testId")
if not isinstance(test_id, str) or not test_id:
return None
phase = meta.get("phase")
if isinstance(phase, str) and phase:
return f"{phase}:{test_id}"
return test_id
def _extra_data_from_label(label: Optional[str]) -> str:
# Keep extraData human-readable in client logs; header remains consensus-hashed as usual.
if not isinstance(label, str) or not label:
label = "Nethermind v1.37.0a"
# Ensure printable, stable ASCII before truncating to the 32-byte header limit.
ascii_text = "".join(ch if 32 <= ord(ch) <= 126 else "_" for ch in label)
data = ascii_text.encode("ascii", errors="ignore")[:32]
return "0x" + data.hex()
def _keccak256(data: bytes) -> bytes:
try:
from eth_hash.auto import keccak as _eth_keccak # type: ignore
return _eth_keccak(data)
except Exception:
pass
try:
import sha3 # type: ignore
k = sha3.keccak_256()
k.update(data)
return k.digest()
except Exception:
pass
try:
from Crypto.Hash import keccak as _crypto_keccak # type: ignore
k = _crypto_keccak.new(digest_bits=256)
k.update(data)
return k.digest()
except Exception:
pass
raise RuntimeError("No Keccak-256 implementation available for tx hash calculation")
def _tx_hash_from_raw(raw_tx: str) -> str:
raw_bytes = _hex_to_bytes(raw_tx)
if raw_bytes is None:
raise ValueError("Invalid raw tx hex")
try:
return "0x" + _keccak256(raw_bytes).hex()
except Exception as local_err:
# Fallback for minimal runner environments: ask node for Keccak(data).
raw_hex = raw_tx if isinstance(raw_tx, str) and raw_tx.startswith("0x") else ("0x" + raw_bytes.hex())
rpc_hash = _rpc("web3_sha3", [raw_hex])
if isinstance(rpc_hash, str) and rpc_hash.startswith("0x") and len(rpc_hash) == 66:
return rpc_hash
raise RuntimeError(
f"No local Keccak-256 implementation and web3_sha3 fallback failed: {local_err}"
)
def _sendraw_success_response(req_obj: Dict[str, Any], tx_hash: str) -> Dict[str, Any]:
return {
"jsonrpc": req_obj.get("jsonrpc", "2.0"),
"id": req_obj.get("id"),
"result": tx_hash,
}
def _sendraw_error_response(req_obj: Dict[str, Any], message: str) -> Dict[str, Any]:
return {
"jsonrpc": req_obj.get("jsonrpc", "2.0"),
"id": req_obj.get("id"),
"error": {"code": -32602, "message": message},
}
def _scenario_name(file_base: str, test_name: str) -> str:
fb = _sanitize_filename_component(file_base)
tn = _sanitize_filename_component(test_name)
# Normalise the EEST-injected "-benchmark-gas-value_XXX" to "-benchmark_XXX"
# so filenames stay consistent with the parametrized naming convention.
tn = re.sub(r"-benchmark-gas-value_([^-\]]+)", r"-benchmark_\1", tn)
scenario = f"{fb}__{tn}"
return scenario
def _collect_hashes_from_node(node: Any) -> List[str]:
hashes: List[str] = []
if isinstance(node, dict):
if "hash" in node and isinstance(node.get("hash"), str):
hashes.append(node["hash"])
for v in node.values():
hashes.extend(_collect_hashes_from_node(v))
elif isinstance(node, list):
for v in node:
hashes.extend(_collect_hashes_from_node(v))
return hashes
def _log_txpool_summary() -> None:
pool = _rpc("txpool_content")
if pool is None:
_log("txpool_content: None")
return
try:
pending = pool.get("pending") if isinstance(pool, dict) else None
queued = pool.get("queued") if isinstance(pool, dict) else None
def _count(node: Any) -> int:
if node is None:
return 0
if isinstance(node, dict):
total = 0
for v in node.values():
total += _count(v)
if "hash" in node and isinstance(node.get("hash"), str):
total = max(total, 1)
return total
if isinstance(node, list):
return sum(_count(v) for v in node)
return 0
p_cnt = _count(pending)
q_cnt = _count(queued)
_log(f"txpool_content pending={p_cnt} queued={q_cnt}")
first_hashes = _collect_hashes_from_node(pending)[:3] if pending is not None else []
if first_hashes:
_log(f"txpool_content sample={', '.join(first_hashes)}")
except Exception as e:
_log(f"txpool summarize error: {e}")
def _hex_to_bytes(value: Any) -> Optional[bytes]:
if not isinstance(value, str):
return None
v = value[2:] if value.startswith("0x") else value
if len(v) % 2 == 1:
v = "0" + v
try:
return bytes.fromhex(v)
except Exception:
return None
def _kzg_commitment_to_versioned_hash(commitment_hex: Any) -> Optional[str]:
raw = _hex_to_bytes(commitment_hex)
if raw is None:
return None
digest = hashlib.sha256(raw).digest()
versioned = b"\x01" + digest[1:]
return "0x" + versioned.hex()
def _extract_blob_versioned_hashes(payload: Dict[str, Any], exec_payload: Dict[str, Any]) -> List[str]:
for key in ("blobVersionedHashes", "blob_versioned_hashes", "versionedHashes", "versioned_hashes"):
hashes = payload.get(key)
if isinstance(hashes, list) and hashes:
return [h for h in hashes if isinstance(h, str)]
bundle = payload.get("blobsBundle") or payload.get("blobs_bundle") or {}
commitments = None
if isinstance(bundle, dict):
commitments = bundle.get("commitments")
if isinstance(commitments, list) and commitments:
computed: List[str] = []
for c in commitments:
vh = _kzg_commitment_to_versioned_hash(c)
if vh:
computed.append(vh)
if computed:
return computed
return []
def _extract_execution_requests(payload: Dict[str, Any]) -> List[Any]:
for key in ("executionRequests", "execution_requests"):
reqs = payload.get(key)
if isinstance(reqs, list):
return reqs
return []
def _extract_parent_beacon_block_root(payload: Dict[str, Any], exec_payload: Dict[str, Any]) -> Optional[str]:
for key in ("parentBeaconBlockRoot", "parent_beacon_block_root"):
val = payload.get(key)
if isinstance(val, str) and val:
return val
for key in ("parentBeaconBlockRoot", "parent_beacon_block_root"):
val = exec_payload.get(key)
if isinstance(val, str) and val:
return val
return None
# ---------------------------------------------------------------------------
# File IO helpers for new layout
# ---------------------------------------------------------------------------
def _ensure_dirs_and_cleanup_old() -> None:
global _LEGACY_PHASE_DIRS_CLEANED
_PAYLOADS_DIR.mkdir(parents=True, exist_ok=True)
_SETUP_DIR.mkdir(parents=True, exist_ok=True)
_TESTING_DIR.mkdir(parents=True, exist_ok=True)
_CLEANUP_DIR.mkdir(parents=True, exist_ok=True)
# One-time cleanup: remove legacy numbered subdirectories from old layout.
if _LEGACY_PHASE_DIRS_CLEANED:
return
_LEGACY_PHASE_DIRS_CLEANED = True
for phase_dir in (_SETUP_DIR, _TESTING_DIR, _CLEANUP_DIR):
try:
for child in phase_dir.iterdir():
if child.is_dir() and child.name.isdigit():
try:
shutil.rmtree(child, ignore_errors=True)
_log(f"removed legacy numbered scenario dir: {child}")
except Exception as exc:
_log(f"failed to remove legacy scenario dir {child}: {exc}")
except Exception:
pass
def _minified_json_line(obj: Any) -> str:
return json.dumps(obj, separators=(",", ":"))
def _next_lifecycle_timestamp(parent_ts: int) -> int:
global _LIFECYCLE_TS
if _LIFECYCLE_TS is None:
_LIFECYCLE_TS = parent_ts + 12
else:
_LIFECYCLE_TS += 1
# Safety: always keep timestamp valid vs chosen parent.
if _LIFECYCLE_TS <= parent_ts:
_LIFECYCLE_TS = parent_ts + 12
return _LIFECYCLE_TS
def _read_hook_block_for_first_setup() -> Optional[str]:
# Preferred hook source: dedicated empty hook anchor.
hook_anchor = (HOOK_BLOCK or "").strip()
if hook_anchor:
return hook_anchor
# Fallback: funding anchor passed by generator config.
funding_anchor = (FINALIZED_BLOCK or "").strip()
if funding_anchor:
return funding_anchor
# Legacy fallback: derive hook from setup-global-test payload file.
if not _SETUP_GLOBAL_FILE.exists():
return None
try:
last_block_hash: Optional[str] = None
lines = _SETUP_GLOBAL_FILE.read_text(encoding="utf-8").splitlines()
for raw in lines:
line = raw.strip()
if not line:
continue
try:
obj = json.loads(line)
except Exception:
continue
method = obj.get("method")
if not isinstance(method, str) or not method.startswith("engine_newPayload"):
continue
params = obj.get("params") or []
if params and isinstance(params[0], dict):
block_hash = params[0].get("blockHash")
if isinstance(block_hash, str) and block_hash:
last_block_hash = block_hash
return last_block_hash
except Exception as e:
_log(f"hook block read failed from {_SETUP_GLOBAL_FILE}: {e}")
return None
def _append_line(path: pathlib.Path, line: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("a", encoding="utf-8") as f:
f.write(line)
f.write("\n")
def _overwrite_with_lines(path: pathlib.Path, lines: List[str]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_suffix(path.suffix + ".tmp")
with tmp.open("w", encoding="utf-8") as f:
for ln in lines:
f.write(ln)
f.write("\n")
tmp.replace(path)
def _truncate(path: pathlib.Path) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("w", encoding="utf-8"):
pass
def _truncate_if_first_seen(scenario: str) -> None:
if scenario in _SEEN_SCENARIOS:
return
idx = _register_scenario(scenario)
_SEEN_SCENARIOS.add(scenario)
_TESTING_SEEN_COUNT[scenario] = 0
_log(f"initialized scenario index {idx} for {scenario}")
def _dump_pair_to_phase(phase: str, scenario: str, np_body: Dict[str, Any], fcu_body: Dict[str, Any]) -> None:
np_line = _minified_json_line(np_body)
fcu_line = _minified_json_line(fcu_body)
if phase == "setup":
setup_path = _scenario_file_path("setup", scenario)
_append_line(setup_path, np_line)
_append_line(setup_path, fcu_line)
_log(f"setup append → {setup_path}")
return
if phase == "cleanup":
cleanup_path = _scenario_file_path("cleanup", scenario)
_append_line(cleanup_path, np_line)
_append_line(cleanup_path, fcu_line)
_log(f"cleanup append → {cleanup_path}")
return
# testing
count = _TESTING_SEEN_COUNT.get(scenario, 0)
testing_path = _scenario_file_path("testing", scenario)
setup_path = _scenario_file_path("setup", scenario)
if EEST_STATEFUL_TESTING:
_append_line(testing_path, np_line)
_append_line(testing_path, fcu_line)
_log(f"testing append (stateful) → {testing_path}")
elif count == 0:
_overwrite_with_lines(testing_path, [np_line, fcu_line])
_log(f"testing write (first) → {testing_path}")
else:
if testing_path.exists():
try:
with testing_path.open("r", encoding="utf-8") as f:
prev_lines = [ln.rstrip("\n") for ln in f if ln.strip() != ""]
for ln in prev_lines:
_append_line(setup_path, ln)
_log(f"testing migrate {len(prev_lines)} line(s) → {setup_path}")
except Exception as e:
_log(f"migrate testing→setup failed: {e}")
_overwrite_with_lines(testing_path, [np_line, fcu_line])
_log(f"testing overwrite (latest) → {testing_path}")
_TESTING_SEEN_COUNT[scenario] = count + 1
# ---- helpers for global no-phase routing ----------------------------------
def _append_pair(path: pathlib.Path, np_body: Dict[str, Any], fcu_body: Dict[str, Any]) -> None:
_append_line(path, _minified_json_line(np_body))
_append_line(path, _minified_json_line(fcu_body))
def _file_has_content(path: pathlib.Path) -> bool:
try:
return path.exists() and path.stat().st_size > 0
except Exception:
return False
def _migrate_current_last_to_middle() -> None:
if _file_has_content(_CURRENT_LAST_FILE):
try:
with _CURRENT_LAST_FILE.open("r", encoding="utf-8") as f:
lines = [ln.rstrip("\n") for ln in f if ln.strip()]
for ln in lines:
_append_line(_MIDDLE_GLOBAL_FILE, ln)
_truncate(_CURRENT_LAST_FILE)
_log(f"migrated {len(lines)} line(s) current-last → { _MIDDLE_GLOBAL_FILE }")
except Exception as e:
_log(f"migrate current-last→middle failed: {e}")
def _cleanup_empty_txt_files() -> None:
try:
phase_dirs = {_SETUP_DIR.resolve(), _TESTING_DIR.resolve(), _CLEANUP_DIR.resolve()}
for p in _PAYLOADS_DIR.rglob("*.txt"):
try:
if p.exists() and p.stat().st_size == 0:
parent = p.parent.resolve()
if parent in phase_dirs:
continue
p.unlink()
_log(f"removed empty file: {p}")
except Exception:
pass
except Exception:
pass
# ---------------------------------------------------------------------------
# Flushing / Production
# ---------------------------------------------------------------------------
def _flush_group(grp: Tuple[str, str, str] | None, txrlps: List[str], last_extra_data_label: Optional[str] = None) -> None:
if not txrlps:
_log(f"flush skipped: empty buffer for group={grp}")
return
try:
first = txrlps[0]
last = txrlps[-1]
preview_first = (first[:18] + "…" + first[-10:]) if isinstance(first, str) else str(first)[:32]
preview_last = (last[:18] + "…" + last[-10:]) if isinstance(last, str) else str(last)[:32]
file_base, test_name, phase = grp or ("unknown", "unknown", "unknown")
scenario = _scenario_name(file_base, test_name)
_log(
f"GETPAYLOAD group={grp} count={len(txrlps)} first={preview_first} "
f"last={preview_last} reorg=false"
)
next_stage = _STAGE.get(grp, 0) + 1
phase_lc = (phase or "").lower()
is_first_setup_for_scenario = (
phase_lc == "setup"
and next_stage == 1
and file_base not in {"global-setup", "global-nophase"}
)
latest_block = _rpc("eth_getBlockByNumber", ["latest", False])
if not isinstance(latest_block, dict):
_log(f"flush failed: could not fetch latest block for group={grp}")
return
parent_block: Dict[str, Any] = latest_block
parent_source = "latest"
use_preinserted_separator = is_first_setup_for_scenario and _SEPARATOR_READY_FOR_NEXT_SETUP
if use_preinserted_separator:
globals()["_SEPARATOR_READY_FOR_NEXT_SETUP"] = False
_log(f"using pre-inserted separator parent for scenario={scenario}")
elif is_first_setup_for_scenario:
hook_block_hash = _read_hook_block_for_first_setup()
if hook_block_hash:
hook_block = _rpc("eth_getBlockByHash", [hook_block_hash, False])
if isinstance(hook_block, dict):
parent_block = hook_block
parent_source = "hook"
else:
_log(f"WARN HOOK_BLOCK {hook_block_hash} not found on node; using latest")
else:
_log("WARN HOOK_BLOCK not found (hook/funding/setup-global fallback); using latest")
parent_hash = parent_block.get("hash")
if not isinstance(parent_hash, str) or not parent_hash:
_log(f"flush failed: parent block missing hash for group={grp} source={parent_source}")
return
extra_data = _extra_data_from_label(last_extra_data_label)
parent_ts_hex = parent_block.get("timestamp")
try:
parent_ts = int(parent_ts_hex, 16) if isinstance(parent_ts_hex, str) else int(parent_ts_hex or 0)
except Exception:
parent_ts = int(time.time())
inline_separator_pair: Optional[Tuple[Dict[str, Any], Dict[str, Any]]] = None
if is_first_setup_for_scenario and parent_source == "hook":
separator_ts = _next_lifecycle_timestamp(parent_ts)
separator_attrs = {
"timestamp": hex(separator_ts),
"prevRandao": parent_hash,
"suggestedFeeRecipient": "0x0000000000000000000000000000000000000000",
"withdrawals": [],
"parentBeaconBlockRoot": parent_hash,
}
if _IS_AMSTERDAM:
separator_attrs["slotNumber"] = _next_slot()
_log(f"inserting empty hook separator block before scenario={scenario} parent={parent_hash}")
sep_raw = _engine("testing_buildBlockV1", [parent_hash, separator_attrs, [], extra_data])
sep_payload = sep_raw if isinstance(sep_raw, dict) else {}
sep_exec = sep_payload.get("executionPayload", sep_payload)
if isinstance(sep_exec, dict):
sep_parent_hash = sep_exec.get("parentHash") or parent_hash
sep_blob_hashes = _extract_blob_versioned_hashes(sep_payload, sep_exec)
sep_exec_requests = _extract_execution_requests(sep_payload)