ethswarm-chain-sync 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,13 @@
1
+ # ethswarm_chain_sync
2
+
3
+ | file | description |
4
+ |---|---|
5
+ | `__init__.py` | Public API: `load`, `iter_rows` and `__version__`. |
6
+ | `cli.py` | Command line entry point with the `sync` and `status` subcommands. |
7
+ | `decode.py` | Decodes raw `eth_getLogs` entries into named, JSON-ready rows using `eth_abi`. |
8
+ | `deployments.py` | Resolves contract and event selectors into sync targets from the `ethswarm-deployments` cache. |
9
+ | `load.py` | Reads the cache back as rows, filtered by contract, event, address and network, in chain order. |
10
+ | `rpc.py` | JSON-RPC client protocol and HTTP implementation with short timeouts, retries and range-too-large detection. |
11
+ | `schema.py` | Builds per-deployment event schemas (signature, `topic0`, inputs, store key) from an ABI. |
12
+ | `store.py` | JSONLines store layout, per-event checkpoints, tail rewind on resume, and the per-deployment lock. |
13
+ | `sync.py` | Acquisition engine: concurrent range fetches committed in order, with range bisection and checkpointing. |
@@ -0,0 +1,26 @@
1
+ """Sync Swarm storage-incentives contract events into a local JSONLines cache.
2
+
3
+ Command line: ``ethswarm-chain-sync sync`` fetches and decodes events from the deployed
4
+ storage-incentives contracts (every version, per ``ethswarm-deployments``) up to the
5
+ chain's ``finalized`` block, resuming from each event's checkpoint.
6
+
7
+ As a library, :func:`load` returns the cached rows as a list of dicts in chain order::
8
+
9
+ import ethswarm_chain_sync as ecs
10
+
11
+ rows = ecs.load("PostageStamp", "BatchCreated")
12
+ rows[0]["args"]["batchId"]
13
+
14
+ Row format and on-disk layout are described in ``docs/data-model.md``.
15
+ """
16
+
17
+ from importlib.metadata import PackageNotFoundError, version
18
+
19
+ from .load import iter_rows, load
20
+
21
+ try:
22
+ __version__ = version("ethswarm-chain-sync")
23
+ except PackageNotFoundError: # running from a source tree without installation
24
+ __version__ = "0.0.0"
25
+
26
+ __all__ = ["__version__", "iter_rows", "load"]
@@ -0,0 +1,183 @@
1
+ """Command line: ``ethswarm-chain-sync {sync,status}``.
2
+
3
+ ``sync`` resolves the selected deployments (``--contract`` / ``--event``, see
4
+ :func:`~ethswarm_chain_sync.deployments.resolve_targets`), reads the chain's
5
+ ``finalized`` block once, and syncs each target up to it. Each event starts from its
6
+ stored checkpoint, or from the contract's deployment block on first sync.
7
+
8
+ ``status`` prints the same selection with each event's checkpoint, without touching the
9
+ chain.
10
+
11
+ The RPC endpoint is ``--rpc-url``, else ``$<SHORT>_RPC_URL`` where ``SHORT`` is the
12
+ network's EIP-3770 chain short name (``GNO`` for mainnet/Gnosis, ``SEP`` for
13
+ testnet/Sepolia).
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import argparse
19
+ import os
20
+ import sys
21
+ import time
22
+
23
+ from . import __version__, store
24
+ from .deployments import NETWORK_SHORT_NAMES, SelectionError, Target, resolve_targets
25
+ from .rpc import HttpRpcClient
26
+ from .sync import DEFAULT_CHUNK_SIZE, DEFAULT_WORKERS, sync_target
27
+
28
+
29
+ class _Progress:
30
+ """Per-target progress line on stderr, redrawn in place on a terminal."""
31
+
32
+ def __init__(self, enabled: bool) -> None:
33
+ self.enabled = enabled
34
+ self.inplace = sys.stderr.isatty()
35
+ self.last = 0.0
36
+
37
+ def __call__(self, target: Target, block: int, to_block: int, rows: int) -> None:
38
+ now = time.monotonic()
39
+ if not self.enabled or (now - self.last < 0.5 and block != to_block):
40
+ return
41
+ self.last = now
42
+ line = f" {target.label}: block {block}/{to_block}, {rows} rows"
43
+ if self.inplace:
44
+ print(f"\r\033[K{line}", end="", file=sys.stderr, flush=True)
45
+ else:
46
+ print(line, file=sys.stderr, flush=True)
47
+
48
+ def done(self) -> None:
49
+ if self.enabled and self.inplace:
50
+ print(file=sys.stderr)
51
+
52
+
53
+ def _targets(args) -> list[Target]:
54
+ return resolve_targets(args.network, args.contract or (), args.event or ())
55
+
56
+
57
+ def cmd_sync(args) -> int:
58
+ """Sync every selected target up to ``finalized`` (or ``--to-block``)."""
59
+ url = args.rpc_url or os.environ.get(f"{NETWORK_SHORT_NAMES[args.network]}_RPC_URL")
60
+ if not url:
61
+ env = f"{NETWORK_SHORT_NAMES[args.network]}_RPC_URL"
62
+ print(f"error: no RPC endpoint; pass --rpc-url or set ${env}", file=sys.stderr)
63
+ return 2
64
+ targets = _targets(args)
65
+ rpc = HttpRpcClient(url, timeout=args.timeout)
66
+ finalized = rpc.finalized_block()
67
+ to_block = finalized if args.to_block is None else args.to_block
68
+ if to_block > finalized:
69
+ print(f"error: --to-block {to_block} is past finalized {finalized}", file=sys.stderr)
70
+ return 2
71
+ store_dir = store.resolve_store_dir(args.store_dir)
72
+ print(
73
+ f"store {store_dir}; syncing {len(targets)} contract(s) to block {to_block}",
74
+ file=sys.stderr,
75
+ )
76
+ progress = _Progress(args.progress if args.progress is not None else sys.stderr.isatty())
77
+ for target in targets:
78
+ print(f"{target.label}: {len(target.selected)} event(s)", file=sys.stderr)
79
+ result = sync_target(
80
+ rpc,
81
+ store_dir,
82
+ target,
83
+ to_block=to_block,
84
+ chunk_size=args.chunk_size,
85
+ workers=args.workers,
86
+ progress=progress,
87
+ )
88
+ progress.done()
89
+ total = sum(result.rows.values())
90
+ detail = ", ".join(f"{k}={n}" for k, n in sorted(result.rows.items()) if n)
91
+ print(f" +{total} rows" + (f" ({detail})" if detail else ""), file=sys.stderr)
92
+ return 0
93
+
94
+
95
+ def cmd_status(args) -> int:
96
+ """Print each selected event's checkpoint."""
97
+ store_dir = store.resolve_store_dir(args.store_dir)
98
+ for t in _targets(args):
99
+ dep_dir = store.deployment_dir(store_dir, t.chain_id, t.contract, t.address)
100
+ cps = store.load_checkpoints(dep_dir)
101
+ print(f"{t.contract}@{t.version} {t.address} (deployed at {t.start_block})")
102
+ for s in t.selected_schemas():
103
+ cp = cps.get(s.key)
104
+ state = f"block {cp.block}, {cp.size} bytes" if cp else "not synced"
105
+ print(f" {s.key:<32} {state}")
106
+ return 0
107
+
108
+
109
+ def _add_selection(p: argparse.ArgumentParser) -> None:
110
+ p.add_argument("-n", "--network", choices=sorted(NETWORK_SHORT_NAMES), default="mainnet")
111
+ p.add_argument(
112
+ "-c",
113
+ "--contract",
114
+ action="append",
115
+ metavar="SEL",
116
+ help="contract name, name@version, or address (repeatable; default: all non-token)",
117
+ )
118
+ p.add_argument(
119
+ "-e",
120
+ "--event",
121
+ action="append",
122
+ metavar="NAME",
123
+ help="event name or signature (repeatable; default: all events)",
124
+ )
125
+ p.add_argument(
126
+ "--store-dir",
127
+ help=f"cache directory (default: ${store.STORE_DIR_ENV} or {store.default_store_dir()})",
128
+ )
129
+
130
+
131
+ def build_parser() -> argparse.ArgumentParser:
132
+ """The argument parser (exposed for tests)."""
133
+ parser = argparse.ArgumentParser(prog="ethswarm-chain-sync", description=__doc__.split("\n")[0])
134
+ parser.add_argument("--version", action="version", version=__version__)
135
+ sub = parser.add_subparsers(dest="command", required=True)
136
+
137
+ p_sync = sub.add_parser("sync", help="sync events into the cache up to finalized")
138
+ _add_selection(p_sync)
139
+ p_sync.add_argument("--rpc-url", help="JSON-RPC endpoint (default: $GNO_RPC_URL/$SEP_RPC_URL)")
140
+ p_sync.add_argument("--to-block", type=int, help="sync to this block instead of finalized")
141
+ p_sync.add_argument(
142
+ "--chunk-size",
143
+ type=int,
144
+ default=DEFAULT_CHUNK_SIZE,
145
+ help="blocks per eth_getLogs (default: %(default)s)",
146
+ )
147
+ p_sync.add_argument(
148
+ "--workers",
149
+ type=int,
150
+ default=DEFAULT_WORKERS,
151
+ help="concurrent eth_getLogs requests (default: %(default)s)",
152
+ )
153
+ p_sync.add_argument(
154
+ "--timeout",
155
+ type=float,
156
+ default=3.0,
157
+ help="per-request timeout, seconds (default: %(default)s)",
158
+ )
159
+ p_sync.add_argument(
160
+ "--progress",
161
+ action=argparse.BooleanOptionalAction,
162
+ default=None,
163
+ help="show progress (default: when stderr is a terminal)",
164
+ )
165
+ p_sync.set_defaults(func=cmd_sync)
166
+
167
+ p_status = sub.add_parser("status", help="show checkpoints of the selected events")
168
+ _add_selection(p_status)
169
+ p_status.set_defaults(func=cmd_status)
170
+ return parser
171
+
172
+
173
+ def main(argv: list[str] | None = None) -> int:
174
+ """Entry point; returns the process exit code."""
175
+ args = build_parser().parse_args(argv)
176
+ try:
177
+ return args.func(args)
178
+ except (SelectionError, store.StoreLockedError) as exc:
179
+ print(f"error: {exc}", file=sys.stderr)
180
+ return 2
181
+ except KeyboardInterrupt:
182
+ print("\ninterrupted; progress is checkpointed, rerun to resume", file=sys.stderr)
183
+ return 130
@@ -0,0 +1,159 @@
1
+ """Decode raw ``eth_getLogs`` entries into web3-free, JSON-ready rows.
2
+
3
+ The mechanical part (splitting indexed topics from data, ABI decoding) is plain
4
+ ``eth_abi``. The only bespoke step is attaching names: each event argument is keyed by its
5
+ ABI parameter name, and each struct (``tuple``) value becomes an object keyed by its
6
+ component names, recursively, including inside arrays. There are no enums to map.
7
+
8
+ Value representation in ``args``:
9
+
10
+ - ``address`` -> lowercase ``0x`` hex string;
11
+ - ``bytes`` / ``bytesN`` -> ``0x`` hex string;
12
+ - integers -> exact Python ``int`` (exact JSON integers on disk, however large);
13
+ - ``bool`` and ``string`` -> as-is;
14
+ - arrays -> lists; structs -> dicts;
15
+ - an *indexed* dynamic value (``string``, ``bytes``, arrays, structs) is only present in
16
+ the log as its keccak hash, so it is stored as that 32-byte topic in ``0x`` hex.
17
+
18
+ ABI parameter names are kept verbatim (``batchId``, ``normalisedBalance``). An unnamed
19
+ parameter is keyed by its position, ``"_0"``, ``"_1"``, ...
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ from collections.abc import Mapping, Sequence
25
+ from datetime import UTC, datetime
26
+ from typing import Any
27
+
28
+ from eth_abi import decode as abi_decode
29
+
30
+ from .schema import EventSchema, canonical_type
31
+
32
+
33
+ class DecodeError(ValueError):
34
+ """A log could not be decoded against the schema chosen for it."""
35
+
36
+
37
+ def _hex_to_bytes(value: str) -> bytes:
38
+ """``0x``-prefixed hex string -> bytes."""
39
+ return bytes.fromhex(value[2:] if value.startswith("0x") else value)
40
+
41
+
42
+ def quantity(value: str | int) -> int:
43
+ """A JSON-RPC quantity (hex string or int) as ``int``."""
44
+ return int(value, 16) if isinstance(value, str) else int(value)
45
+
46
+
47
+ def _is_dynamic(param: Mapping[str, Any]) -> bool:
48
+ """Whether an indexed parameter of this type is stored in its topic as a hash.
49
+
50
+ Per the ABI spec, every value type of static size (``uintN``, ``address``, ``bool``,
51
+ ``bytesN``, ...) is stored in its topic directly; ``string``, ``bytes``, arrays and
52
+ structs are stored as ``keccak`` of their encoding.
53
+ """
54
+ typ = param["type"]
55
+ return typ in ("string", "bytes") or typ.endswith("]") or typ.startswith("tuple")
56
+
57
+
58
+ def name_value(param: Mapping[str, Any], value: Any) -> Any:
59
+ """Normalize one ``eth_abi``-decoded value, attaching struct component names.
60
+
61
+ Recurses through arrays (``T[]``, ``T[k]``) and structs, following the ABI
62
+ parameter's ``type`` and ``components``.
63
+ """
64
+ typ = param["type"]
65
+ if typ.endswith("]"):
66
+ element = dict(param)
67
+ element["type"] = typ[: typ.rindex("[")]
68
+ return [name_value(element, v) for v in value]
69
+ if typ == "tuple":
70
+ return {
71
+ (c.get("name") or f"_{i}"): name_value(c, v)
72
+ for i, (c, v) in enumerate(zip(param["components"], value, strict=True))
73
+ }
74
+ if typ == "address":
75
+ return value.lower()
76
+ if typ.startswith("bytes"):
77
+ return "0x" + bytes(value).hex()
78
+ return value
79
+
80
+
81
+ def decode_args(schema: EventSchema, topics: Sequence[str], data: str) -> dict[str, Any]:
82
+ """Decode a log's ``topics[1:]`` and ``data`` into named ``args`` per ``schema``.
83
+
84
+ Raises :class:`DecodeError` when the number of indexed topics does not match the
85
+ schema or ``eth_abi`` rejects the payload.
86
+ """
87
+ indexed = [p for p in schema.inputs if p.get("indexed")]
88
+ plain = [p for p in schema.inputs if not p.get("indexed")]
89
+ if len(topics) - 1 != len(indexed):
90
+ raise DecodeError(
91
+ f"{schema.signature}: expected {len(indexed)} indexed topics, got {len(topics) - 1}"
92
+ )
93
+ try:
94
+ plain_values = abi_decode([canonical_type(p) for p in plain], _hex_to_bytes(data))
95
+ except Exception as exc: # eth_abi raises a family of decoding errors
96
+ raise DecodeError(f"{schema.signature}: {exc}") from exc
97
+
98
+ decoded: dict[int, Any] = {}
99
+ topic_iter = iter(topics[1:])
100
+ plain_iter = iter(plain_values)
101
+ for pos, param in enumerate(schema.inputs):
102
+ if param.get("indexed"):
103
+ topic = next(topic_iter)
104
+ if _is_dynamic(param):
105
+ decoded[pos] = "0x" + _hex_to_bytes(topic).hex()
106
+ else:
107
+ (value,) = abi_decode([canonical_type(param)], _hex_to_bytes(topic))
108
+ decoded[pos] = name_value(param, value)
109
+ else:
110
+ decoded[pos] = name_value(param, next(plain_iter))
111
+ return {(p.get("name") or f"_{i}"): decoded[i] for i, p in enumerate(schema.inputs)}
112
+
113
+
114
+ def block_timestamp(raw_log: Mapping[str, Any]) -> datetime:
115
+ """The UTC block time carried on the log itself (``blockTimestamp``).
116
+
117
+ Part of the current execution-apis Log object and served by mainstream clients; there
118
+ is no fallback lookup. Raises :class:`DecodeError` if the node omitted it.
119
+ """
120
+ value = raw_log.get("blockTimestamp")
121
+ if value is None:
122
+ raise DecodeError("RPC returned a log without blockTimestamp; use a newer node")
123
+ return datetime.fromtimestamp(quantity(value), tz=UTC)
124
+
125
+
126
+ def decode_log(
127
+ raw_log: Mapping[str, Any],
128
+ schemas: Mapping[str, EventSchema],
129
+ *,
130
+ chain_id: int,
131
+ contract: str,
132
+ version: str,
133
+ ) -> dict[str, Any]:
134
+ """Decode one raw log into a store row (see ``docs/data-model.md``).
135
+
136
+ ``schemas`` is the emitting deployment's ``topic0 -> EventSchema`` index, so the
137
+ schema is chosen by ``(address, topic0)``, never by name. Raises :class:`DecodeError`
138
+ for a log whose ``topic0`` is not in the index.
139
+ """
140
+ topics = raw_log["topics"]
141
+ if not topics:
142
+ raise DecodeError("anonymous log (no topics) cannot be decoded")
143
+ schema = schemas.get(topics[0].lower())
144
+ if schema is None:
145
+ raise DecodeError(f"unknown topic0 {topics[0]} for {contract} at {raw_log['address']}")
146
+ return {
147
+ "chain_id": chain_id,
148
+ "contract": contract,
149
+ "version": version,
150
+ "address": raw_log["address"].lower(),
151
+ "event": schema.key,
152
+ "signature": schema.signature,
153
+ "block_number": quantity(raw_log["blockNumber"]),
154
+ "block_timestamp": block_timestamp(raw_log).isoformat().replace("+00:00", "Z"),
155
+ "transaction_hash": raw_log["transactionHash"].lower(),
156
+ "transaction_index": quantity(raw_log["transactionIndex"]),
157
+ "log_index": quantity(raw_log["logIndex"]),
158
+ "args": decode_args(schema, topics, raw_log["data"]),
159
+ }
@@ -0,0 +1,161 @@
1
+ """Sync targets: which deployed contracts (and which of their events) to sync.
2
+
3
+ Deployment data (addresses, deployment blocks, ABIs) comes from the
4
+ ``ethswarm-deployments`` package, read from its shared user-local cache
5
+ (``~/.cache/ethswarm-deployments`` unless ``$ETHSWARM_DEPLOYMENTS_CACHE`` says otherwise),
6
+ so the cache is built once and reused across projects.
7
+
8
+ A :class:`Target` is one deployed contract address. A contract name that was redeployed
9
+ in several releases (``Redistribution``, ``StakeRegistry``, ...) yields one target per
10
+ distinct address; an address carried unchanged across releases (``Token``) yields one.
11
+
12
+ Selection rules of :func:`resolve_targets`, in one sentence: a contract selector picks
13
+ deployments by name, ``name@version`` or address; an event selector then narrows each
14
+ picked deployment to the events it names (dropping deployments that have none of them);
15
+ with no contract selector, every non-token contract is a candidate.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ from collections.abc import Sequence
21
+ from dataclasses import dataclass, field
22
+
23
+ from .schema import EventSchema, event_schemas
24
+
25
+ #: Networks known to ``ethswarm-deployments`` and their EIP-3770 chain short names,
26
+ #: which name the RPC environment variable (``$GNO_RPC_URL``, ``$SEP_RPC_URL``).
27
+ NETWORK_SHORT_NAMES = {"mainnet": "GNO", "testnet": "SEP"}
28
+
29
+ #: ERC-20 contracts excluded when no contract is selected: their ``Transfer`` /
30
+ #: ``Approval`` streams are far larger than the storage-incentives events and are only
31
+ #: synced when asked for by name.
32
+ TOKEN_CONTRACTS = frozenset({"Token", "TestToken"})
33
+
34
+
35
+ @dataclass(frozen=True)
36
+ class Target:
37
+ """One deployed contract to sync.
38
+
39
+ Fields:
40
+ network: ``ethswarm-deployments`` network name (``"mainnet"`` / ``"testnet"``).
41
+ chain_id: EVM chain id of that network.
42
+ contract: Canonical contract name, e.g. ``"Redistribution"``.
43
+ version: First storage-incentives release this address appeared in.
44
+ address: Contract address, lowercase hex.
45
+ start_block: Deployment block; the first block synced.
46
+ schemas: ``topic0 -> EventSchema`` for every event in this deployment's ABI.
47
+ selected: Store keys of the events to sync (a subset of ``schemas``' keys).
48
+ """
49
+
50
+ network: str
51
+ chain_id: int
52
+ contract: str
53
+ version: str
54
+ address: str
55
+ start_block: int
56
+ schemas: dict[str, EventSchema] = field(repr=False)
57
+ selected: frozenset[str]
58
+
59
+ @property
60
+ def label(self) -> str:
61
+ """Human-readable ``Contract@version (0xaddr…)`` label."""
62
+ return f"{self.contract}@{self.version} ({self.address[:10]}…)"
63
+
64
+ def selected_schemas(self) -> list[EventSchema]:
65
+ """The schemas of the selected events, sorted by key."""
66
+ return sorted(
67
+ (s for s in self.schemas.values() if s.key in self.selected), key=lambda s: s.key
68
+ )
69
+
70
+
71
+ class SelectionError(ValueError):
72
+ """A contract or event selector matched nothing."""
73
+
74
+
75
+ def deployment_manager():
76
+ """An ``ethswarm-deployments`` manager over the shared user-local cache."""
77
+ from ethswarm_deployments import DeploymentManager
78
+
79
+ return DeploymentManager(location="user")
80
+
81
+
82
+ def all_targets(network: str = "mainnet", manager=None) -> list[Target]:
83
+ """Every distinct deployment on ``network``, all events selected.
84
+
85
+ Ordered by contract name, then deployment block.
86
+ """
87
+ mgr = manager or deployment_manager()
88
+ chain_id = mgr.network_info(network)["chain_id"]
89
+ names = sorted({c for v in mgr.versions(network) for c in mgr.contract_names(v, network)})
90
+ out: list[Target] = []
91
+ for name in names:
92
+ for d in sorted(mgr.all_deployments(name, network), key=lambda d: d.block):
93
+ schemas = event_schemas(d.abi)
94
+ out.append(
95
+ Target(
96
+ network=network,
97
+ chain_id=chain_id,
98
+ contract=d.name,
99
+ version=d.version,
100
+ address=d.address.lower(),
101
+ start_block=d.block,
102
+ schemas=schemas,
103
+ selected=frozenset(s.key for s in schemas.values()),
104
+ )
105
+ )
106
+ return out
107
+
108
+
109
+ def _matches(target: Target, selector: str) -> bool:
110
+ """Whether a contract selector (``name``, ``name@version`` or address) picks ``target``."""
111
+ if selector.lower().startswith("0x"):
112
+ return target.address == selector.lower()
113
+ name, _, version = selector.partition("@")
114
+ return target.contract == name and (not version or target.version == version)
115
+
116
+
117
+ def _event_keys(target: Target, events: Sequence[str]) -> frozenset[str]:
118
+ """Store keys of ``target`` events matching ``events`` (by name, key or signature)."""
119
+ return frozenset(
120
+ s.key
121
+ for s in target.schemas.values()
122
+ if s.name in events or s.key in events or s.signature in events
123
+ )
124
+
125
+
126
+ def resolve_targets(
127
+ network: str = "mainnet",
128
+ contracts: Sequence[str] = (),
129
+ events: Sequence[str] = (),
130
+ manager=None,
131
+ ) -> list[Target]:
132
+ """Resolve CLI-style selectors into sync targets (rules in the module docstring).
133
+
134
+ Raises :class:`SelectionError` if a contract selector matches no deployment, if an
135
+ event selector matches no event of any candidate, or if nothing is left to sync.
136
+ """
137
+ candidates = all_targets(network, manager)
138
+ if contracts:
139
+ picked: list[Target] = []
140
+ for sel in contracts:
141
+ hits = [t for t in candidates if _matches(t, sel)]
142
+ if not hits:
143
+ raise SelectionError(f"no {network} deployment matches {sel!r}")
144
+ picked.extend(t for t in hits if t not in picked)
145
+ else:
146
+ picked = [t for t in candidates if t.contract not in TOKEN_CONTRACTS]
147
+
148
+ if events:
149
+ for ev in events:
150
+ if not any(_event_keys(t, [ev]) for t in picked):
151
+ raise SelectionError(f"no selected contract declares event {ev!r}")
152
+ narrowed = []
153
+ for t in picked:
154
+ keys = _event_keys(t, events)
155
+ if keys:
156
+ narrowed.append(Target(**{**t.__dict__, "selected": keys}))
157
+ picked = narrowed
158
+
159
+ if not picked:
160
+ raise SelectionError("nothing selected")
161
+ return picked
@@ -0,0 +1,101 @@
1
+ """Read the local cache back as a list of row objects.
2
+
3
+ Loading needs neither web3 nor the deployments package: rows are self-describing and
4
+ the directory layout (``store`` module) is enough to find them. Each event file is read
5
+ only up to its checkpointed size, so loading is consistent while a sync is running and
6
+ never sees a torn line.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import os
12
+ from collections.abc import Iterable, Iterator
13
+ from datetime import datetime
14
+ from typing import Any
15
+
16
+ from . import store
17
+
18
+ #: ``ethswarm-deployments`` network names -> chain ids, for selecting by network.
19
+ NETWORK_CHAIN_IDS = {"mainnet": 100, "testnet": 11155111}
20
+
21
+
22
+ def _as_set(value: str | Iterable[str] | None) -> set[str] | None:
23
+ if value is None:
24
+ return None
25
+ return {value} if isinstance(value, str) else set(value)
26
+
27
+
28
+ def iter_rows(
29
+ contract: str | Iterable[str] | None = None,
30
+ event: str | Iterable[str] | None = None,
31
+ *,
32
+ network: str | int = "mainnet",
33
+ address: str | Iterable[str] | None = None,
34
+ store_dir: str | os.PathLike[str] | None = None,
35
+ parse_timestamps: bool = True,
36
+ ) -> Iterator[dict[str, Any]]:
37
+ """Yield cached rows, file by file, unordered across files.
38
+
39
+ Filters (each ``None`` = no filter; a string or an iterable of strings):
40
+
41
+ - ``contract``: contract name(s), e.g. ``"Redistribution"``;
42
+ - ``event``: event key(s), name or (for overloaded names) full signature;
43
+ - ``address``: emitting contract address(es);
44
+ - ``network``: ``"mainnet"`` / ``"testnet"`` or a chain id.
45
+
46
+ With ``parse_timestamps`` each row's ``block_timestamp`` is a timezone-aware UTC
47
+ :class:`~datetime.datetime`; otherwise the ISO 8601 string stored on disk.
48
+ """
49
+ chain_id = NETWORK_CHAIN_IDS.get(network, network) if isinstance(network, str) else network
50
+ chain_dir = store.resolve_store_dir(store_dir) / str(chain_id)
51
+ contracts, events = _as_set(contract), _as_set(event)
52
+ addresses = {a.lower() for a in _as_set(address) or ()} or None
53
+ if not chain_dir.is_dir():
54
+ return
55
+ for dep_dir in sorted(p for p in chain_dir.iterdir() if p.is_dir()):
56
+ name, _, addr = dep_dir.name.rpartition("_")
57
+ if contracts is not None and name not in contracts:
58
+ continue
59
+ if addresses is not None and addr not in addresses:
60
+ continue
61
+ for key, cp in sorted(store.load_checkpoints(dep_dir).items()):
62
+ if events is not None and key not in events:
63
+ continue
64
+ path = store.event_path(dep_dir, key)
65
+ if not path.exists():
66
+ continue
67
+ for row in store.iter_event_file(path, limit=cp.size):
68
+ if parse_timestamps:
69
+ row["block_timestamp"] = datetime.fromisoformat(
70
+ row["block_timestamp"].replace("Z", "+00:00")
71
+ )
72
+ yield row
73
+
74
+
75
+ def load(
76
+ contract: str | Iterable[str] | None = None,
77
+ event: str | Iterable[str] | None = None,
78
+ *,
79
+ network: str | int = "mainnet",
80
+ address: str | Iterable[str] | None = None,
81
+ store_dir: str | os.PathLike[str] | None = None,
82
+ parse_timestamps: bool = True,
83
+ ) -> list[dict[str, Any]]:
84
+ """Load cached rows as a list in chain order.
85
+
86
+ Same filters as :func:`iter_rows`. Rows are sorted by
87
+ ``(block_number, log_index, address)``, which is chain order across every contract
88
+ and event loaded (the address tie-break only matters across chains, never within one).
89
+ """
90
+ rows = list(
91
+ iter_rows(
92
+ contract,
93
+ event,
94
+ network=network,
95
+ address=address,
96
+ store_dir=store_dir,
97
+ parse_timestamps=parse_timestamps,
98
+ )
99
+ )
100
+ rows.sort(key=lambda r: (r["block_number"], r["log_index"], r["address"]))
101
+ return rows
@@ -0,0 +1,150 @@
1
+ """Minimal JSON-RPC transport for log acquisition.
2
+
3
+ :class:`RpcClient` is the protocol the sync engine depends on; tests substitute an
4
+ in-memory fake. :class:`HttpRpcClient` is the production implementation, tuned for hosted
5
+ endpoints where some requests hang: a short per-request timeout, immediate retry on
6
+ timeout or connection failure, and one keep-alive HTTPS session per thread (the sync
7
+ engine fetches block ranges from a thread pool).
8
+
9
+ A node that rejects a ``eth_getLogs`` because the range or result set is too large raises
10
+ :class:`RangeTooLargeError`, which the sync engine answers by splitting the range.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import itertools
16
+ import threading
17
+ import time
18
+ from typing import Any, Protocol
19
+
20
+ import requests
21
+
22
+
23
+ class RpcError(RuntimeError):
24
+ """The node returned a JSON-RPC error, or retries were exhausted."""
25
+
26
+
27
+ class RangeTooLargeError(RpcError):
28
+ """``eth_getLogs`` was refused because the block range or result was too large."""
29
+
30
+
31
+ #: Lowercased substrings of node error messages that mean "narrow the range and retry".
32
+ _RANGE_ERROR_HINTS = (
33
+ "range",
34
+ "too many",
35
+ "limit exceeded",
36
+ "query returned more than",
37
+ "response size",
38
+ "max results",
39
+ "blocks without the log index",
40
+ )
41
+
42
+
43
+ class RpcClient(Protocol):
44
+ """The eth JSON-RPC surface the sync engine needs."""
45
+
46
+ def finalized_block(self) -> int:
47
+ """Number of the chain's ``finalized`` block."""
48
+ ...
49
+
50
+ def get_logs(
51
+ self, *, address: str, topics: list[Any] | None, from_block: int, to_block: int
52
+ ) -> list[dict[str, Any]]:
53
+ """Raw logs for ``[from_block, to_block]`` (inclusive) emitted by ``address``."""
54
+ ...
55
+
56
+
57
+ class HttpRpcClient:
58
+ """:class:`RpcClient` over HTTP(S) JSON-RPC.
59
+
60
+ Args:
61
+ url: Endpoint URL.
62
+ timeout: Per-request timeout in seconds. Kept short; a hung request is abandoned
63
+ and retried immediately rather than waited on.
64
+ max_attempts: Attempts per call before giving up with :class:`RpcError`.
65
+ split_after_timeouts: Consecutive timeouts after which a multi-block
66
+ ``eth_getLogs`` is reported as :class:`RangeTooLargeError`, so the sync engine
67
+ bisects it. Some nodes are consistently slower than ``timeout`` on dense or
68
+ uncached ranges; retrying the same range forever would never succeed.
69
+ """
70
+
71
+ def __init__(
72
+ self,
73
+ url: str,
74
+ *,
75
+ timeout: float = 3.0,
76
+ max_attempts: int = 8,
77
+ split_after_timeouts: int = 3,
78
+ ) -> None:
79
+ self.url = url
80
+ self.timeout = timeout
81
+ self.max_attempts = max_attempts
82
+ self.split_after_timeouts = split_after_timeouts
83
+ self._local = threading.local()
84
+ self._ids = itertools.count(1)
85
+
86
+ def _session(self) -> requests.Session:
87
+ session = getattr(self._local, "session", None)
88
+ if session is None:
89
+ session = requests.Session()
90
+ session.headers["Content-Type"] = "application/json"
91
+ self._local.session = session
92
+ return session
93
+
94
+ def call(self, method: str, params: list[Any], *, splittable: bool = False) -> Any:
95
+ """One JSON-RPC call with retry.
96
+
97
+ Timeouts and connection errors are retried immediately; HTTP 429/5xx and
98
+ non-range JSON-RPC errors are retried with a short linear backoff. A range error
99
+ is raised at once as :class:`RangeTooLargeError`, and so are
100
+ ``split_after_timeouts`` timeouts in a row when ``splittable``.
101
+ """
102
+ last: Exception | None = None
103
+ timeouts = 0
104
+ for attempt in range(self.max_attempts):
105
+ body = {"jsonrpc": "2.0", "id": next(self._ids), "method": method, "params": params}
106
+ try:
107
+ resp = self._session().post(self.url, json=body, timeout=self.timeout)
108
+ except (requests.Timeout, requests.ConnectionError) as exc:
109
+ last = exc
110
+ self._local.session = None # drop a possibly wedged connection
111
+ if isinstance(exc, requests.Timeout):
112
+ timeouts += 1
113
+ if splittable and timeouts >= self.split_after_timeouts:
114
+ raise RangeTooLargeError(f"{method} timed out {timeouts} times") from exc
115
+ continue
116
+ if resp.status_code == 429 or resp.status_code >= 500:
117
+ last = RpcError(f"HTTP {resp.status_code}")
118
+ time.sleep(0.5 * (attempt + 1))
119
+ continue
120
+ try:
121
+ payload = resp.json()
122
+ except ValueError as exc:
123
+ last = RpcError(f"non-JSON response (HTTP {resp.status_code})")
124
+ last.__cause__ = exc
125
+ time.sleep(0.5 * (attempt + 1))
126
+ continue
127
+ err = payload.get("error")
128
+ if err is None:
129
+ return payload["result"]
130
+ message = str(err.get("message", err))
131
+ if any(h in message.lower() for h in _RANGE_ERROR_HINTS):
132
+ raise RangeTooLargeError(message)
133
+ last = RpcError(f"{method}: {message}")
134
+ time.sleep(0.5 * (attempt + 1))
135
+ raise RpcError(f"{method} failed after {self.max_attempts} attempts: {last}")
136
+
137
+ def finalized_block(self) -> int:
138
+ return int(self.call("eth_getBlockByNumber", ["finalized", False])["number"], 16)
139
+
140
+ def get_logs(
141
+ self, *, address: str, topics: list[Any] | None, from_block: int, to_block: int
142
+ ) -> list[dict[str, Any]]:
143
+ flt: dict[str, Any] = {
144
+ "address": address,
145
+ "fromBlock": hex(from_block),
146
+ "toBlock": hex(to_block),
147
+ }
148
+ if topics is not None:
149
+ flt["topics"] = topics
150
+ return self.call("eth_getLogs", [flt], splittable=to_block > from_block)
@@ -0,0 +1,89 @@
1
+ """Event schemas derived from a contract ABI.
2
+
3
+ An :class:`EventSchema` is everything needed to recognise and decode one event emitted by
4
+ one deployed contract: its name, canonical signature, ``topic0`` and ABI inputs (including
5
+ struct ``components``). Schemas are always taken from the ABI of the *specific deployment*
6
+ that emitted the log, never looked up by event name alone. This is what disambiguates
7
+ events that share a name across contracts (``Paused``, ``RoleGranted``, ``PriceUpdate``)
8
+ or across versions of one contract (``StakeUpdated`` has three different signatures;
9
+ ``WinnerSelected``'s struct field order changed in v0.6.0).
10
+
11
+ The *file key* of an event (:attr:`EventSchema.key`) is its bare name, unless the ABI
12
+ overloads that name, in which case it is the full signature. Within one deployment the
13
+ key is therefore unique, and it names the event's JSONLines file in the store.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from collections.abc import Iterable, Mapping
19
+ from dataclasses import dataclass
20
+ from typing import Any
21
+
22
+ from eth_hash.auto import keccak
23
+
24
+
25
+ def canonical_type(param: Mapping[str, Any]) -> str:
26
+ """The canonical ABI type string of one parameter.
27
+
28
+ Tuples are expanded recursively into ``(t1,t2,...)`` form, keeping any array suffix:
29
+ a ``tuple[]`` whose components are ``address`` and ``uint256`` becomes
30
+ ``(address,uint256)[]``. This form serves both as the signature fragment hashed into
31
+ ``topic0`` and as the type string handed to ``eth_abi``.
32
+ """
33
+ typ = param["type"]
34
+ if typ.startswith("tuple"):
35
+ inner = ",".join(canonical_type(c) for c in param["components"])
36
+ return f"({inner}){typ[len('tuple') :]}"
37
+ return typ
38
+
39
+
40
+ @dataclass(frozen=True)
41
+ class EventSchema:
42
+ """The decode schema for one event of one deployed contract.
43
+
44
+ Fields:
45
+ name: Event name as declared in the ABI, e.g. ``"Committed"``.
46
+ signature: Canonical signature, e.g. ``"Committed(uint256,bytes32,uint8)"``.
47
+ topic0: ``keccak(signature)`` as ``0x``-prefixed lowercase hex.
48
+ inputs: The ABI ``inputs`` list, verbatim (names, types, ``indexed`` flags,
49
+ struct ``components``).
50
+ key: Store key, unique within a deployment (see module docstring).
51
+ """
52
+
53
+ name: str
54
+ signature: str
55
+ topic0: str
56
+ inputs: tuple[Mapping[str, Any], ...]
57
+ key: str
58
+
59
+ @staticmethod
60
+ def from_abi(entry: Mapping[str, Any], key: str | None = None) -> EventSchema:
61
+ """Build a schema from one ABI ``event`` entry; ``key`` defaults to the name."""
62
+ types = ",".join(canonical_type(i) for i in entry["inputs"])
63
+ signature = f"{entry['name']}({types})"
64
+ return EventSchema(
65
+ name=entry["name"],
66
+ signature=signature,
67
+ topic0="0x" + keccak(signature.encode()).hex(),
68
+ inputs=tuple(entry["inputs"]),
69
+ key=key or entry["name"],
70
+ )
71
+
72
+
73
+ def event_schemas(abi: Iterable[Mapping[str, Any]]) -> dict[str, EventSchema]:
74
+ """All non-anonymous events of an ABI, keyed by ``topic0``.
75
+
76
+ Anonymous events carry no ``topic0`` and cannot be recognised from a log, so they are
77
+ omitted (the Swarm contracts declare none). Overloaded names get signature keys.
78
+ """
79
+ events = [e for e in abi if e.get("type") == "event" and not e.get("anonymous", False)]
80
+ counts: dict[str, int] = {}
81
+ for e in events:
82
+ counts[e["name"]] = counts.get(e["name"], 0) + 1
83
+ out: dict[str, EventSchema] = {}
84
+ for e in events:
85
+ schema = EventSchema.from_abi(e)
86
+ if counts[e["name"]] > 1:
87
+ schema = EventSchema.from_abi(e, key=schema.signature)
88
+ out[schema.topic0] = schema
89
+ return out
@@ -0,0 +1,174 @@
1
+ """The JSONLines event cache and its per-event checkpoints.
2
+
3
+ Layout (see ``docs/data-model.md``)::
4
+
5
+ <store-dir>/
6
+ <chain_id>/
7
+ <Contract>_<address>/ one directory per deployed contract
8
+ <event-key>.jsonl one append-only file per event; one row per line
9
+ head.json {"events": {<event-key>: {"block": N, "size": B}}}
10
+
11
+ The checkpoint of an event records the last block synced (inclusive) *and* the byte size
12
+ of its ``.jsonl`` file at that point. Rows are appended and flushed to disk before the
13
+ checkpoint is atomically replaced, so after any interruption the file holds a valid
14
+ prefix of exactly ``size`` bytes plus, possibly, a tail written after the last checkpoint
15
+ (including a torn final line). :func:`rewind` truncates that tail before a sync resumes,
16
+ which makes the on-disk log exactly-once: no duplicates and no partial lines. A ``.jsonl``
17
+ file with no checkpoint is a tail in its entirety and is truncated to empty.
18
+
19
+ The store is a cache, reconstructible from chain: deleting a deployment directory just
20
+ makes the next sync start again from the deployment block.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import fcntl
26
+ import json
27
+ import os
28
+ from collections.abc import Iterable, Iterator
29
+ from contextlib import contextmanager
30
+ from dataclasses import dataclass
31
+ from pathlib import Path
32
+ from typing import Any
33
+
34
+ #: Environment variable overriding the default store location.
35
+ STORE_DIR_ENV = "ETHSWARM_CHAIN_SYNC_STORE"
36
+ APP_DIR_NAME = "ethswarm-chain-sync"
37
+ HEAD_FILENAME = "head.json"
38
+ LOCK_FILENAME = ".lock"
39
+
40
+
41
+ class StoreLockedError(RuntimeError):
42
+ """Another process is already syncing this deployment directory."""
43
+
44
+
45
+ class StoreCorruptError(RuntimeError):
46
+ """A ``.jsonl`` file is shorter than its checkpoint says; the cache must be rebuilt."""
47
+
48
+
49
+ @dataclass(frozen=True)
50
+ class Checkpoint:
51
+ """Sync progress of one event of one deployment.
52
+
53
+ Fields:
54
+ block: Last block synced, inclusive.
55
+ size: Byte length of the event's ``.jsonl`` file once that block was synced.
56
+ """
57
+
58
+ block: int
59
+ size: int
60
+
61
+
62
+ def default_store_dir() -> Path:
63
+ """``$XDG_CACHE_HOME/ethswarm-chain-sync``, else ``~/.cache/ethswarm-chain-sync``."""
64
+ xdg = os.environ.get("XDG_CACHE_HOME")
65
+ return (Path(xdg) if xdg else Path.home() / ".cache") / APP_DIR_NAME
66
+
67
+
68
+ def resolve_store_dir(explicit: str | os.PathLike[str] | None = None) -> Path:
69
+ """Store directory by precedence: ``explicit`` > ``$ETHSWARM_CHAIN_SYNC_STORE`` > default."""
70
+ if explicit is not None:
71
+ return Path(explicit)
72
+ env = os.environ.get(STORE_DIR_ENV)
73
+ return Path(env) if env else default_store_dir()
74
+
75
+
76
+ def deployment_dir(
77
+ store_dir: str | os.PathLike[str], chain_id: int, contract: str, address: str
78
+ ) -> Path:
79
+ """``<store-dir>/<chain_id>/<Contract>_<address>``."""
80
+ return Path(store_dir) / str(chain_id) / f"{contract}_{address.lower()}"
81
+
82
+
83
+ def event_path(dep_dir: Path, key: str) -> Path:
84
+ """The ``.jsonl`` file for one event key."""
85
+ return dep_dir / f"{key}.jsonl"
86
+
87
+
88
+ @contextmanager
89
+ def locked(dep_dir: Path) -> Iterator[None]:
90
+ """Hold an exclusive, non-blocking ``flock`` on a deployment directory.
91
+
92
+ Two writers on one directory would interleave appends and checkpoints, so a sync
93
+ takes this lock for the whole of its run. Raises :class:`StoreLockedError` at once if
94
+ another process holds it. Readers do not lock.
95
+ """
96
+ dep_dir.mkdir(parents=True, exist_ok=True)
97
+ with (dep_dir / LOCK_FILENAME).open("a") as fh:
98
+ try:
99
+ fcntl.flock(fh, fcntl.LOCK_EX | fcntl.LOCK_NB)
100
+ except BlockingIOError as exc:
101
+ raise StoreLockedError(f"{dep_dir} is being synced by another process") from exc
102
+ try:
103
+ yield
104
+ finally:
105
+ fcntl.flock(fh, fcntl.LOCK_UN)
106
+
107
+
108
+ def load_checkpoints(dep_dir: Path) -> dict[str, Checkpoint]:
109
+ """All event checkpoints of a deployment (empty if never synced)."""
110
+ path = dep_dir / HEAD_FILENAME
111
+ if not path.is_file():
112
+ return {}
113
+ raw = json.loads(path.read_text(encoding="utf-8"))["events"]
114
+ return {k: Checkpoint(block=v["block"], size=v["size"]) for k, v in raw.items()}
115
+
116
+
117
+ def save_checkpoints(dep_dir: Path, checkpoints: dict[str, Checkpoint]) -> None:
118
+ """Atomically replace a deployment's ``head.json``."""
119
+ dep_dir.mkdir(parents=True, exist_ok=True)
120
+ body = {
121
+ "events": {k: {"block": c.block, "size": c.size} for k, c in sorted(checkpoints.items())}
122
+ }
123
+ tmp = dep_dir / (HEAD_FILENAME + ".tmp")
124
+ tmp.write_text(json.dumps(body, indent=1) + "\n", encoding="utf-8")
125
+ os.replace(tmp, dep_dir / HEAD_FILENAME)
126
+
127
+
128
+ def rewind(dep_dir: Path, key: str, checkpoint: Checkpoint | None) -> int:
129
+ """Truncate an event file back to its checkpoint; return the resulting size.
130
+
131
+ Raises :class:`StoreCorruptError` if the file is shorter than the checkpoint, which
132
+ can only happen if the file was modified outside this package.
133
+ """
134
+ path = event_path(dep_dir, key)
135
+ want = checkpoint.size if checkpoint else 0
136
+ if not path.exists():
137
+ if want:
138
+ raise StoreCorruptError(f"{path} is missing but its checkpoint says {want} bytes")
139
+ return 0
140
+ have = path.stat().st_size
141
+ if have < want:
142
+ raise StoreCorruptError(
143
+ f"{path} has {have} bytes, checkpoint says {want}; delete {dep_dir} and resync"
144
+ )
145
+ if have > want:
146
+ with path.open("r+b") as fh:
147
+ fh.truncate(want)
148
+ return want
149
+
150
+
151
+ def append_rows(dep_dir: Path, key: str, rows: Iterable[dict[str, Any]]) -> int:
152
+ """Append rows to an event file, flush them to stable storage, return the new size."""
153
+ dep_dir.mkdir(parents=True, exist_ok=True)
154
+ path = event_path(dep_dir, key)
155
+ payload = "".join(json.dumps(r, separators=(",", ":")) + "\n" for r in rows).encode()
156
+ with path.open("ab") as fh:
157
+ if payload:
158
+ fh.write(payload)
159
+ fh.flush()
160
+ os.fsync(fh.fileno())
161
+ return fh.tell()
162
+
163
+
164
+ def iter_event_file(path: Path, limit: int | None = None) -> Iterator[dict[str, Any]]:
165
+ """Rows of one ``.jsonl`` file, reading at most ``limit`` bytes when given.
166
+
167
+ Reading only up to the checkpointed size makes loading safe while a sync is
168
+ appending to the same file.
169
+ """
170
+ with path.open("rb") as fh:
171
+ data = fh.read() if limit is None else fh.read(limit)
172
+ for line in data.splitlines():
173
+ if line.strip():
174
+ yield json.loads(line)
@@ -0,0 +1,187 @@
1
+ """The acquisition engine: fetch, decode and checkpoint one deployment's events.
2
+
3
+ Contract of :func:`sync_target`:
4
+
5
+ - **Range.** Each selected event is synced over ``(checkpoint, to_block]``, or
6
+ ``[start_block, to_block]`` if it has no checkpoint. ``to_block`` is normally the
7
+ chain's ``finalized`` block, so nothing synced can be reorged away and there is no
8
+ reorg handling.
9
+ - **Grouping.** Selected events that resume from the same block are fetched together
10
+ with one topic-filtered ``eth_getLogs`` per block range (``topics=[[t0, t1, …]]``).
11
+ After one complete sync every event of a deployment shares a checkpoint, so the
12
+ steady state is a single group.
13
+ - **Ordering and resumability.** Block ranges are fetched concurrently but committed
14
+ strictly in ascending order: a range's rows are appended and flushed, then the group's
15
+ checkpoints are advanced to the range's end. Interrupting at any point therefore loses
16
+ at most the uncommitted ranges, and the next run :func:`~ethswarm_chain_sync.store.rewind`\\ s
17
+ any uncheckpointed tail and resumes. An interrupted-then-resumed sync produces a store
18
+ byte-identical to an uninterrupted one.
19
+ - **Range splitting.** A range the node refuses as too large is bisected until it is
20
+ accepted (a single-block refusal is an error).
21
+ - **Exclusivity.** A sync holds an exclusive lock on the deployment directory; a second
22
+ concurrent sync of the same deployment fails immediately with
23
+ :class:`~ethswarm_chain_sync.store.StoreLockedError`.
24
+ - **Strictness.** A log that cannot be decoded against the deployment's own ABI aborts
25
+ the sync before anything from its range is written.
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ from collections import deque
31
+ from collections.abc import Callable, Iterator
32
+ from concurrent.futures import Future, ThreadPoolExecutor
33
+ from dataclasses import dataclass
34
+ from pathlib import Path
35
+ from typing import Any
36
+
37
+ from . import store
38
+ from .decode import decode_log, quantity
39
+ from .deployments import Target
40
+ from .rpc import RangeTooLargeError, RpcClient
41
+
42
+ #: Default blocks per ``eth_getLogs`` (inclusive span); 10,000 is a common node cap.
43
+ DEFAULT_CHUNK_SIZE = 10_000
44
+ DEFAULT_WORKERS = 32
45
+
46
+ #: ``progress(target, block_reached, to_block, rows_written_so_far)``
47
+ ProgressFn = Callable[[Target, int, int, int], None]
48
+
49
+
50
+ @dataclass
51
+ class SyncResult:
52
+ """Outcome of syncing one target.
53
+
54
+ Fields:
55
+ target: The target synced.
56
+ to_block: The block every selected event is now synced to.
57
+ rows: Rows appended per event key during this run.
58
+ """
59
+
60
+ target: Target
61
+ to_block: int
62
+ rows: dict[str, int]
63
+
64
+
65
+ def block_ranges(start: int, end: int, size: int) -> Iterator[tuple[int, int]]:
66
+ """Inclusive ``(a, b)`` ranges of at most ``size`` blocks covering ``[start, end]``."""
67
+ a = start
68
+ while a <= end:
69
+ b = min(a + size - 1, end)
70
+ yield a, b
71
+ a = b + 1
72
+
73
+
74
+ def fetch_range(
75
+ rpc: RpcClient, address: str, topics: list[Any], a: int, b: int
76
+ ) -> list[dict[str, Any]]:
77
+ """All logs in ``[a, b]``, bisecting the range whenever the node refuses it as too large."""
78
+ try:
79
+ return rpc.get_logs(address=address, topics=topics, from_block=a, to_block=b)
80
+ except RangeTooLargeError:
81
+ if a == b:
82
+ raise
83
+ mid = (a + b) // 2
84
+ return fetch_range(rpc, address, topics, a, mid) + fetch_range(
85
+ rpc, address, topics, mid + 1, b
86
+ )
87
+
88
+
89
+ def _ordered_fetch(
90
+ rpc: RpcClient,
91
+ address: str,
92
+ topics: list[Any],
93
+ ranges: Iterator[tuple[int, int]],
94
+ workers: int,
95
+ ) -> Iterator[tuple[int, int, list[dict[str, Any]]]]:
96
+ """Fetch ranges on a thread pool, yielding ``(a, b, logs)`` in ascending range order.
97
+
98
+ At most ``2 * workers`` ranges are in flight. On early exit (exception, interrupt or
99
+ the consumer stopping) queued fetches are cancelled.
100
+ """
101
+ pool = ThreadPoolExecutor(max_workers=workers, thread_name_prefix="getlogs")
102
+ pending: deque[tuple[int, int, Future]] = deque()
103
+
104
+ def submit_next() -> None:
105
+ nxt = next(ranges, None)
106
+ if nxt is not None:
107
+ pending.append((*nxt, pool.submit(fetch_range, rpc, address, topics, *nxt)))
108
+
109
+ try:
110
+ for _ in range(2 * workers):
111
+ submit_next()
112
+ while pending:
113
+ a, b, fut = pending.popleft()
114
+ logs = fut.result()
115
+ submit_next()
116
+ yield a, b, logs
117
+ finally:
118
+ pool.shutdown(wait=False, cancel_futures=True)
119
+
120
+
121
+ def sync_target(
122
+ rpc: RpcClient,
123
+ store_dir: str | Path,
124
+ target: Target,
125
+ *,
126
+ to_block: int,
127
+ chunk_size: int = DEFAULT_CHUNK_SIZE,
128
+ workers: int = DEFAULT_WORKERS,
129
+ progress: ProgressFn | None = None,
130
+ ) -> SyncResult:
131
+ """Sync ``target``'s selected events up to ``to_block`` (contract in module docstring)."""
132
+ dep_dir = store.deployment_dir(store_dir, target.chain_id, target.contract, target.address)
133
+ with store.locked(dep_dir):
134
+ return _sync_locked(rpc, dep_dir, target, to_block, chunk_size, workers, progress)
135
+
136
+
137
+ def _sync_locked(
138
+ rpc: RpcClient,
139
+ dep_dir: Path,
140
+ target: Target,
141
+ to_block: int,
142
+ chunk_size: int,
143
+ workers: int,
144
+ progress: ProgressFn | None,
145
+ ) -> SyncResult:
146
+ """Body of :func:`sync_target`, run while holding the deployment directory lock."""
147
+ checkpoints = store.load_checkpoints(dep_dir)
148
+ sizes: dict[str, int] = {}
149
+ groups: dict[int, list[str]] = {}
150
+ for schema in target.selected_schemas():
151
+ cp = checkpoints.get(schema.key)
152
+ sizes[schema.key] = store.rewind(dep_dir, schema.key, cp)
153
+ start = cp.block + 1 if cp else target.start_block
154
+ groups.setdefault(start, []).append(schema.key)
155
+
156
+ by_key = {s.key: s for s in target.schemas.values()}
157
+ written = {k: 0 for k in sizes}
158
+ for start in sorted(groups):
159
+ keys = groups[start]
160
+ if start > to_block:
161
+ continue
162
+ topics = [[by_key[k].topic0 for k in keys]]
163
+ ranges = block_ranges(start, to_block, chunk_size)
164
+ for _, b, logs in _ordered_fetch(rpc, target.address, topics, ranges, workers):
165
+ rows_by_key: dict[str, list[dict[str, Any]]] = {k: [] for k in keys}
166
+ logs = [log for log in logs if not log.get("removed", False)]
167
+ logs.sort(key=lambda log: (quantity(log["blockNumber"]), quantity(log["logIndex"])))
168
+ for log in logs:
169
+ row = decode_log(
170
+ log,
171
+ target.schemas,
172
+ chain_id=target.chain_id,
173
+ contract=target.contract,
174
+ version=target.version,
175
+ )
176
+ if row["address"] != target.address or row["event"] not in rows_by_key:
177
+ raise ValueError(f"node returned an unrequested log: {log}")
178
+ rows_by_key[row["event"]].append(row)
179
+ for k, rows in rows_by_key.items():
180
+ if rows:
181
+ sizes[k] = store.append_rows(dep_dir, k, rows)
182
+ written[k] += len(rows)
183
+ checkpoints[k] = store.Checkpoint(block=b, size=sizes[k])
184
+ store.save_checkpoints(dep_dir, checkpoints)
185
+ if progress is not None:
186
+ progress(target, b, to_block, sum(written.values()))
187
+ return SyncResult(target=target, to_block=to_block, rows=written)
@@ -0,0 +1,76 @@
1
+ Metadata-Version: 2.5
2
+ Name: ethswarm-chain-sync
3
+ Version: 0.1.0
4
+ Summary: Sync Swarm storage-incentives contract events into a local JSONLines cache
5
+ Requires-Python: >=3.11
6
+ Requires-Dist: eth-abi>=5
7
+ Requires-Dist: eth-hash[pycryptodome]>=0.7
8
+ Requires-Dist: ethswarm-deployments
9
+ Requires-Dist: requests>=2.31
10
+ Description-Content-Type: text/markdown
11
+
12
+ # ethswarm-chain-sync data model
13
+
14
+ ethswarm-chain-sync syncs events emitted by the Swarm storage-incentives contracts (every deployed version, on Gnosis "mainnet" and Sepolia "testnet") into a local JSONLines cache, and loads that cache back as a list of objects. It follows the acquisition layer of the VolumeRegistry indexer (`swarm-volume-registry/services/indexer`): a finalized-only, event-sourced log cache, partitioned per event type, with web3 confined to the acquisition and decode step. It has no projector.
15
+
16
+ ## Sources
17
+
18
+ Deployments (address, deployment block, ABI) come from the `ethswarm-deployments` package's user-local cache. A sync target is one distinct contract address. Each target's event schemas come from that address's own ABI, so a log is decoded by `(address, topic0)`, never by event name alone. This disambiguates names shared across contracts (`Paused`, `RoleGranted`, `PriceUpdate`) and across versions of one contract (`StakeUpdated` has three signatures; the field order of the `WinnerSelected` struct changed in v0.6.0).
19
+
20
+ Acquisition reads `eth_getLogs` up to the chain's `finalized` block only, so the cache never needs reorg handling.
21
+
22
+ ## Row
23
+
24
+ One row per log:
25
+
26
+ | field | type | meaning |
27
+ |---|---|---|
28
+ | `chain_id` | int | 100 (Gnosis) or 11155111 (Sepolia) |
29
+ | `contract` | str | canonical contract name, e.g. `Redistribution` |
30
+ | `version` | str | first storage-incentives release containing this address |
31
+ | `address` | str | emitting contract, lowercase hex |
32
+ | `event` | str | event key: the event name, or its full signature if the ABI overloads the name |
33
+ | `signature` | str | canonical signature, e.g. `Committed(uint256,bytes32,uint8)` |
34
+ | `block_number` | int | |
35
+ | `block_timestamp` | str | UTC ISO 8601 (`...Z`), from the log's `blockTimestamp`; `load()` returns a timezone-aware `datetime` |
36
+ | `transaction_hash` | str | lowercase hex |
37
+ | `transaction_index` | int | |
38
+ | `log_index` | int | `(block_number, log_index)` is chain order |
39
+ | `args` | object | decoded event arguments keyed by ABI parameter name |
40
+
41
+ Decoding of `args` is plain ABI decoding, with names attached. Addresses are lowercase hex, `bytes`/`bytesN` are `0x` hex, integers are exact JSON integers (uint256 values are not rounded), and structs are objects keyed by component name, recursively and inside arrays. An indexed dynamic value (string, bytes, array, struct) only appears in the log as its keccak hash, and is stored as that hash. The Swarm contracts have no enums, so no value mapping is applied.
42
+
43
+ ## On disk
44
+
45
+ ```
46
+ <store-dir>/ --store-dir, $ETHSWARM_CHAIN_SYNC_STORE, or ~/.cache/ethswarm-chain-sync
47
+ <chain_id>/
48
+ <Contract>_<address>/ one directory per deployed contract
49
+ <event>.jsonl one append-only file per event, rows in chain order
50
+ head.json {"events": {"<event>": {"block": N, "size": B}}}
51
+ ```
52
+
53
+ Each event has its own checkpoint: the last block synced (inclusive) and the byte size of its file at that block. Syncing a subset of events and later a superset therefore works, and each event resumes from its own checkpoint. On first sync an event starts at the contract's deployment block.
54
+
55
+ Each block range is appended and fsynced before `head.json` is atomically replaced. A sync that is interrupted at any point leaves each file as its checkpointed prefix plus, possibly, an uncheckpointed tail, which may include a torn final line. The next sync truncates each file back to its checkpointed size before resuming, so the files are exactly-once (no duplicate or partial rows), and an interrupted and resumed sync produces the same bytes as an uninterrupted one. The loader reads each file only up to its checkpointed size, so it is safe to load while a sync is running.
56
+
57
+ The store is a cache. Deleting a contract's directory makes the next sync rebuild it from the deployment block.
58
+
59
+ ## Usage
60
+
61
+ ```
62
+ ethswarm-chain-sync sync # all non-token contracts, mainnet
63
+ ethswarm-chain-sync sync -c PostageStamp -e BatchCreated # one event, every PostageStamp deployment
64
+ ethswarm-chain-sync sync -c Redistribution@v0.9.4 # one deployment
65
+ ethswarm-chain-sync sync -n testnet -c 0x... # by address, on Sepolia
66
+ ethswarm-chain-sync status -c StakeRegistry # checkpoints, no RPC
67
+ ```
68
+
69
+ The RPC endpoint is `--rpc-url`, else `$GNO_RPC_URL` (mainnet) or `$SEP_RPC_URL` (testnet). `Token`/`TestToken` are only synced when named with `-c`.
70
+
71
+ ```python
72
+ import ethswarm_chain_sync as ecs
73
+
74
+ rows = ecs.load("PostageStamp", "BatchCreated") # list[dict], chain order
75
+ rows = ecs.load(event=["Committed", "Revealed"], network="testnet")
76
+ ```
@@ -0,0 +1,14 @@
1
+ ethswarm_chain_sync/README.md,sha256=iEC8fAq1XO0SzAdZhbwAVmxOQK2sup2a0JR9oBrlV28,1005
2
+ ethswarm_chain_sync/__init__.py,sha256=7vOtZiv16MI5SazDK3lXjPRwl7h9ixmVhZ1o9iR5CN8,914
3
+ ethswarm_chain_sync/cli.py,sha256=emNVHsdcLXIGPAwods1zB_7yxsT4DofJL4ApYYj67bo,6772
4
+ ethswarm_chain_sync/decode.py,sha256=NSwCrPG6BiRwkng5AHZlbgH8XEUKeKJb-tdzIY5aOgc,6386
5
+ ethswarm_chain_sync/deployments.py,sha256=5uo6F66lCg2caxUOgDuGiJlxUq8A-7K4YKe8huxFQgc,6268
6
+ ethswarm_chain_sync/load.py,sha256=FS_WrUYbDmm4cXMr0c7pe6VURFF54Oen6UaWTHk1f4s,3831
7
+ ethswarm_chain_sync/rpc.py,sha256=nqFtwfyLTmZ0kDA-5iyy67xkwkBqUHZNhbM6by_gFJQ,5828
8
+ ethswarm_chain_sync/schema.py,sha256=HJv33qCklYsLsHRbBMkFgbMzRWLixJa5Ef_xb4WVjZo,3689
9
+ ethswarm_chain_sync/store.py,sha256=nTqZyQBFNORTrsJnnOaou8tIRhbuuqU61pADzNxHrMY,6508
10
+ ethswarm_chain_sync/sync.py,sha256=UklPG_k-xV7yuTtZCrSlFjvdxeGyvtxKjpxVgYcxIho,7345
11
+ ethswarm_chain_sync-0.1.0.dist-info/METADATA,sha256=9Ayzy8ji-hyBlsBlXet7JUPxO10llvn06KhhAz2MTzs,5082
12
+ ethswarm_chain_sync-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
13
+ ethswarm_chain_sync-0.1.0.dist-info/entry_points.txt,sha256=rVs9hhKYVpymRT03sOaIMWU9DAyKCkI4Gmv4dJr0OTg,69
14
+ ethswarm_chain_sync-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ ethswarm-chain-sync = ethswarm_chain_sync.cli:main