diff --git a/.agents/skills/check-wip1006-config/SKILL.md b/.agents/skills/check-wip1006-config/SKILL.md new file mode 100644 index 000000000..47c0563cb --- /dev/null +++ b/.agents/skills/check-wip1006-config/SKILL.md @@ -0,0 +1,55 @@ +--- +name: check-wip1006-config +description: Inspect the active WIP-1006 factory configuration from an L1 AnchorStateRegistry at one finalized snapshot, including safety state, Nitro PCR approvals, and optional implementation comparison. +--- + +Run `python3 scripts/check_config.py [l1_rpc] [--implementation
]`, resolving the script relative to this skill directory. Execute directly; do not read/recreate the script unless troubleshooting. Requires Python standard library, Foundry `cast` (local Keccak only), and the adjacent investigate-game RPC helper. GitHub CLI authentication (`gh auth login`) or `GH_TOKEN`/`GITHUB_TOKEN` with repository push access lets the release lookup include draft releases. No transactions are sent. + +RPC defaults: `ETHEREUM_PROVIDER` for mainnet, `ETHEREUM_SEPOLIA_PROVIDER` for sepolia. An explicit URL overrides the environment. Never expose URLs/credentials. Wrong chain IDs fail. Reads use an EIP-1898 canonical block hash, preferably finalized; unsupported finalized tags fall back explicitly to latest. Historical state, JSON-RPC batches and event queries are required. No unpinned state fallback is permitted. + +Return the script's compact text report directly, preserving complete addresses/hashes, UNKNOWN fields, checks, provenance, and snapshot metadata. Exit 1 means incomplete or inconsistent configuration; partial output is useful but is not a clean bill of health. Do not infer missing values from existing games or deployment files. If factory discovery fails, report the failed registry getter rather than guessing a deployment. + +The script discovers registry → factory → `gameImpls(1006)`, SystemConfig/SuperchainConfig, bond vault/token, SP1 backend, council authority, Nitro key registry → attestation verifier → certificate/P384 dependencies. It checks registration, immutable relationships, constructor constraints, proof domain, ETH init bond (must be zero with this ERC-20 architecture), pauses and PCR approvals. Game type 1006 and domain encoding version 1 are protocol identifiers from repository source, not deployment configuration. + +`--implementation` adds an OLD (currently registered) vs NEW (supplied candidate) comparison of all collected implementation/dependency parameters at the same snapshot, including unchanged values. Changes are not classified as safe/unsafe. The candidate is not assumed activated. + +Active means the implementation registered at the snapshot, used by games created after its activation. `setImplementation()` does not update existing games. Existing game parameters are never evidence of current factory configuration. + +PCR0/1/2 are **Keccak digests of raw PCRs**, not raw SHA-384 PCR bytes. The implementation pins only PCR0 (`teeImageId`); there is no unique expected PCR1/2. Approval events supply candidate triples, and `isPCRSetApproved` verifies current state. Scanning is bounded (64 requests and 180 seconds per verifier); unavailable/incomplete history means UNKNOWN, never “not approved.” A missing approved triple blocks new registrations, but PCR revocation does not revoke already registered signers. + +The report identifies the `proofs/...` release matching the active implementation's aggregation vkey, range vkey commitment, and `teeImageId`. The script reads release notes from the [world-chain releases](https://github.com/worldcoin/world-chain/releases) via GitHub's API and hashes each release's raw PCR0 before comparing it with the onchain image ID. All three values must match one release. Draft releases require GitHub authentication with push access; without confirmed draft visibility, a search with no published match reports UNKNOWN because drafts could match. A complete search with no match reports that the onchain proofs release doesn't match any release in the world-chain releases section. Missing onchain values, unavailable GitHub data, malformed release notes, or an incomplete search also report UNKNOWN. This is release metadata identification, not proof artifact verification. + +Limitations: this inspects the repository's contract interfaces, not arbitrary future implementations. Getter compatibility/code presence cannot authenticate deployed bytecode, prove key/artifact correctness, test a proof, or certify end-to-end availability. Custom verifier adapters may yield UNKNOWN dependencies. The supplied registry is the trust root, not independently authenticated as a canonical deployment. No automatic network switch. No signer inventory, private keys, certificate cache enumeration, or existing-game inspection. RPC completeness is trusted for historical logs. + +Examples: + +```text +$check-wip1006-config 0x... sepolia +$check-wip1006-config 0x... mainnet https://... --implementation 0x... +``` + +Example report shape (illustrative, not live data; actual addresses/hashes are untruncated): + +```text +WIP-1006 Active Configuration +Network: sepolia | Chain ID: 11155111 +Snapshot: | | | finalized +... +WIP-1006 +implementation:
+proposerBond: [raw ERC-20 units] +... +TEE Attestation +PCR0= PCR1= PCR2= approved=True +... +Onchain proofs release: proofs/v1.0.0-rc.4 +Release source: https://api.github.com/repos/worldcoin/world-chain/releases +... +Checks +[OK] Factory init bond is zero (ETH); proposer bond uses the ERC-20 vault +[UNKNOWN] Proof artifacts/key correctness cannot be established from getters +... +Discovered via +implementation: factory.gameImpls(1006) +... +``` diff --git a/.agents/skills/check-wip1006-config/scripts/check_config.py b/.agents/skills/check-wip1006-config/scripts/check_config.py new file mode 100644 index 000000000..4effac1b4 --- /dev/null +++ b/.agents/skills/check-wip1006-config/scripts/check_config.py @@ -0,0 +1,467 @@ +#!/usr/bin/env python3 +"""Read-only active configuration inspection; shared RPC transport, local cast Keccak.""" + +import argparse +from functools import lru_cache +import importlib.util +import json +import os +from pathlib import Path +import re +import subprocess +import sys +import time +from urllib.parse import urlsplit +from urllib.request import Request, urlopen + +HELPER = Path(__file__).resolve().parents[2] / "investigate-game/scripts/investigate_game.py" +spec = importlib.util.spec_from_file_location("game_rpc", HELPER) +base = importlib.util.module_from_spec(spec) +spec.loader.exec_module(base) +UNKNOWN = "UNKNOWN" +ZERO = "0x" + "00" * 20 +GAME_TYPE = 1006 # pkg/contracts/src/dispute/lib/GameTypes.sol +NETWORKS = {"mainnet": (1, "ETHEREUM_PROVIDER"), "sepolia": (11155111, "ETHEREUM_SEPOLIA_PROVIDER")} +RELEASES_API = "https://api.github.com/repos/worldcoin/world-chain/releases" +IMPL = { + **{k: v[1] for k, v in base.GETTERS.items() if k in ( + "gameType", "proposerBond", "challengerBond", "aggregationVKey", "rangeVKeyCommitment", + "teeImageId", "validityProofVerifier", "teeVerifier", "securityCouncil", + "disputeGameFactory", "anchorStateRegistry", "bondVault")}, + "domainHash": "bytes32", "rollupConfigHash": "bytes32", "blockInterval": "uint256", + "challengePeriod": "uint64", "proofPeriod": "uint64", "PROOF_THRESHOLD": "uint8", + "PROOF_LANE_COUNT": "uint8", "CHALLENGER_REWARD_BPS": "uint256", + "protocolFeeRecipient": "address", +} + + +@lru_cache(maxsize=256) +def keccak(value): + try: + result = subprocess.run(["cast", "keccak", value], capture_output=True, text=True, + timeout=5, check=True).stdout.strip() + except (OSError, subprocess.SubprocessError): + raise ValueError("Local cast keccak failed; install Foundry and check PATH") from None + return base.decode(result, "bytes32") + + +def github_token(): + token = os.environ.get("GH_TOKEN") or os.environ.get("GITHUB_TOKEN") + if token: + return token + try: + result = subprocess.run(["gh", "auth", "token"], capture_output=True, text=True, timeout=5) + except (OSError, subprocess.SubprocessError): + return None + return result.stdout.strip() if result.returncode == 0 else None + + +def proofs_release(aggregation, range_commitment, image_id): + """Match all three onchain identities against published GitHub release notes.""" + if UNKNOWN in (aggregation, range_commitment, image_id): + return UNKNOWN + expected = (aggregation.lower(), range_commitment.lower(), image_id.lower()) + deadline = time.monotonic() + 30 + token = github_token() + headers = {"Accept": "application/vnd.github+json", "User-Agent": "check-wip1006-config"} + if token: + headers["Authorization"] = f"Bearer {token}" + for page in range(1, 21): + remaining = deadline - time.monotonic() + if remaining <= 0: + raise ValueError("GitHub release lookup timed out") + request = Request(f"{RELEASES_API}?per_page=100&page={page}", + headers=headers) + try: + with urlopen(request, timeout=min(10, remaining)) as response: + payload = response.read(2_000_001) + if len(payload) > 2_000_000: + raise ValueError("GitHub release response exceeds size limit") + releases = json.loads(payload) + except (OSError, TimeoutError, UnicodeError, json.JSONDecodeError) as error: + raise ValueError(f"GitHub release lookup failed: {type(error).__name__}") from None + if not isinstance(releases, list) or len(releases) > 100: + raise ValueError("Invalid GitHub release response") + for release in releases: + if not isinstance(release, dict) or not isinstance(release.get("tag_name"), str): + raise ValueError("Invalid GitHub release entry") + tag = release["tag_name"] + if not tag.startswith("proofs/"): + continue + if not re.fullmatch(r"proofs/v[0-9A-Za-z._-]+", tag): + raise ValueError("Invalid proofs release tag") + body = release.get("body") + if not isinstance(body, str): + raise ValueError(f"Proofs release {tag} has no release notes") + values = [] + for field, size in (("aggregation_vkey", 64), ("range_vkey_commitment", 64), ("PCR0", 96)): + matches = re.findall(rf"(?im)^\s*\|\s*{field}\s*\|\s*`?(0x[0-9a-f]{{{size}}})`?\s*\|", body) + if len(matches) != 1: + raise ValueError(f"Proofs release {tag} has missing or ambiguous {field}") + values.append(matches[0].lower()) + if (values[0], values[1], keccak(values[2]).lower()) == expected: + return tag + if len(releases) < 100: + if not token: + raise ValueError("GitHub authentication unavailable; draft releases were not searched") + remaining = deadline - time.monotonic() + if remaining <= 0: + raise ValueError("GitHub release lookup timed out") + try: + request = Request("https://api.github.com/repos/worldcoin/world-chain", headers=headers) + with urlopen(request, timeout=min(10, remaining)) as response: + repository = json.loads(response.read(1_000_001)) + except (OSError, TimeoutError, UnicodeError, json.JSONDecodeError) as error: + raise ValueError(f"GitHub draft visibility check failed: {type(error).__name__}") from None + permissions = repository.get("permissions") if isinstance(repository, dict) else None + if not isinstance(permissions, dict) or permissions.get("push") is not True: + raise ValueError("GitHub token cannot confirm draft release visibility") + return None + raise ValueError("GitHub release lookup exceeded 20 pages; history incomplete") + + +def address(value): + if not re.fullmatch(r"0x[0-9a-fA-F]{40}", value) or value.lower() == ZERO: + raise argparse.ArgumentTypeError("Expected a nonzero 20-byte Ethereum address") + return value.lower() + + +def decode(value, kind): + if kind == "bool": + number = base.decode(value, "uint8") + if number not in (0, 1): + raise ValueError("Invalid ABI boolean") + return bool(number) + if kind == "anchor": + data = base.hexdata(value) + if len(data) != 128: + raise ValueError("Invalid anchor tuple") + return (base.decode("0x" + data[:64], "bytes32"), int(data[64:], 16)) + return base.decode(value, kind) + + +class Inspector: + def __init__(self, url, network, registry): + self.url, self.network, self.registry = url, network, registry + self.checks, self.sources, self.sections = [], {}, {} + self.block = None + self.pcr_cache = {} + self.release_result = UNKNOWN + self.sections["WIP-1006"] = dict.fromkeys(["implementation", *IMPL], UNKNOWN) + self.sections["TEE Attestation"] = {"NitroAttestationVerifier": UNKNOWN, "PCR sets": UNKNOWN} + + def check(self, status, message): + self.checks.append((status, message)) + + def rpc(self, calls): + return base.rpc(self.url, calls) + + def start(self): + chain, snapshot = self.rpc([("eth_chainId", []), ("eth_getBlockByNumber", ["finalized", False])]) + if base.quantity(chain) != NETWORKS[self.network][0]: + raise ValueError("RPC chain ID does not match supplied network") + finality = "finalized" + if snapshot is None or isinstance(snapshot, base.CallError) and snapshot.args[0].startswith( + ("RPC error code -32601", "RPC error code -32602")): + snapshot, = self.rpc([("eth_getBlockByNumber", ["latest", False])]) + finality = "latest (finalized unavailable)" + self.check("WARNING", "Finalized tag unavailable; using explicitly reported latest snapshot") + base.require(snapshot) + if not isinstance(snapshot, dict): + raise ValueError("Snapshot unavailable") + self.number = base.quantity(snapshot.get("number")) + self.hash = base.decode(snapshot.get("hash"), "bytes32") + self.timestamp = base.quantity(snapshot.get("timestamp")) + self.block = {"blockHash": self.hash, "requireCanonical": True} + self.snapshot = f"{self.number} | {self.hash} | {base.utc(self.timestamp)} | {finality}" + + def collect(self, target, fields, prefix, args=""): + """fields maps getter signatures (or names) to ABI return types.""" + values = dict.fromkeys(fields, UNKNOWN) + for name in fields: + self.sources[f"{prefix}.{name}"] = f"{target}.{name if '(' in name else name + '()'}" + if target in (UNKNOWN, ZERO): + self.check("ERROR", f"{prefix}: dependency address unavailable or zero; fields UNKNOWN") + return values + calls = [("eth_call", [{"to": target, "data": keccak( + name if "(" in name else name + "()")[:10] + args}, self.block]) for name in fields] + try: + results = self.rpc(calls) + except ValueError as error: + results = [error] * len(fields) + for (name, kind), result in zip(fields.items(), results): + try: + values[name] = decode(result, kind) + except ValueError as error: + self.check("ERROR", f"{prefix}.{name}: UNKNOWN ({error})") + return values + + def code(self, addresses): + if ZERO in addresses: + self.check("ERROR", "Required contract dependency is the zero address") + targets = sorted(set(a for a in addresses if a not in (UNKNOWN, ZERO))) + if not targets: + return + try: + results = self.rpc([("eth_getCode", [a, self.block]) for a in targets]) + except ValueError as error: + results = [error] * len(targets) + for target, result in zip(targets, results): + try: + if not base.hexdata(result): + raise ValueError("no contract bytecode") + except ValueError as error: + self.check("ERROR", f"Contract {target}: {error}") + + def compare(self, label, actual, expected, severity="ERROR"): + if UNKNOWN in (actual, expected): + self.check("UNKNOWN", label) + else: + self.check("OK" if actual == expected else severity, + label + ("" if actual == expected else f": got {actual}, expected {expected}")) + + def pcrs(self, verifier): + if verifier in self.pcr_cache: + return self.pcr_cache[verifier] + if verifier in (UNKNOWN, ZERO): + return UNKNOWN + # Events only enumerate candidates; approval always comes from snapshot state. + topic = keccak("PCRSetApproved(bytes32,bytes32,bytes32)") + pending, triples, requests = [(0, self.number)], set(), 0 + deadline = time.monotonic() + 180 + try: + while pending: + if requests >= 64 or time.monotonic() >= deadline: + raise ValueError("PCR event scan budget exhausted; history incomplete") + lo, hi = pending.pop() + requests += 1 + result, = self.rpc([("eth_getLogs", [{"address": verifier, "topics": [topic], + "fromBlock": hex(lo), "toBlock": hex(hi)}])]) + if isinstance(result, base.CallError): + if lo == hi: + raise result + mid = (lo + hi) // 2 + pending.extend([(lo, mid), (mid + 1, hi)]) + continue + base.require(result) + if not isinstance(result, list) or len(result) > 10000: + raise ValueError("Invalid or excessive PCR log response") + for log in result: + if (not isinstance(log, dict) or log.get("address", "").lower() != verifier + or log.get("topics") != [topic] or log.get("removed") is not False + or not lo <= base.quantity(log.get("blockNumber")) <= hi): + raise ValueError("Invalid PCR event metadata") + data = base.hexdata(log.get("data")) + if len(data) != 192: + raise ValueError("Invalid PCR event ABI") + triples.add(tuple("0x" + data[i:i + 64] for i in range(0, 192, 64))) + if len(triples) > 256: + raise ValueError("PCR set enumeration exceeds 256-set budget") + approved = [] + for triple in sorted(triples): + value = self.collect(verifier, {"isPCRSetApproved(bytes32,bytes32,bytes32)": "bool"}, + "PCR approval", "".join(p[2:] for p in triple)) + approved.append((*triple, next(iter(value.values())))) + self.pcr_cache[verifier] = approved + except ValueError as error: + self.check("ERROR", f"PCR approval: UNKNOWN ({error})") + self.pcr_cache[verifier] = UNKNOWN + return self.pcr_cache[verifier] + + def implementation(self, target, label, factory, system): + values = {"implementation": target, **self.collect(target, IMPL, label)} + self.sections["WIP-1006" if label == "WIP-1006" else "NEW implementation"] = values + self.sources[f"{label}.implementation"] = "factory.gameImpls(1006)" if label == "WIP-1006" else "--implementation argument" + self.compare(f"{label}: implementation game type", values["gameType"], GAME_TYPE) + self.compare(f"{label}: factory relationship", values["disputeGameFactory"], factory) + self.compare(f"{label}: registry relationship", values["anchorStateRegistry"], self.registry) + for name, kind in IMPL.items(): + value = values[name] + if value != UNKNOWN and (kind in ("address", "bytes32") or name in ( + "proposerBond", "challengerBond", "blockInterval", "challengePeriod")) and int(str(value), 16 if isinstance(value, str) else 10) == 0: + self.check("ERROR", f"{label}.{name} is zero") + if all(values[k] != UNKNOWN for k in ("PROOF_THRESHOLD", "PROOF_LANE_COUNT", "proofPeriod", "challengePeriod")): + valid = 2 <= values["PROOF_THRESHOLD"] <= values["PROOF_LANE_COUNT"] == 3 and values["proofPeriod"] > values["challengePeriod"] > 0 + self.check("OK" if valid else "ERROR", f"{label}: proof threshold and timing constraints") + if values["proposerBond"] != UNKNOWN and values["CHALLENGER_REWARD_BPS"] != UNKNOWN: + bps = values["CHALLENGER_REWARD_BPS"] + self.check("OK" if 0 < bps <= 10000 and values["proposerBond"] <= (2**256 - 1) // bps else "ERROR", + f"{label}: reward basis points and proposer bond arithmetic") + if all(values[k] != UNKNOWN for k in ("domainHash", "rollupConfigHash", "blockInterval")) and system["l2ChainId"] != UNKNOWN: + encoded = f'{system["l2ChainId"]:064x}{1:064x}' + values["rollupConfigHash"][2:] + f'{values["blockInterval"]:064x}' + self.compare(f"{label}: domainHash (LibProof v1 encoding)", values["domainHash"], keccak("0x" + encoded)) + + def dependency(name, parent, fields): + result = self.collect(parent, fields, label + "." + name) + values.update({name + "." + k: v for k, v in result.items()}) + return result + + vault = dependency("vault", values["bondVault"], {"token": "address", "systemConfig": "address", "disputeGameFactory": "address", "delay": "uint256"}) + self.compare(f"{label}: vault factory", vault["disputeGameFactory"], factory) + self.compare(f"{label}: vault SystemConfig", vault["systemConfig"], self.system_address) + dependency("token", vault["token"], {"decimals": "uint8"}) + sp1 = dependency("validity", values["validityProofVerifier"], {"sp1Verifier": "address"}) + council = dependency("council", values["securityCouncil"], {"council": "address"}) + tee = dependency("tee", values["teeVerifier"], {"registry": "address"}) + registry = dependency("nitroRegistry", tee["registry"], {"verifier": "address", "owner": "address"}) + nitro = dependency("attestation", registry["verifier"], {"certManager": "address", "p384Verifier": "address", "owner": "address", "MAX_AGE": "uint256", "CLOCK_SKEW_TOLERANCE": "uint256", "MAX_CABUNDLE_LEN": "uint256"}) + cert = dependency("certManager", nitro["certManager"], {"p384Verifier": "address", "owner": "address", "revoker": "address", "ROOT_CA_CERT_HASH": "bytes32", "ROOT_CA_CERT_NOT_AFTER": "uint64"}) + if cert["ROOT_CA_CERT_HASH"] != UNKNOWN: + root = self.collect(nitro["certManager"], {"revoked(bytes32)": "bool"}, label + ".certRoot", cert["ROOT_CA_CERT_HASH"][2:]) + values["certRoot.revoked"] = root["revoked(bytes32)"] + self.compare(f"{label}: Nitro root certificate not revoked", values["certRoot.revoked"], False) + else: + values["certRoot.revoked"] = UNKNOWN + if cert["ROOT_CA_CERT_NOT_AFTER"] != UNKNOWN: + self.check("OK" if cert["ROOT_CA_CERT_NOT_AFTER"] > self.timestamp else "ERROR", f"{label}: Nitro root certificate expiry") + self.compare(f"{label}: certificate and attestation P384 verifiers", cert["p384Verifier"], nitro["p384Verifier"]) + self.code([target, values["bondVault"], vault["token"], values["validityProofVerifier"], sp1["sp1Verifier"], + values["securityCouncil"], values["teeVerifier"], tee["registry"], registry["verifier"], nitro["certManager"], nitro["p384Verifier"]]) + if council["council"] == ZERO: + self.check("ERROR", f"{label}: zero council authority") + pcrs = self.pcrs(registry["verifier"]) + values["PCR sets"] = pcrs + if label == "WIP-1006": + self.sections.pop("TEE Attestation", None) + image = values["teeImageId"] + if image == UNKNOWN or pcrs == UNKNOWN: + self.check("UNKNOWN", f"{label}: approval of PCR0 matching teeImageId") + else: + matching = [p for p in pcrs if p[0] == image] + status = "OK" if any(p[3] is True for p in matching) else "UNKNOWN" if any(p[3] == UNKNOWN for p in matching) else "WARNING" + self.check(status, f"{label}: approved PCR triple for teeImageId: " + ("yes" if status == "OK" else "UNKNOWN" if status == "UNKNOWN" else "none; new key registrations blocked for this image")) + return values + + def run(self, candidate=None): + self.start() + registry = self.collect(self.registry, {"disputeGameFactory": "address", "systemConfig": "address", "superchainConfig": "address", "paused": "bool", "respectedGameType": "uint32", "retirementTimestamp": "uint64", "disputeGameFinalityDelaySeconds": "uint256", "anchorGame": "address", "getAnchorRoot": "anchor"}, "AnchorStateRegistry") + self.sections["System State"] = registry + factory = registry["disputeGameFactory"] + if factory in (ZERO, UNKNOWN): + raise ValueError("DisputeGameFactory cannot be discovered via AnchorStateRegistry.disputeGameFactory()") + fields = self.collect(factory, {"gameImpls(uint32)": "address", "initBonds(uint32)": "uint256", "gameArgs(uint32)": "bytes"}, "factory", f"{GAME_TYPE:064x}") + self.sections["Factory"] = {"address": factory, **fields} + self.compare("Factory init bond is zero (ETH); proposer bond uses the ERC-20 vault", fields["initBonds(uint32)"], 0) + self.compare("Factory implementation args empty (WIP-1006 CWIA layout)", fields["gameArgs(uint32)"], "0x") + self.compare("Registry respects WIP-1006", registry["respectedGameType"], GAME_TYPE, "WARNING") + if registry["retirementTimestamp"] != UNKNOWN and registry["retirementTimestamp"] >= self.timestamp: + self.check("WARNING", "Retirement timestamp is at/after snapshot; games created through that timestamp are retired") + self.system_address = registry["systemConfig"] + system = self.collect(self.system_address, {"superchainConfig": "address", "paused": "bool", "l2ChainId": "uint256"}, "SystemConfig") + self.sections["SystemConfig"] = {"address": self.system_address, **system} + self.compare("SuperchainConfig relationship", system["superchainConfig"], registry["superchainConfig"]) + self.compare("Registry and SystemConfig pause agree", registry["paused"], system["paused"]) + pause = self.collect(registry["superchainConfig"], {"paused(address)": "bool"}, "SuperchainConfig", "0" * 64) + self.sections["SuperchainConfig"] = {"address": registry["superchainConfig"], "paused(address(0))": pause["paused(address)"]} + self.sections["SuperchainConfig"].update(self.collect(registry["superchainConfig"], {"guardian": "address", "pauseExpiry": "uint256"}, "SuperchainConfig")) + for label, value in (("global", pause["paused(address)"]), ("registry (global or chain-specific)", registry["paused"])): + self.compare(label + " pause inactive", value, False, "WARNING") + if pause["paused(address)"] is True: + self.compare("Global pause propagated to registry", registry["paused"], True) + self.code([self.registry, factory, self.system_address, registry["superchainConfig"]]) + target = fields["gameImpls(uint32)"] + if target in (ZERO, UNKNOWN): + self.sections["WIP-1006"] = dict.fromkeys(["implementation", *IMPL], UNKNOWN) + raise ValueError("WIP-1006 not registered or factory implementation unreadable") + self.check("OK", "WIP-1006 registered in factory") + self.sections["WIP-1006"] = self.implementation(target, "WIP-1006", factory, system) + if candidate: + self.sections["NEW implementation"] = self.implementation(candidate, "NEW", factory, system) + active = self.sections["WIP-1006"] + try: + release = proofs_release(active["aggregationVKey"], active["rangeVKeyCommitment"], active["teeImageId"]) + if release == UNKNOWN: + self.check("UNKNOWN", "Proofs release lookup: onchain identity unavailable") + elif release is None: + self.release_result = "doesn't match any release in the world-chain releases section" + self.check("WARNING", "Onchain proofs identities match no published world-chain proofs release") + else: + self.release_result = release + except ValueError as error: + self.check("UNKNOWN", f"Proofs release lookup: {error}") + self.check("UNKNOWN", "Proof artifacts/key correctness and end-to-end availability cannot be established from getters") + self.check("WARNING", "Supplied registry is the trust root; canonical deployment and bytecode identity not authenticated") + + def finish(self): + if self.block is None: + return + current, = self.rpc([("eth_getBlockByNumber", [hex(self.number), False])]) + base.require(current) + if not isinstance(current, dict) or base.decode(current.get("hash"), "bytes32") != self.hash: + self.sections.clear() + self.sources.clear() + self.checks.clear() + self.release_result = UNKNOWN + raise ValueError("Snapshot reorganized; discarded report. Rerun inspection") + + def render(self): + lines = ["WIP-1006 Active Configuration", f"Network: {self.network} | Chain ID: {NETWORKS[self.network][0]} (requested)", + f"Snapshot: {getattr(self, 'snapshot', UNKNOWN)}", f"AnchorStateRegistry: {self.registry}"] + for section, fields in self.sections.items(): + if section == "NEW implementation": + continue # The comparison below includes every candidate field. + lines.extend(["", section]) + for key, value in fields.items(): + if key == "PCR sets": + lines.append("TEE Attestation (PCRs are Keccak digests)") + if value == UNKNOWN: + lines.append("PCR0/PCR1/PCR2/approval: UNKNOWN") + elif not value: + lines.append("No PCR approval events found through snapshot") + else: + lines.extend(f"PCR0={p[0]} PCR1={p[1]} PCR2={p[2]} approved={p[3]}" for p in value) + else: + suffix = " [raw ERC-20 units]" if key in ("proposerBond", "challengerBond") else " [wei]" if key == "initBonds(uint32)" else "" + lines.append(f"{key}: {value}{suffix}") + lines.extend(["", f"Onchain proofs release: {self.release_result}", f"Release source: {RELEASES_API}"]) + if "NEW implementation" in self.sections: + lines.extend(["", "OLD (active) vs NEW (candidate)"]) + old, new = self.sections["WIP-1006"], self.sections["NEW implementation"] + for key in dict.fromkeys([*old, *new]): + before, after = old.get(key, UNKNOWN), new.get(key, UNKNOWN) + status = "UNKNOWN" if UNKNOWN in (before, after) else "unchanged" if before == after else "CHANGED" + lines.append(f"{key} [{status}]: OLD={before} | NEW={after}") + lines.extend(["", "Checks", *[f"[{status}] {message}" for status, message in self.checks], "", "Discovered via"]) + grouped = {} + for name, source in self.sources.items(): + if name.endswith(".implementation"): + lines.append(f"{name}: {source}") + else: + target, getter = source.split(".", 1) + grouped.setdefault(target, set()).add(getter) + lines.extend(f"{target}: " + ", ".join(sorted(getters)) for target, getters in grouped.items()) + lines.extend(["", "Active = factory implementation at snapshot, used for new games after activation; existing games are not updated by setImplementation().", + "PCR revocation blocks new registrations, not existing signers. Implementation pins PCR0 only; PCR1/2 are allowlisted triples."]) + return "\n".join(lines) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("anchor_state_registry", type=address) + parser.add_argument("network", choices=NETWORKS) + parser.add_argument("l1_rpc", nargs="?") + parser.add_argument("--implementation", type=address) + args = parser.parse_args() + url = args.l1_rpc or os.environ.get(NETWORKS[args.network][1]) + try: + valid_url = url and urlsplit(url).scheme in ("http", "https") and urlsplit(url).hostname + except ValueError: + valid_url = False + if not valid_url: + print(f"[ERROR] No usable RPC: supply l1_rpc or set {NETWORKS[args.network][1]}") + return 1 + inspector = Inspector(url, args.network, args.anchor_state_registry) + try: + inspector.run(args.implementation) + except ValueError as error: + inspector.check("ERROR", str(error)) + try: + inspector.finish() + except ValueError as error: + inspector.check("ERROR", f"Snapshot verification failed: {error}") + print(inspector.render()) + return int(any(status == "ERROR" for status, _ in inspector.checks)) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.agents/skills/debug-node-tracing/SKILL.md b/.agents/skills/debug-node-tracing/SKILL.md new file mode 100644 index 000000000..75c531131 --- /dev/null +++ b/.agents/skills/debug-node-tracing/SKILL.md @@ -0,0 +1,55 @@ +--- +name: debug-node-tracing +description: Debug World Chain nodes with temporary admin_tracingDirectives log filters and targeted log collection. Use for live Flashblocks, networking, pool, builder, or validator debugging; not EVM transaction traces. +--- + +# Debug node tracing + +Use World Chain's `admin_tracingDirectives` RPC to change a running node's log filter for a bounded time. Adapted from the local `nodl` skill; verify behavior against `crates/rpc/src/admin.rs`, `crates/cli/src/app.rs`, and `crates/node/src/add_ons.rs`. + +## Check the target + +- Establish the environment, pod, symptom, and time window from the debugging request. Start with one pod and a narrow target at `debug` for 120 seconds; use `trace` only when needed. +- Check the deployed image and startup flags. Reload requires `admin` in an enabled `--http.api` or `--ws.api` at startup. This RPC uses that HTTP/WS server, not the Engine API on 8551. +- Inspect startup stdout and file filters before changing them. Reload affects all reloadable outputs; expiry restores the stdout startup filter to every output. A different file filter is lost until restart. Preserve existing diagnostic coverage when choosing whether to use this RPC. +- Overrides are process-wide. A new call replaces the active override and its timer. Do not interrupt another debugging session; renew deliberately before expiry when more time is needed. + +## Connect and apply + +Builders require VPN access and pod port-forwarding in `world-chain-builder`. Contexts are `tfh-crypto-{dev,stage,prod}-eu-central-2`. Load the matching JWT from the configured secret store without printing it; port 8545 also requires authentication in this deployment. + +Stage example; change the context, pod, and credential together for another target: + +```bash +kubectl --context tfh-crypto-stage-eu-central-2 -n world-chain-builder \ + port-forward --address 127.0.0.1 --pod-running-timeout=30s \ + pod/world-chain-builder-0 18545:8545 +``` + +Keep that process running while collecting logs. Select targets from the deployed code's `target:` fields; examples in this repository include `flashblocks::p2p`, `flashblocks::payload_builder`, and `flashblocks::state_executor`. + +The following example assumes the stdout baseline is `info`. Preserve any required baseline directives in the replacement filter: + +```bash +ETH_RPC_JWT_SECRET="$JWT_STAGE" cast rpc admin_tracingDirectives \ + '{"directives":"info,flashblocks::p2p=debug","ttlSecs":120}' \ + --rpc-url http://localhost:18545 --rpc-timeout 15 +``` + +`cast` mints the bearer token from the raw JWT secret. Its flag is `--jwt-secret`; `nodl` uses `--jwt` and does not wrap this custom method. Never print credentials or enable shell tracing around authenticated commands. + +Use camelCase `ttlSecs`. The allowed TTL is 1–3600 seconds; trimmed directives must be nonempty and at most 1024 bytes. Save the successful response's `applied`, `ttlSecs`, and `revertsTo` fields. A timeout leaves application uncertain; inspect logs before retrying, since a retry replaces the timer. + +## Collect and restore + +1. Filter Datadog logs by environment, pod, target, and the capture window. If DEBUG/TRACE is not shipped, inspect bounded pod logs or the configured on-pod log file. +2. Correlate block, payload, transaction, and peer identifiers relevant to the symptom. Avoid collecting unrelated payloads or logging secrets. +3. Let the TTL expire, or restore early by calling the same method with the returned `revertsTo` as `directives` and `ttlSecs: 1`. Do this only while your override still owns the session; do not overwrite a newer operator's filter. +4. Check for the `world_chain::admin` revert message or a revert failure. If restoration cannot be observed, report it as unverified. Stop the port-forward you started. +5. Report the target/image, filter, capture window, evidence, and restoration status. Do not restart a node or change its deployment unless the task authorizes it. + +## Failures + +- `401`: verify the environment's JWT and forwarded port; do not remove authentication. +- `-32601 Method not found`: check the deployed version, namespace, and port. Local source alone does not establish deployed support. +- `tracing reload is not active`: startup did not install reload support. Report the required startup flag change; it cannot be enabled through this RPC. diff --git a/.agents/skills/invalid-parent/SKILL.md b/.agents/skills/invalid-parent/SKILL.md new file mode 100644 index 000000000..c8de474c5 --- /dev/null +++ b/.agents/skills/invalid-parent/SKILL.md @@ -0,0 +1,21 @@ +--- +name: invalid-parent +description: Trace a WIP1006 INVALID_PARENT cascade to its first ancestor with a different status or invalidation reason. +--- + +Run `python3 scripts/trace_parent.py [mainnet|sepolia]`, resolving +the script relative to this skill directory. Execute it directly; reading or +recreating the script is unnecessary unless troubleshooting. + +Default to mainnet for Ethereum/mainnet or no network; use sepolia when specified. +The script reads `ETHEREUM_PROVIDER` or `ETHEREUM_SEPOLIA_PROVIDER` respectively. +It requires only Python's standard library and a provider supporting JSON-RPC batches. + +The script verifies the initial game reports CHALLENGER_WINS / INVALID_PARENT, +then follows parentRef() to the first ancestor where either value differs. +Reads use one block, with bounded requests, cycle detection, and a 200-hop limit. +Failures exit nonzero; partial rows are not a completed trace. + +Report the terminal address, GameStatus, InvalidationReason, and parent-hop count. +Include the chain when short. This identifies the on-chain origin of the cascade, +not the underlying cause of a proof timeout, and does not authenticate contract type. diff --git a/.agents/skills/invalid-parent/scripts/trace_parent.py b/.agents/skills/invalid-parent/scripts/trace_parent.py new file mode 100644 index 000000000..fc9e0679b --- /dev/null +++ b/.agents/skills/invalid-parent/scripts/trace_parent.py @@ -0,0 +1,126 @@ +#!/usr/bin/env python3 +"""Read-only WIP1006 parent traversal; no third-party dependencies.""" + +import argparse +import json +import os +import re +import sys +import urllib.error +import urllib.request + + +STATUSES = ("IN_PROGRESS", "CHALLENGER_WINS", "DEFENDER_WINS") +REASONS = ("NONE", "PROOF_TIMEOUT", "INVALID_PARENT") +# keccak256 of status(), claimData(), and parentRef(), truncated to four bytes. +SELECTORS = ("0x200d2ed2", "0x3ec4d4d6", "0x93f4d416") + + +def rpc(url, calls): + payload = [ + {"jsonrpc": "2.0", "id": i, "method": method, "params": params} + for i, (method, params) in enumerate(calls) + ] + try: + request = urllib.request.Request( + url, data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + with urllib.request.urlopen(request, timeout=20) as response: + results = json.load(response) + except urllib.error.HTTPError as error: + raise ValueError(f"RPC HTTP failure: status {error.code}") from None + except (urllib.error.URLError, TimeoutError, OSError): + raise ValueError("RPC connection failed or timed out") from None + except (ValueError, UnicodeError): + raise ValueError("Invalid RPC URL or JSON response") from None + + if not isinstance(results, list) or len(results) != len(calls): + raise ValueError("RPC returned an invalid batch response") + by_id = {} + for result in results: + if not isinstance(result, dict): + raise ValueError("RPC returned an invalid response entry") + index = result.get("id") + if type(index) is not int or index not in range(len(calls)) or index in by_id: + raise ValueError("RPC returned invalid or duplicate response IDs") + if result.get("jsonrpc") != "2.0" or "error" in result or "result" not in result: + # Provider error messages can contain credentials or request URLs. + raise ValueError(f"RPC {calls[index][0]} failed (batch item {index})") + by_id[index] = result["result"] + return [by_id[i] for i in range(len(calls))] + + +def quantity(value): + if not isinstance(value, str) or not re.fullmatch(r"0x[0-9a-fA-F]+", value): + raise ValueError("RPC returned an invalid hexadecimal quantity") + return int(value, 16) + + +def words(value, count): + if not isinstance(value, str) or not re.fullmatch(r"0x[0-9a-fA-F]{%d}" % (64 * count), value): + raise ValueError(f"Invalid ABI response: expected {count} words") + return [int(value[i:i + 64], 16) for i in range(2, len(value), 64)] + + +def trace(url, address, chain_id): + chain, block = rpc(url, [("eth_chainId", []), ("eth_blockNumber", [])]) + if quantity(chain) != chain_id: + raise ValueError("Provider chain ID does not match the requested network") + block = hex(quantity(block)) + print(f"chain_id={chain_id} block={int(block, 16)}", flush=True) + visited = set() + for depth in range(201): + if address in visited: + raise ValueError(f"Parent cycle detected at {address}") + visited.add(address) + try: + status_raw, claim_raw, parent_raw = rpc(url, [ + ("eth_call", [{"to": address, "data": selector}, block]) + for selector in SELECTORS + ]) + status, = words(status_raw, 1) + proposal, challenger, deadline, bitmap, reason = words(claim_raw, 5) + if (status >= len(STATUSES) or reason >= len(REASONS) or proposal > 4 + or challenger >= 2**160 or deadline >= 2**64 or bitmap >= 2**8): + raise ValueError("Invalid claim/status ABI values") + print(f"hop={depth} game={address} status={STATUSES[status]} " + f"reason={REASONS[reason]}", flush=True) + if depth == 0 and (status != 1 or reason != 2): + raise ValueError("Initial game is not CHALLENGER_WINS / INVALID_PARENT") + if status != 1 or reason != 2: + print(f"terminal={address} parent_hops={depth}", flush=True) + return + parent, = words(parent_raw, 1) + if not 0 < parent < 2**160: + raise ValueError("Invalid or zero parent address") + address = f"0x{parent:040x}" + except ValueError as error: + raise ValueError(f"hop={depth} game={address}: {error}") from None + raise ValueError("200-hop limit reached without a terminal ancestor") + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("address") + parser.add_argument("network", nargs="?", choices=("mainnet", "sepolia"), default="mainnet") + args = parser.parse_args() + if not re.fullmatch(r"0x[0-9a-fA-F]{40}", args.address): + parser.error("game address must be 0x followed by 40 hexadecimal digits") + provider, chain_id = (("ETHEREUM_PROVIDER", 1) if args.network == "mainnet" + else ("ETHEREUM_SEPOLIA_PROVIDER", 11155111)) + url = os.environ.get(provider) + if not url: + parser.error(f"{provider} is not set") + if not url.startswith(("http://", "https://")): + parser.error(f"{provider} must be an HTTP(S) URL") + try: + trace(url, args.address.lower(), chain_id) + except ValueError as error: + print(f"Trace failed: {error}", file=sys.stderr) + return 1 + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.agents/skills/investigate-game/SKILL.md b/.agents/skills/investigate-game/SKILL.md new file mode 100644 index 000000000..e63441b7b --- /dev/null +++ b/.agents/skills/investigate-game/SKILL.md @@ -0,0 +1,35 @@ +--- +name: investigate-game +description: Verify an Ethereum address is a WIP1006 dispute game and report its status, claim, bonds, proof configuration, and proposal context in a compact debugging table. +--- + +Run `python3 scripts/investigate_game.py [mainnet|sepolia]`, +resolving the script relative to this skill directory. Execute it directly; +reading or recreating it is unnecessary unless troubleshooting. + +Default to mainnet; use sepolia when specified. The script reads +`ETHEREUM_PROVIDER` or `ETHEREUM_SEPOLIA_PROVIDER`, respectively. Requires only +Python's standard library and a provider supporting JSON-RPC batches. No +transactions are submitted. Network permission can be scoped to this script. + +The script checks chain ID, bytecode, game type 1006, and factory registration +before collecting fields. Reads use one L1 block, 20-second request timeouts, +and one snapshot restart if a reorg occurs. Pass `--expected-factory
` +when a trusted factory for the requested network/deployment is available from +user context or repository deployment configuration. Otherwise report the +script's provenance limitation; self-reported registration is not authentication +of a canonical World Chain deployment. + +On success, present the JSON `fields` as one compact Field / Value table in the +returned order. Include every field, the full game address, network/chain ID, +snapshot block number/hash/UTC timestamp, factory, and bond token. Keep addresses +and hashes complete and copyable. Include `warnings` and `errors` briefly. +The script decodes enums, proof lanes, UTC times, and exact ERC-20 bond amounts. +Do not assume the council verifier is a Safe or that deadline expiry resolves +the game. Parent references can point to the anchor registry; do not recurse. + +Exit 2 with `This is not a WIP1006 game contract address.` means return only +that sentence. Exit 1 means verification/RPC failure or an incomplete report, +not evidence of a non-WIP1006 contract. If partial JSON is returned, show the +available fields, mark the report incomplete, and identify failed reads. +Never expose provider URLs or credentials. diff --git a/.agents/skills/investigate-game/scripts/investigate_game.py b/.agents/skills/investigate-game/scripts/investigate_game.py new file mode 100644 index 000000000..ce011705d --- /dev/null +++ b/.agents/skills/investigate-game/scripts/investigate_game.py @@ -0,0 +1,330 @@ +#!/usr/bin/env python3 +"""Read-only WIP1006 game inspection; Python standard library only.""" + +import argparse +from datetime import datetime, timezone +import json +import os +import re +import sys +import urllib.error +import urllib.parse +import urllib.request + + +# First four bytes of keccak256 of the Solidity signatures (not SHA3-256). +# ABI: pkg/contracts/src/dispute/{MultiProofGame.sol,interfaces/IMultiProofGame.sol}. +GETTERS = { + "gameType": ("bbdc02db", "uint32"), + "disputeGameFactory": ("f2b4e617", "address"), + "rootClaim": ("bcef3b55", "bytes32"), + "extraData": ("609d3334", "bytes"), + "createdAt": ("cf09e0d0", "uint64"), + "status": ("200d2ed2", "uint8"), + "challengerBond": ("68ccdc86", "uint256"), + "proposerBond": ("d2e25d84", "uint256"), + "aggregationVKey": ("276fd5ac", "bytes32"), + "rangeVKeyCommitment": ("9bdd5de1", "bytes32"), + "teeImageId": ("5f0a6ce0", "bytes32"), + "validityProofVerifier": ("d020cbb1", "address"), + "teeVerifier": ("cda752ff", "address"), + "securityCouncil": ("27eb6c0f", "address"), + "claimData": ("3ec4d4d6", "claim"), + "l2SequenceNumber": ("99735e32", "uint256"), + "gameCreator": ("37b1b229", "address"), + "l1Head": ("6361506d", "bytes32"), + "parentRef": ("93f4d416", "address"), + "attempt": ("732b7a8d", "uint256"), + "proposalDomainHash": ("0e972f39", "bytes32"), + "bondVault": ("990826b3", "address"), + "anchorStateRegistry": ("5c0cba33", "address"), + "token": ("fc0c546a", "address"), + "decimals": ("313ce567", "uint8"), +} +STATUSES = ("IN_PROGRESS", "CHALLENGER_WINS", "DEFENDER_WINS") +PROPOSALS = ( + "Unchallenged", "Challenged", "UnchallengedAndValidProofProvided", + "ChallengedAndValidProofProvided", "Resolved", +) +REASONS = ("NONE", "PROOF_TIMEOUT", "INVALID_PARENT") +LANES = ("VALIDITY_PROOF", "TEE_ATTESTATION", "SECURITY_COUNCIL") + + +class NotGame(ValueError): + pass + + +class Reorg(ValueError): + pass + + +class CallError(ValueError): + def __init__(self, code, reverted=False): + super().__init__(f"RPC error code {code}" + (" (execution reverted)" if reverted else "")) + self.reverted = reverted + + +def rpc(url, calls): + payload = [ + {"jsonrpc": "2.0", "id": i, "method": method, "params": params} + for i, (method, params) in enumerate(calls) + ] + try: + request = urllib.request.Request( + url, data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}, + ) + with urllib.request.urlopen(request, timeout=20) as response: + results = json.load(response) + except urllib.error.HTTPError as error: + raise ValueError(f"RPC HTTP failure: status {error.code}") from None + except (urllib.error.URLError, TimeoutError, OSError): + raise ValueError("RPC connection failed or timed out") from None + except (ValueError, UnicodeError): + raise ValueError("Invalid RPC URL or JSON response") from None + if not isinstance(results, list) or len(results) != len(calls): + raise ValueError("Invalid RPC batch response count") + by_id = {} + for entry in results: + if not isinstance(entry, dict): + raise ValueError("Invalid RPC response entry") + index = entry.get("id") + if type(index) is not int or index not in range(len(calls)) or index in by_id: + raise ValueError("Invalid or duplicate RPC response ID") + if entry.get("jsonrpc") != "2.0" or ("result" in entry) == ("error" in entry): + raise ValueError("Invalid RPC response envelope") + if "error" in entry: + error = entry["error"] + if not isinstance(error, dict) or type(error.get("code")) is not int: + raise ValueError("Invalid RPC error response") + # Classify reverts, but never expose provider-supplied text/credentials. + message = error.get("message", "") + reverted = isinstance(message, str) and "execution reverted" in message.lower() + by_id[index] = CallError(error["code"], reverted) + else: + by_id[index] = entry["result"] + return [by_id[i] for i in range(len(calls))] + + +def require(value): + if isinstance(value, Exception): + raise value + return value + + +def hexdata(value): + require(value) + if not isinstance(value, str) or not re.fullmatch(r"0x(?:[0-9a-fA-F]{2})*", value): + raise ValueError("Invalid hexadecimal data") + return value[2:].lower() + + +def quantity(value): + require(value) + if not isinstance(value, str) or not re.fullmatch(r"0x(?:0|[1-9a-fA-F][0-9a-fA-F]*)", value): + raise ValueError("Invalid hexadecimal quantity") + return int(value, 16) + + +def decode(value, kind): + data = hexdata(value) + if kind == "bytes": + if len(data) < 128 or int(data[:64], 16) != 32: + raise ValueError("Invalid dynamic bytes ABI offset") + size = int(data[64:128], 16) + if len(data) != 128 + ((size + 31) // 32) * 64 or any(c != "0" for c in data[128 + size * 2:]): + raise ValueError("Invalid dynamic bytes ABI length/padding") + return "0x" + data[128:128 + size * 2] + if kind == "claim": + if len(data) != 320: + raise ValueError("Invalid claim ABI length") + return [decode("0x" + data[i * 64:(i + 1) * 64], item) + for i, item in enumerate(("uint8", "address", "uint64", "uint8", "uint8"))] + if len(data) != 64: + raise ValueError("Expected one ABI word") + if kind == "bytes32": + return "0x" + data + number = int(data, 16) + bits = 160 if kind == "address" else int(kind[4:]) + if number >= 2**bits: + raise ValueError(f"ABI value exceeds {kind}") + return "0x" + data[-40:] if kind == "address" else number + + +def read(url, block, target, names): + results = rpc(url, [("eth_call", [{"to": target, "data": "0x" + GETTERS[name][0]}, block]) + for name in names]) + values = {} + for name, result in zip(names, results): + try: + values[name] = decode(result, GETTERS[name][1]) + except ValueError as error: + values[name] = error + return values + + +def utc(timestamp): + try: + return datetime.fromtimestamp(timestamp, timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC") + except (OverflowError, OSError, ValueError): + return "outside supported UTC date range" + + +def inspect(url, game, chain_id, expected_factory=None): + chain, snapshot = rpc(url, [("eth_chainId", []), ("eth_getBlockByNumber", ["latest", False])]) + if quantity(chain) != chain_id: + raise ValueError("Provider chain ID does not match requested network") + require(snapshot) + if not isinstance(snapshot, dict): + raise ValueError("Snapshot block unavailable") + block = hex(quantity(snapshot.get("number"))) + block_hash = decode(snapshot.get("hash"), "bytes32") + now = quantity(snapshot.get("timestamp")) + code, = rpc(url, [("eth_getCode", [game, block])]) + if not hexdata(code): + raise NotGame() + game_type = read(url, block, game, ["gameType"])["gameType"] + if isinstance(game_type, CallError) and not game_type.reverted: + raise game_type + if isinstance(game_type, ValueError) or game_type != 1006: + raise NotGame() + identity = read(url, block, game, ["disputeGameFactory", "rootClaim", "extraData", "createdAt"]) + for name, value in identity.items(): + if isinstance(value, Exception): + raise ValueError(f"Cannot verify {name}: {value}") + factory = identity["disputeGameFactory"] + if expected_factory and factory != expected_factory: + raise NotGame() + extra = identity["extraData"][2:] + # ABI encode games(uint32,bytes32,bytes): dynamic tail starts after 3 words. + args = f"{1006:064x}" + identity["rootClaim"][2:] + f"{96:064x}{len(extra) // 2:064x}" + args += extra.ljust(((len(extra) + 63) // 64) * 64, "0") + registration, = rpc(url, [("eth_call", [{"to": factory, "data": "0x5f0150cb" + args}, block])]) + data = hexdata(registration) + if len(data) != 128: + raise ValueError("Invalid factory registration ABI") + registered = decode("0x" + data[:64], "address") + created = decode("0x" + data[64:], "uint64") + if registered != game or not created or created != identity["createdAt"]: + raise NotGame() + + errors, warnings = [], [] + if not expected_factory: + warnings.append("Type and factory registration verified; canonical deployment provenance not authenticated.") + + def collect(target, names): + try: + values = read(url, block, target, names) + except ValueError as error: + values = dict.fromkeys(names, error) + for name, value in values.items(): + if isinstance(value, Exception): + errors.append(f"{name} at {target}: {value}") + return {name: value for name, value in values.items() if not isinstance(value, Exception)} + + names = [name for name in GETTERS if name not in identity and name not in ("gameType", "token", "decimals")] + values = {**identity, **collect(game, names)} + token, decimals = None, None + if "bondVault" in values: + token = collect(values["bondVault"], ["token"]).get("token") + if token: + decimals = collect(token, ["decimals"]).get("decimals") + + def enum(value, labels): + if value >= len(labels): + warnings.append(f"Unknown enum value {value}") + return f"UNKNOWN ({value})" + return f"{labels[value]} ({value})" + + def bond(name): + if name not in values: + return "unavailable" + amount = values[name] + raw = f"{amount} raw token units" + if decimals is None: + return raw + digits = str(amount).zfill(decimals + 1) + formatted = (digits[:-decimals] + "." + digits[-decimals:]).rstrip("0").rstrip(".") if decimals else digits + return f"{formatted} tokens ({raw})" + + fields = {"GameStatus": enum(values["status"], STATUSES) if "status" in values else "unavailable", + "challengerBond": bond("challengerBond"), "proposerBond": bond("proposerBond")} + for name in ("aggregationVKey", "rangeVKeyCommitment", "teeImageId", "validityProofVerifier", "teeVerifier", "securityCouncil"): + fields[name] = values.get(name, "unavailable") + fields["createdAt"] = f"{created} — {utc(created)}" + claim_fields = ("status", "challenger", "deadline", "proofBitmap", "invalidationReason") + if "claimData" in values: + proposal, challenger, deadline, bitmap, reason = values["claimData"] + lanes = ", ".join(lane for i, lane in enumerate(LANES) if bitmap & (1 << i)) or "no accepted lanes" + if bitmap & ~7: + warnings.append(f"Unknown proof bitmap bits: {hex(bitmap & ~7)}") + delta = deadline - now + claim = [enum(proposal, PROPOSALS), challenger + (" (no challenger)" if int(challenger, 16) == 0 else ""), + f"{deadline} — {utc(deadline)}; {abs(delta)} seconds {'remaining' if delta > 0 else 'elapsed'} at snapshot", + f"0x{bitmap:02x} ({bitmap}) — {lanes}", enum(reason, REASONS)] + else: + claim = ["unavailable"] * 5 + fields.update(("claimData." + name, value) for name, value in zip(claim_fields, claim)) + for name in ("rootClaim", "l2SequenceNumber", "gameCreator", "l1Head", "parentRef", "attempt", "proposalDomainHash"): + fields[name] = str(values.get(name, "unavailable")) + if "parentRef" in values and "anchorStateRegistry" in values: + fields["parentRef"] += " (anchor registry)" if values["parentRef"] == values["anchorStateRegistry"] else " (parent game reference)" + current, = rpc(url, [("eth_getBlockByNumber", [block, False])]) + require(current) + if not isinstance(current, dict): + raise ValueError("Snapshot recheck unavailable") + if decode(current.get("hash"), "bytes32") != block_hash: + raise Reorg("Snapshot changed during investigation") + return { + "game": game, "chain_id": chain_id, "game_type": 1006, + "snapshot": {"number": int(block, 16), "hash": block_hash, "timestamp": now, "utc": utc(now)}, + "factory": factory, "expected_factory": expected_factory, + "bond_token": token, "bond_token_decimals": decimals, + "complete": not errors, "fields": fields, "warnings": warnings, "errors": errors, + } + + +def address_arg(value): + if not re.fullmatch(r"0x[0-9a-fA-F]{40}", value): + raise argparse.ArgumentTypeError("address must be 0x followed by 40 hexadecimal digits") + return value.lower() + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("address", type=address_arg) + parser.add_argument("network", nargs="?", choices=("mainnet", "sepolia"), default="mainnet") + parser.add_argument("--expected-factory", type=address_arg) + args = parser.parse_args() + provider, chain_id = (("ETHEREUM_PROVIDER", 1) if args.network == "mainnet" + else ("ETHEREUM_SEPOLIA_PROVIDER", 11155111)) + url = os.environ.get(provider) + if not url: + parser.error(f"{provider} is not set") + try: + parsed = urllib.parse.urlsplit(url) + if parsed.scheme not in ("http", "https") or not parsed.hostname: + raise ValueError() + except ValueError: + parser.error(f"{provider} must be an HTTP(S) URL") + try: + for attempt in range(2): + try: + report = inspect(url, args.address, chain_id, args.expected_factory) + break + except Reorg: + if attempt: + raise ValueError("Snapshot changed twice; rerun when the chain is stable") from None + report["network"] = args.network + print(json.dumps(report, indent=2)) + return 0 if report["complete"] else 1 + except NotGame: + print("This is not a WIP1006 game contract address.") + return 2 + except ValueError as error: + print(f"Investigation failed: {error}", file=sys.stderr) + return 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.agents/skills/pending-games/SKILL.md b/.agents/skills/pending-games/SKILL.md new file mode 100644 index 000000000..db6f68dd9 --- /dev/null +++ b/.agents/skills/pending-games/SKILL.md @@ -0,0 +1,37 @@ +--- +name: pending-games +description: List unresolved WIP1006 dispute game addresses by scanning backward through at most the newest 2000 entries in a supplied factory. +--- + +Run `python3 scripts/pending_games.py [mainnet|sepolia]`, +resolving the script relative to this skill directory. Execute it directly; +reading or recreating it is unnecessary unless troubleshooting. + +The user supplies the dispute game factory. Default to mainnet; use sepolia +when specified. L1 comes from `ETHEREUM_PROVIDER` or +`ETHEREUM_SEPOLIA_PROVIDER`, respectively. Requires Python's standard library, +the adjacent investigate-game RPC helper, and a provider supporting JSON-RPC +batches and EIP-1898 canonical block-hash reads. No transactions are submitted. + +Pending means game type `1006` with stored `status() == IN_PROGRESS` (`0`). +Include expired, challenged, proven, blacklisted, or retired games when their +stored status remains in progress. Deadline expiry and eligibility to resolve +do not mean the game has resolved. Resolved games awaiting `closeGame()` or +registry finality are excluded. + +The script checks the L1 chain ID and scans backward from the newest factory +entry at one latest L1 snapshot, in batches of 50, up to 2000 factory entries +(including non-1006 types). It does not stop at a resolved game or an expired +deadline: older games may still be pending, including across implementation +changes. Reads stay pinned to the canonical snapshot hash; a reorg fails the +scan rather than mixing snapshots. The supplied factory is the trust root, +not independently authenticated as a canonical World Chain deployment. + +On success, return `pending_games` as full, copyable addresses, one per line in +a code block, newest first. Briefly include network, factory, pending count, +entries scanned, and L1 snapshot number/hash. If `older_entries_unscanned` is +nonzero, state that older games were not checked and the list covers only the +newest 2000 factory entries. An empty list means no pending WIP1006 games in +the scanned range at that snapshot. Exit 1 means a failed scan or RPC/decoding +failure; report the failure, never a partial list as complete. Never expose +RPC URLs or credentials. diff --git a/.agents/skills/pending-games/scripts/pending_games.py b/.agents/skills/pending-games/scripts/pending_games.py new file mode 100644 index 000000000..69e5039c8 --- /dev/null +++ b/.agents/skills/pending-games/scripts/pending_games.py @@ -0,0 +1,137 @@ +#!/usr/bin/env python3 +"""List unresolved WIP1006 games among the newest 2000 factory entries.""" + +import argparse +import importlib.util +import json +import os +from pathlib import Path +import re +import sys +from urllib.parse import urlsplit + + +HELPER = Path(__file__).resolve().parents[2] / "investigate-game/scripts/investigate_game.py" +spec = importlib.util.spec_from_file_location("game_rpc", HELPER) +base = importlib.util.module_from_spec(spec) +spec.loader.exec_module(base) +BATCH_SIZE = 50 +MAX_SCAN = 2000 +GAME_TYPE = 1006 +NETWORKS = {"mainnet": (1, "ETHEREUM_PROVIDER"), "sepolia": (11155111, "ETHEREUM_SEPOLIA_PROVIDER")} +# First four bytes of keccak256 of the Solidity signatures. +SELECTORS = {"gameCount": "4d1975b4", "gameAtIndex": "bb8aa1fc", "status": "200d2ed2"} + + +def contract_calls(url, block, requests): + results = base.rpc(url, [ + ("eth_call", [{"to": target, "data": "0x" + SELECTORS[method] + args}, block]) + for target, method, args in requests + ]) + for (target, method, _), result in zip(requests, results): + try: + base.require(result) + except ValueError as error: + raise ValueError(f"{method} at {target}: {error}") from None + return results + + +def factory_entry(raw, index): + data = base.hexdata(raw) + if len(data) != 192: + raise ValueError(f"Invalid factory entry ABI length at index {index}") + game_type, created_at, game = [ + base.decode("0x" + data[i * 64:(i + 1) * 64], kind) + for i, kind in enumerate(("uint32", "uint64", "address")) + ] + if int(game, 16) == 0: + raise ValueError(f"Zero game address at factory index {index}") + return game_type, game + + +def scan(url, factory, chain_id): + chain, snapshot = base.rpc(url, [ + ("eth_chainId", []), ("eth_getBlockByNumber", ["latest", False]), + ]) + if base.quantity(chain) != chain_id: + raise ValueError("L1 chain ID does not match the requested network") + base.require(snapshot) + if not isinstance(snapshot, dict): + raise ValueError("L1 snapshot unavailable") + number = base.quantity(snapshot.get("number")) + block_hash = base.decode(snapshot.get("hash"), "bytes32") + timestamp = base.quantity(snapshot.get("timestamp")) + block = {"blockHash": block_hash, "requireCanonical": True} + raw_count, = contract_calls(url, block, [(factory, "gameCount", "")]) + count = base.decode(raw_count, "uint256") + scan_count = min(count, MAX_SCAN) + lowest_index = count - scan_count + pending = [] + games_read = 0 + for end in range(count, lowest_index, -BATCH_SIZE): + indexes = range(end - 1, max(lowest_index, end - BATCH_SIZE) - 1, -1) + entries = contract_calls(url, block, [ + (factory, "gameAtIndex", f"{index:064x}") for index in indexes + ]) + games = [] + for index, raw in zip(indexes, entries): + try: + game_type, game = factory_entry(raw, index) + except ValueError as error: + raise ValueError(f"Factory index {index}: {error}") from None + if game_type == GAME_TYPE: + games.append(game) + if not games: + continue + statuses = contract_calls(url, block, [(game, "status", "") for game in games]) + for game, raw in zip(games, statuses): + try: + status = base.decode(raw, "uint8") + if status >= len(base.STATUSES): + raise ValueError(f"Unknown GameStatus {status}") + except ValueError as error: + raise ValueError(f"status at {game}: {error}") from None + if status == 0: + pending.append(game) + games_read += len(games) + current, = base.rpc(url, [("eth_getBlockByNumber", [hex(number), False])]) + base.require(current) + if not isinstance(current, dict) or base.decode(current.get("hash"), "bytes32") != block_hash: + raise ValueError("L1 snapshot changed during scan; rerun the scan") + return { + "l1_chain_id": chain_id, "l1_block_number": number, + "l1_block_hash": block_hash, "l1_timestamp": timestamp, + "factory": factory, "factory_game_count": count, + "factory_entries_read": scan_count, "wip1006_games_read": games_read, + "scan_limit": MAX_SCAN, "older_entries_unscanned": lowest_index, + "pending_count": len(pending), "pending_games": pending, + } + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("factory", help="dispute game factory address") + parser.add_argument("network", nargs="?", choices=NETWORKS, default="mainnet") + args = parser.parse_args() + if not re.fullmatch(r"0x[0-9a-fA-F]{40}", args.factory) or int(args.factory, 16) == 0: + parser.error("factory must be a nonzero 20-byte hexadecimal address") + chain_id, provider = NETWORKS[args.network] + url = os.environ.get(provider, "") + try: + parsed = urlsplit(url) + valid_url = parsed.scheme in ("http", "https") and bool(parsed.hostname) + except ValueError: + valid_url = False + if not valid_url: + parser.error(f"{provider} must be set to an HTTP(S) URL") + try: + report = scan(url, args.factory.lower(), chain_id) + except ValueError as error: + print(f"Scan failed: {error}", file=sys.stderr) + return 1 + print(json.dumps(report, indent=2)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.agents/skills/recovery-parent/SKILL.md b/.agents/skills/recovery-parent/SKILL.md new file mode 100644 index 000000000..4f2acc8e3 --- /dev/null +++ b/.agents/skills/recovery-parent/SKILL.md @@ -0,0 +1,37 @@ +--- +name: recovery-parent +description: Find the nearest defender-winning, ASR claim-valid game backward in a WIP-1006 lineage for the proposer and defender recovery-parent flag. +--- + +Run `python3 scripts/find_parent.py `, resolving +the script relative to this skill directory. Execute directly; read the script +only when troubleshooting. Interpret "seoplia" as sepolia. Requires Python's +standard library and the adjacent investigate-game RPC helper. No transactions +are submitted. + +Use `ETHEREUM_PROVIDER` for mainnet and `ETHEREUM_SEPOLIA_PROVIDER` for sepolia. +The script checks chain ID, initial game type 1006, and registration in the +discovered ASR's factory. Supply `--expected-factory
` when a trusted +deployment factory is available from user context. Otherwise retain the returned +provenance warning; self-reported registry/factory wiring is not canonical +deployment authentication. Never expose provider URLs or credentials. + +The starting game is included: return it if it qualifies, otherwise follow +`parentRef()` until the first game with `status() == DEFENDER_WINS` and +`ASR.isGameClaimValid(game) == true`. This includes registration, blacklist, +retirement, pause, respected-type and finality-delay checks. A qualifying legacy +game may also be returned. Stop at the ASR sentinel; it is not a recovery parent. +Cycles, unavailable getters, malformed RPC data, and exceeding 200 parent hops +fail explicitly. All reads use one latest canonical block hash so a recent +blacklist is not intentionally hidden behind a finalized snapshot. One reorg +restart is allowed; RPC requests time out after 20 seconds. + +On success, report the full `recovery_parent` address first, then +`--recovery-parent
`, network, L2 block number, parent-hop count, snapshot, +and any warning. Explain briefly that the script checks onchain claim validity; +the services additionally verify the canonical L2 root. Replacing an occupied +factory UUID still requires a new proof domain or an onchain retry mechanism. + +Exit 1 means an incomplete/failed lookup, not proof that no valid ancestor exists. +Exit 2 means the traversal reached the ASR sentinel without a qualifying game. +In either case, do not recommend a parent address from partial results. diff --git a/.agents/skills/recovery-parent/scripts/find_parent.py b/.agents/skills/recovery-parent/scripts/find_parent.py new file mode 100644 index 000000000..33d21cb3e --- /dev/null +++ b/.agents/skills/recovery-parent/scripts/find_parent.py @@ -0,0 +1,153 @@ +#!/usr/bin/env python3 +"""Find the nearest ASR claim-valid defender-winning ancestor; read-only RPC.""" + +import argparse +import importlib.util +import json +import os +from pathlib import Path +import sys +from urllib.parse import urlsplit + + +HELPER = Path(__file__).resolve().parents[2] / "investigate-game/scripts/investigate_game.py" +spec = importlib.util.spec_from_file_location("game_rpc", HELPER) +base = importlib.util.module_from_spec(spec) +spec.loader.exec_module(base) +ZERO = "0x" + "00" * 20 +NETWORKS = {"mainnet": (1, "ETHEREUM_PROVIDER"), "sepolia": (11155111, "ETHEREUM_SEPOLIA_PROVIDER")} +MAX_PARENT_HOPS = 200 +# First four bytes of Keccak-256 of the Solidity signatures. +REGISTRY_GETTERS = {"isGameRegistered": "ee658e45", "isGameClaimValid": "6c4f4467"} + + +class NoRecoveryParent(ValueError): + pass + + +def address_arg(value): + address = base.address_arg(value) + if address == ZERO: + raise argparse.ArgumentTypeError("game/factory address must be nonzero") + return address + + +def registry_bool(url, block, registry, getter, game): + data = "0x" + REGISTRY_GETTERS[getter] + game[2:].rjust(64, "0") + result, = base.rpc(url, [("eth_call", [{"to": registry, "data": data}, block])]) + value = base.decode(result, "uint8") + if value not in (0, 1): + raise ValueError(f"Invalid ABI boolean from {getter}") + return bool(value) + + +def read(url, block, game, names): + values = base.read(url, block, game, names) + for name, value in values.items(): + if isinstance(value, Exception): + raise ValueError(f"Cannot read {name} at {game}: {value}") + return values + + +def verify_snapshot(url, number, block_hash): + current, = base.rpc(url, [("eth_getBlockByNumber", [hex(number), False])]) + base.require(current) + if not isinstance(current, dict): + raise ValueError("Cannot verify snapshot block") + if base.decode(current.get("hash"), "bytes32") != block_hash: + raise base.Reorg("Snapshot changed during traversal") + + +def find_parent(url, game, chain_id, expected_factory=None): + chain, snapshot = base.rpc(url, [ + ("eth_chainId", []), ("eth_getBlockByNumber", ["latest", False]), + ]) + if base.quantity(chain) != chain_id: + raise ValueError("Provider chain ID does not match requested network") + base.require(snapshot) + if not isinstance(snapshot, dict): + raise ValueError("Snapshot block unavailable") + number = base.quantity(snapshot.get("number")) + block_hash = base.decode(snapshot.get("hash"), "bytes32") + timestamp = base.quantity(snapshot.get("timestamp")) + block = {"blockHash": block_hash, "requireCanonical": True} + identity = read(url, block, game, ["gameType", "anchorStateRegistry", "disputeGameFactory"]) + if identity["gameType"] != 1006: + raise ValueError("Initial address is not a WIP-1006 game") + registry, factory = identity["anchorStateRegistry"], identity["disputeGameFactory"] + if registry == ZERO or factory == ZERO: + raise ValueError("Initial game has a zero registry or factory") + registry_factory = read(url, block, registry, ["disputeGameFactory"])["disputeGameFactory"] + if registry_factory != factory or (expected_factory and factory != expected_factory): + raise ValueError("Game factory does not match the registry or expected deployment") + if not registry_bool(url, block, registry, "isGameRegistered", game): + raise ValueError("Initial game is not registered in the registry's factory") + + visited = set() + for hops in range(MAX_PARENT_HOPS + 1): + if game == registry: + verify_snapshot(url, number, block_hash) + raise NoRecoveryParent("Reached the ASR sentinel without a claim-valid defender-winning game") + if game == ZERO or game in visited: + raise ValueError(f"Zero parent or lineage cycle at {game}") + visited.add(game) + status = read(url, block, game, ["status"])["status"] + if status >= len(base.STATUSES): + raise ValueError(f"Unknown game status at {game}") + if status == 2 and registry_bool(url, block, registry, "isGameClaimValid", game): + l2_block = read(url, block, game, ["l2SequenceNumber"])["l2SequenceNumber"] + if l2_block >= 2**64: + raise ValueError(f"L2 block number exceeds uint64 at {game}") + verify_snapshot(url, number, block_hash) + return { + "recovery_parent": game, "l2_block_number": l2_block, "parent_hops": hops, + "status": "DEFENDER_WINS", "is_game_claim_valid": True, + "registry": registry, "factory": factory, + "snapshot": {"number": number, "hash": block_hash, "utc": base.utc(timestamp)}, + "warnings": [] if expected_factory else [ + "Registry/factory wiring verified; canonical deployment provenance not authenticated.", + ], + } + if hops == MAX_PARENT_HOPS: + raise ValueError(f"{MAX_PARENT_HOPS}-hop limit reached without a recovery parent") + game = read(url, block, game, ["parentRef"])["parentRef"] + raise ValueError("Traversal ended unexpectedly") + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("address", type=address_arg) + parser.add_argument("network", choices=NETWORKS) + parser.add_argument("--expected-factory", type=address_arg) + args = parser.parse_args() + chain_id, variable = NETWORKS[args.network] + url = os.environ.get(variable) + if not url: + parser.error(f"{variable} is not set") + try: + parsed = urlsplit(url) + if parsed.scheme not in ("http", "https") or not parsed.hostname: + raise ValueError() + except ValueError: + parser.error(f"{variable} must be an HTTP(S) URL") + try: + for attempt in range(2): + try: + report = find_parent(url, args.address, chain_id, args.expected_factory) + break + except base.Reorg: + if attempt: + raise ValueError("Snapshot changed twice; rerun when the chain is stable") from None + report["network"] = args.network + print(json.dumps(report, indent=2)) + return 0 + except NoRecoveryParent as error: + print(f"No recovery parent: {error}", file=sys.stderr) + return 2 + except ValueError as error: + print(f"Recovery lookup failed: {error}", file=sys.stderr) + return 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.agents/skills/scan-invalid-games/SKILL.md b/.agents/skills/scan-invalid-games/SKILL.md new file mode 100644 index 000000000..a9da3caa3 --- /dev/null +++ b/.agents/skills/scan-invalid-games/SKILL.md @@ -0,0 +1,34 @@ +--- +name: scan-invalid-games +description: Scan WIP1006 games inside their challenge deadline for root claims that disagree with a supplied L2 consensus RPC at finalized L2 blocks, including challenge status and game creator. +--- + +Run `python3 scripts/scan_games.py [mainnet|sepolia]`, +resolving the script relative to this skill directory. Execute it directly; reading +or recreating the script is unnecessary unless troubleshooting. + +The user supplies the dispute game factory and its corresponding L2 consensus RPC. +Default to mainnet; use sepolia when specified. L1 comes from `ETHEREUM_PROVIDER` +or `ETHEREUM_SEPOLIA_PROVIDER`, respectively, as in invalid-parent. Requires only +Python's standard library and an L1 provider supporting JSON-RPC batches. + +The scanner pins reads to one latest L1 block and uses its timestamp. It scans +factory entries backward, skipping non-1006 types, and stops at the first expired +WIP1006 challenge deadline. This assumes WIP1006 challenge deadlines are +nondecreasing with factory index, including across implementation changes. +Only L2 heights at or below `optimism_syncStatus.finalized_l2.number` are compared. +Expected roots come from `optimism_outputAtBlock` on the supplied client; they +are not independently derived or authenticated by this skill. + +Inside the original `challengeDeadline()` is the eligibility criterion, even for +already-challenged or resolved games. It does not mean another challenge can be +submitted. `claimData.deadline` is not the original challenge deadline after a +challenge. A nonzero stored challenger address determines whether a game was +challenged. No transactions are submitted. + +On success, present the JSON report as a concise mismatch table with game address, +L2 block, creator, challenged flag, game status, deadline, and claimed/expected +roots. Include the L1 snapshot, finalized L2 height, and skipped unfinalized count. +Report no mismatches only after a successful complete scan. RPC or decoding +failures exit nonzero and are not evidence of a clean scan. Do not expose RPC URLs +or credentials in the report. diff --git a/.agents/skills/scan-invalid-games/scripts/scan_games.py b/.agents/skills/scan-invalid-games/scripts/scan_games.py new file mode 100644 index 000000000..c40227190 --- /dev/null +++ b/.agents/skills/scan-invalid-games/scripts/scan_games.py @@ -0,0 +1,257 @@ +#!/usr/bin/env python3 +"""Read-only WIP1006 root comparison against finalized L2 outputs.""" + +import argparse +import json +import os +import re +import sys +import urllib.error +import urllib.parse +import urllib.request + + +BATCH_SIZE = 50 +# First four bytes of keccak256 of each Solidity signature. +SELECTORS = { + "gameCount": "0x4d1975b4", + "gameAtIndex": "0xbb8aa1fc", + "challengeDeadline": "0xca593dad", + "l2SequenceNumber": "0x99735e32", + "rootClaim": "0xbcef3b55", + "gameCreator": "0x37b1b229", + "status": "0x200d2ed2", + "claimData": "0x3ec4d4d6", +} +STATUSES = ("IN_PROGRESS", "CHALLENGER_WINS", "DEFENDER_WINS") +PROPOSALS = ( + "Unchallenged", "Challenged", "UnchallengedAndValidProofProvided", + "ChallengedAndValidProofProvided", "Resolved", +) + + +def rpc(url, calls, *, batch=True): + payload = [ + {"jsonrpc": "2.0", "id": i, "method": method, "params": params} + for i, (method, params) in enumerate(calls) + ] + try: + request = urllib.request.Request( + url, data=json.dumps(payload if batch else payload[0]).encode(), + headers={"Content-Type": "application/json"}, + ) + with urllib.request.urlopen(request, timeout=20) as response: + results = json.load(response) + except urllib.error.HTTPError as error: + raise ValueError(f"RPC HTTP failure: status {error.code}") from None + except (urllib.error.URLError, TimeoutError, OSError): + raise ValueError("RPC connection failed or timed out") from None + except (ValueError, UnicodeError): + raise ValueError("Invalid RPC URL or JSON response") from None + if not batch: + results = [results] + if not isinstance(results, list) or len(results) != len(calls): + raise ValueError("RPC returned an invalid response count") + by_id = {} + for result in results: + if not isinstance(result, dict): + raise ValueError("RPC returned an invalid response entry") + index = result.get("id") + if type(index) is not int or index not in range(len(calls)) or index in by_id: + raise ValueError("RPC returned invalid or duplicate response IDs") + if result.get("jsonrpc") != "2.0" or "error" in result or "result" not in result: + # Provider error text may contain URLs or credentials. + raise ValueError(f"RPC {calls[index][0]} failed (item {index})") + by_id[index] = result["result"] + return [by_id[i] for i in range(len(calls))] + + +def quantity(value): + if not isinstance(value, str) or not re.fullmatch(r"0x[0-9a-fA-F]+", value): + raise ValueError("Invalid hexadecimal quantity") + return int(value, 16) + + +def number(value): + if type(value) is int and value >= 0: + return value + return quantity(value) + + +def hash32(value): + if not isinstance(value, str) or not re.fullmatch(r"0x[0-9a-fA-F]{64}", value): + raise ValueError("Invalid 32-byte hash") + return value.lower() + + +def words(value, count): + if not isinstance(value, str) or not re.fullmatch(r"0x[0-9a-fA-F]{%d}" % (64 * count), value): + raise ValueError(f"Invalid ABI response: expected {count} words") + return [int(value[i:i + 64], 16) for i in range(2, len(value), 64)] + + +def address(value): + if not 0 <= value < 2**160: + raise ValueError("Invalid ABI address") + return f"0x{value:040x}" + + +def contract_calls(url, block, requests): + results = [] + for start in range(0, len(requests), BATCH_SIZE): + chunk = requests[start:start + BATCH_SIZE] + calls = [ + ("eth_call", [{"to": target, "data": SELECTORS[method] + args}, block]) + for target, method, args in chunk + ] + try: + results.extend(rpc(url, calls)) + except ValueError as error: + target, method, _ = chunk[0] + raise ValueError( + f"L1 batch starting with {method} at {target}: {error}" + ) from None + return results + + +def scan(l1_url, l2_url, factory, chain_id): + chain, snapshot = rpc(l1_url, [ + ("eth_chainId", []), ("eth_getBlockByNumber", ["latest", False]), + ]) + if quantity(chain) != chain_id: + raise ValueError("L1 chain ID does not match the requested network") + if not isinstance(snapshot, dict): + raise ValueError("L1 snapshot unavailable") + block = hex(quantity(snapshot.get("number"))) + block_hash = hash32(snapshot.get("hash")) + now = quantity(snapshot.get("timestamp")) + sync, = rpc(l2_url, [("optimism_syncStatus", [])], batch=False) + if not isinstance(sync, dict) or not isinstance(sync.get("finalized_l2"), dict): + raise ValueError("L2 finalized head unavailable") + finalized = number(sync["finalized_l2"].get("number")) + finalized_hash = hash32(sync["finalized_l2"].get("hash")) + raw_count, = contract_calls(l1_url, block, [(factory, "gameCount", "")]) + count, = words(raw_count, 1) + report = { + "l1_chain_id": chain_id, "l1_block_number": int(block, 16), + "l1_block_hash": block_hash, "l1_timestamp": now, + "factory": factory, "finalized_l2_number": finalized, + "finalized_l2_hash": finalized_hash, "factory_game_count": count, + "factory_entries_read": 0, "games_inside_deadline": 0, + "skipped_unfinalized": 0, "games_compared": 0, + "distinct_outputs_requested": 0, "mismatches": [], + } + roots = {} + stop = False + for end in range(count, 0, -BATCH_SIZE): + indexes = list(range(end - 1, max(-1, end - BATCH_SIZE - 1), -1)) + entries = contract_calls(l1_url, block, [ + (factory, "gameAtIndex", f"{index:064x}") for index in indexes + ]) + report["factory_entries_read"] += len(entries) + games = [] + for index, entry in zip(indexes, entries): + game_type, created_at, proxy = words(entry, 3) + if game_type >= 2**32 or created_at >= 2**64 or proxy == 0: + raise ValueError(f"Invalid factory entry at index {index}") + game_address = address(proxy) + if game_type == 1006: + games.append((index, game_address)) + deadlines = contract_calls(l1_url, block, [ + (game, "challengeDeadline", "") for _, game in games + ]) + for (index, game), raw_deadline in zip(games, deadlines): + deadline, = words(raw_deadline, 1) + if deadline >= 2**64: + raise ValueError(f"Invalid challenge deadline at {game}") + # Deadlines are monotonic across WIP1006 factory indexes. + if deadline <= now: + stop = True + break + report["games_inside_deadline"] += 1 + try: + raw_height, raw_root = contract_calls(l1_url, block, [ + (game, "l2SequenceNumber", ""), (game, "rootClaim", ""), + ]) + height, = words(raw_height, 1) + claimed = hash32(raw_root) + if height > finalized: + report["skipped_unfinalized"] += 1 + continue + if height not in roots: + output, = rpc(l2_url, [ + ("optimism_outputAtBlock", [hex(height)]), + ], batch=False) + if not isinstance(output, dict) or not isinstance(output.get("blockRef"), dict): + raise ValueError("Invalid L2 output response") + if number(output["blockRef"].get("number")) != height: + raise ValueError("L2 output returned a different block number") + if height == finalized and hash32(output["blockRef"].get("hash")) != finalized_hash: + raise ValueError("L2 output disagrees with the finalized head hash") + roots[height] = hash32(output.get("outputRoot")) + report["games_compared"] += 1 + if roots[height] == claimed: + continue + creator_raw, status_raw, claim_raw = contract_calls(l1_url, block, [ + (game, "gameCreator", ""), (game, "status", ""), + (game, "claimData", ""), + ]) + creator, = words(creator_raw, 1) + status, = words(status_raw, 1) + proposal, challenger, proof_deadline, bitmap, reason = words(claim_raw, 5) + if (status >= len(STATUSES) or proposal >= len(PROPOSALS) + or proof_deadline >= 2**64 or bitmap >= 2**8 or reason > 2): + raise ValueError("Invalid game status or claim data") + report["mismatches"].append({ + "game": game, "factory_index": index, "l2_block_number": height, + "root_claim": claimed, "expected_root": roots[height], + "creator": address(creator), "challenged": challenger != 0, + "challenger": address(challenger), "status": STATUSES[status], + "proposal_status": PROPOSALS[proposal], "challenge_deadline": deadline, + }) + except ValueError as error: + raise ValueError(f"game={game} index={index}: {error}") from None + if stop: + break + current, = rpc(l1_url, [("eth_getBlockByNumber", [block, False])]) + if not isinstance(current, dict) or hash32(current.get("hash")) != block_hash: + raise ValueError("L1 snapshot changed during scan; rerun the scan") + report["distinct_outputs_requested"] = len(roots) + report["mismatches"].sort(key=lambda game: game["factory_index"]) + return report + + +def valid_url(value): + try: + parsed = urllib.parse.urlsplit(value) + return parsed.scheme in ("http", "https") and bool(parsed.hostname) + except ValueError: + return False + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("factory", help="dispute game factory address") + parser.add_argument("l2_consensus_rpc", help="HTTP(S) Optimism consensus RPC URL") + parser.add_argument("network", nargs="?", choices=("mainnet", "sepolia"), default="mainnet") + args = parser.parse_args() + if not re.fullmatch(r"0x[0-9a-fA-F]{40}", args.factory) or int(args.factory, 16) == 0: + parser.error("factory must be a nonzero 20-byte hexadecimal address") + provider, chain_id = (("ETHEREUM_PROVIDER", 1) if args.network == "mainnet" + else ("ETHEREUM_SEPOLIA_PROVIDER", 11155111)) + l1_url = os.environ.get(provider) + if not l1_url or not valid_url(l1_url): + parser.error(f"{provider} must be set to an HTTP(S) URL") + if not valid_url(args.l2_consensus_rpc): + parser.error("L2 consensus RPC must be an HTTP(S) URL") + try: + report = scan(l1_url, args.l2_consensus_rpc, args.factory.lower(), chain_id) + except ValueError as error: + print(f"Scan failed: {error}", file=sys.stderr) + return 1 + print(json.dumps(report, indent=2)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.dev/update-to-v2.6.0-fh.md b/.dev/update-to-v2.6.0-fh.md new file mode 100644 index 000000000..c5cad42f8 --- /dev/null +++ b/.dev/update-to-v2.6.0-fh.md @@ -0,0 +1,118 @@ +# World-Chain v2.6.0-fh — upstream merge plan + +## Context +- Repo: `streamingfast/world-chain` (remote `origin` here), upstream `worldcoin/world-chain` (remote `upstream`, read-only). +- Goal: merge upstream tag `v2.6.0` into `release/2.x`, release as `v2.6.0-fh3.1`. +- Last merged upstream: `v2.4.3`, released up to `v2.4.3-fh3.1-4` (keccak preimage filter). +- Upstream skipped v2.5.x; `v2.4.4` and `v2.4.5` are in the range (84 commits). +- All PRs opened as **draft** PRs (user request). +- The Firehose ExEx is gone from the reth/op-reth forks: `FIRE INIT` and the genesis block are + emitted from `on_component_initialized`. World-chain must adopt the same hook (it used + `on_node_started` for genesis, which can run after the engine traced a block). + +## Dependency pins + +| | v2.4.3 | v2.6.0 | +| --- | --- | --- | +| reth | `op-rs/reth` rev `aef8d3ef` | `ethereum-optimism/reth` rev `0fbe4285` (**patch URL key changes**) | +| optimism monorepo | rev `96ffbb2a` | rev `da6d3252` = tag `op-reth/v2.6.0` | +| alloy-evm | 0.37.0 | 0.38.0 | +| revm | 41 | 42 | +| alloy | =2.1.1 | 2.3.0 | +| reth-codecs / reth-primitives-traits (crates.io) | 0.5.0 | 0.6.0 | + +The op-reth line already moved to these revs: reth `op-reth-v2.6.1-fh3.1` (`d4875c13`, on +`ethereum-optimism/reth` `0fbe4285`) and optimism `op-reth-v2.6.1-fh3.1` (on `op-reth/v2.6.1` = +`da6d3252` + 3 security commits). + +## Work items + +### streamingfast/reth +- [x] Branch `bump/world-chain-v2.6.0` off `release/world-chain-2.x`, merge `release/optimism-2.x` + (brings `0fbe4285`, the reth v2.5.2 adaptations, and the ExEx removal). Merge commit + `6c161666`. Only `CHANGELOG.md` conflicted (both lines carry the same keccak-filter + entries under different section names). The tree outside `CHANGELOG.md` is byte-identical + to `op-reth-v2.6.1-fh3.1` (`d4875c13`). +- [x] CHANGELOG section `world-chain-v2.6.0-fh3.1`. +- [x] `cargo test -p reth-firehose -p reth-firehose-tests`: 35 passed, 0 failed. Branch pushed. +- [x] streamingfast/reth#82 merged as `29828ae2`, tagged `world-chain-v2.6.0-fh3.1`. + +### streamingfast/optimism +- [x] Branch `bump/world-chain-v2.6.0` off `release/world-chain-2.x`, merge `op-reth/v2.6.0` + (`eadfc591`). Conflicts: `rust/Cargo.toml` (reth pin block, taken from + `op-reth-v2.6.1-fh3.1`; `rust/Cargo.toml` is identical at `op-reth/v2.6.0` and `v2.6.1`) and + `rust/Cargo.lock` (started from upstream's, regenerated). +- [x] Cherry-picked the op-reth-2.x Firehose adaptations (`15364bbb90`, `32233cea27`, + `3c054206ad`). `rust/op-reth/` is now byte-identical to `op-reth-v2.6.1-fh3.1`. +- [x] Reth pinned with `branch = "bump/world-chain-v2.6.0"` (flip to the tag once it exists). +- [x] `firehose-tracer` locked at 5.5.0. A fresh resolve picks 5.7.0, which adds a required + `TxEvent.account_abstraction_trx_input` field, and `reth-firehose` fails to compile. +- [x] `cargo check -p op-reth -p reth-optimism-firehose -p alloy-op-evm` clean; + `cargo test -p reth-optimism-firehose -p alloy-op-evm`: 86 passed. Branch pushed. +- [x] Reth pin flipped to the tag (`f32db0bb`). streamingfast/optimism#27 merged as `b8bbd08e`, + tagged `world-chain-v2.6.0-fh3.1`. + +### streamingfast/world-chain +- [x] Branch `bump/v2.6.0` off `release/2.x`, `git merge v2.6.0`. + - `AGENTS.md` (add/add): upstream added its own `AGENTS.md`. Took upstream's verbatim and moved + our fork notes to `AGENTS.sf.md`; `CLAUDE.md` (ours) imports both. Future upstream edits to + `AGENTS.md` merge cleanly. + - `Cargo.lock`: started from upstream's v2.6.0 lock, let cargo swap sources to the forks, + `cargo update -p firehose-tracer --precise 5.5.0`. One reth graph (105 crates from + `streamingfast/reth`), one optimism graph (`streamingfast/optimism`), no + `ethereum-optimism/*` source left. + - Auto-merged and checked by hand: `crates/evm/src/execution/executor.rs` (our + `execute_transaction_with_commit_condition` forward survives next to upstream's new + `State` witness snapshot), `crates/evm/src/lib.rs`, `crates/node/src/context.rs`, + `crates/node/src/payload.rs`, `crates/devnet/src/full_stack.rs` (our `retry_until`), + `crates/builder/benches/flashblock_building_live_node.rs` (`.inner`). +- [x] Re-keyed `[patch."https://github.com/op-rs/reth"]` → `[patch."https://github.com/ethereum-optimism/reth"]`. +- [x] Optimism patch block: added `kona-sp1-host-utils` and `kona-sp1-client-utils` (the latter is + pulled in by `proofs/measured/core`, which the root workspace builds host-side). Did not + patch `reth-optimism-cli`: upstream declares it but no crate uses it, so cargo reports the + patch as unused. `alloy-evm` → `v0.38.0-sf`. +- [x] Firehose init + genesis moved to `on_component_initialized` in both launch paths of + `crates/node/src/proof_history.rs`; the `init_blockchain(chain_id)` call in `main.rs` and + the `reth-chainspec` dependency of `bin/world-chain` are gone. No Firehose ExEx exists in + world-chain; the only ExEx is upstream's `proofs-history`. +- [x] `cargo check -p world-chain` clean (only upstream's unused-workspace-dependency warnings). +- [x] `cargo test -p world-chain-evm -p world-chain-node`: 23 passed, 0 failed. + `cargo check -p world-chain-builder --benches` clean. +- [x] Battlefield `world-chain-devnet` (battlefield-ethereum `master` `ffd9260`, fireeth `d0f4ef2`): + 78 passing, 23 pending, 1 failing. No snapshot changed. `FIRE INIT` read, genesis block + emitted, the node kept up with the sequencer at 2 s blocks. + - The 23 pending tests are skipped by network (Amsterdam, blobs, BSC, Arc assets). + - The failure is `zz_compare_blocks` (`fireeth tools compare-blocks-rpc` over #1–#277): all 277 + blocks differ, and only in `transaction_traces[N].blob_gas` and + `transaction_traces[N].receipt.blob_gas_used`, which the RPC side has and the Firehose block + does not. This is a false diff from the compare tool, not a node change: under Jovian, + op-reth's receipt builder puts the transaction's DA footprint in receipt `blobGasUsed` + (`op-reth/crates/rpc/src/eth/receipt.rs`, already present at `96ffbb2a`/v2.4.3), and + firehose-ethereum `44ac168` (2026-09-29, after the v2.4.3 run) started copying receipt + `blobGasUsed` into `blob_gas`/`blob_gas_used` when rebuilding a block from RPC. The block + header's `blobGasUsed` is 0 and the transactions are not EIP-4844. The fix belongs in + `compare-blocks-rpc` (skip the field on OP Jovian chains), not here. + - The v2.4.3 diff on `set_code_authorizations` (blocks 399/401) is gone (fireeth `d5a5e39`). +- [x] `CHANGELOG.sf.md`, `ACTIVATIONS.md`, `Dockerfile.sf` toolchain note (nightly-2026-10-10). +- [x] Pins flipped to both `world-chain-v2.6.0-fh3.1` tags; lock resolves 105 reth crates and 47 + optimism crates from the tags. `cargo check -p world-chain` and the 23 tests pass again. +- [x] streamingfast/world-chain#12 merged, tagged `v2.6.0-fh3.1`. + +## Firehose bug pattern review + +1. **Serial tracing.** The engine-API path goes through `OpFirehoseEngineValidator`, the same code + as `op-reth-v2.6.1-fh3.1`, which runs the sequential traced executor when the tracer is on. World + Chain configures no Amsterdam timestamp, so no block carries an EIP-7928 access list. World + Chain's own BAL executor (`crates/evm/src/execution/bal.rs`) is used by flashblock validation + (`crates/validator`), which is not traced; upstream's changes there (#1196 received-BAL hash + check, #1197 cumulative gas/DA limits) stay inside flashblock validation. No new spawn or + system call on the traced path in `v2.4.3..v2.6.0`. +2. **Emit after acceptance.** Unchanged from op-reth: `pending_tracer` / `mark_verified()`. The + new validator checks in world-chain are on flashblocks, not on canonical `newPayload`. +3. **Activations.** `ACTIVATIONS.md` created. Karst is live on mainnet since 2026-09-21. Tropo and + Strato are defined but not scheduled and gate no execution code. OP Lagoon maps to + `ForkCondition::Never` for World Chain. +4. **Unmapped fields.** No new transaction type reaches World Chain blocks. Known gap carried from + op-reth: PostExec `0x7D` (Lagoon) would hit the `expect` in `reth_firehose::mapper`. + `firehose-tracer` 5.7.0 adds `TxEvent.account_abstraction_trx_input` (for Base EIP-8130); the + forks stay on 5.5.0, and moving to 5.7.0 needs a `reth-firehose` change first. diff --git a/.github/actionlint.yaml b/.github/actionlint.yaml new file mode 100644 index 000000000..6b1673c76 --- /dev/null +++ b/.github/actionlint.yaml @@ -0,0 +1,3 @@ +self-hosted-runner: + labels: + - arc-public-8xlarge-amd64-runner diff --git a/.github/actions/docker-build-push-digest/action.yml b/.github/actions/docker-build-push-digest/action.yml index 45f2bb535..e43b87a51 100644 --- a/.github/actions/docker-build-push-digest/action.yml +++ b/.github/actions/docker-build-push-digest/action.yml @@ -51,6 +51,10 @@ inputs: more than one image so their digest artifacts do not collide. required: false default: digests + no_cache_filters: + description: Build stages to exclude from the cache. + required: false + default: "" runs: using: composite @@ -113,6 +117,7 @@ runs: tags: ${{ inputs.registry }}/${{ inputs.image_name }} platforms: ${{ inputs.platform }} labels: ${{ steps.meta.outputs.labels }} + no-cache-filters: ${{ inputs.no_cache_filters }} cache-from: | type=s3,region=${{ inputs.aws_region }},bucket=${{ inputs.sccache_bucket }},prefix=${{ env.BUILDKIT_CACHE_PREFIX }},name=${{ env.CACHE_SCOPE }} type=s3,region=${{ inputs.aws_region }},bucket=${{ inputs.sccache_bucket }},prefix=${{ env.BUILDKIT_CACHE_PREFIX }},name=main diff --git a/.github/review-policy.json b/.github/review-policy.json new file mode 100644 index 000000000..8367f48fd --- /dev/null +++ b/.github/review-policy.json @@ -0,0 +1,33 @@ +{ + "defaultRisk": "important", + "riskRules": [ + { "risk": "critical", "patterns": ["crates/builder/**", "crates/chainspec/**", "crates/evm/**", "crates/node/**", "crates/payload/**", "crates/primitives/**", "crates/validator/**", "proofs/protocol/**", "proofs/services/challenger/**", "proofs/services/defender/**"] }, + { "risk": "low", "patterns": ["README.md", "LICENSE*", "assets/**", "book/**", "docs/**", "**/README.md", "**/benches/**", "**/tests/**", "**/test_fixtures/**", "pkg/contracts/test/**", "pkg/contracts/etc/**", "crates/pbh/**", "crates/devnet/**", "crates/test-utils/**", "e2e-tests/**", "proofs/debug/**", "proofs/it/**", "scripts/stress/**"] }, + { "risk": "important", "patterns": ["docs/proof/**", "docs/review-policy.md", "proofs/measurements.json"] }, + { "risk": "critical", "patterns": ["pkg/contracts/src/dispute/**", "proofs/measured/**", "proofs/backends/sp1/elfs/**", "proofs/succinct/programs/**", ".github/workflows/**", ".github/actions/**", ".github/review-policy.json", ".github/actionlint.yaml", ".github/CODEOWNERS", "CODEOWNERS", "docs/CODEOWNERS", "AGENTS.md", "**/AGENTS.md", ".cursor/**", ".agents/**", "scripts/review-policy/**", "scripts/build-eif.sh", "scripts/safe-operation.py", "pkg/contracts/scripts/**", "justfiles/proof.just", "flake.nix", "flake.lock", "rust-toolchain.toml", "Cargo.toml", "Dockerfile.prover"] } + ], + "ci": [ + { + "id": "rust", "workflow": "rust-ci.yml", "jobs": ["cargo-tests", "clippy", "docs"], + "patterns": ["**/*.rs", "**/Cargo.toml", "**/Cargo.lock", "rust-toolchain.toml", ".cargo/**", ".config/nextest.toml", "clippy.toml", "rustfmt.toml", "Justfile", "justfiles/rust.just", "justfiles/contracts.just", "justfiles/proof.just", "pkg/contracts/src/**", "crates/**/res/**", ".github/workflows/rust-ci.yml"] + }, + { + "id": "contracts", "workflow": "foundry.yml", "jobs": ["Foundry project"], + "patterns": ["pkg/contracts/**", ".gitmodules", "Justfile", "justfiles/contracts.just", ".github/workflows/foundry.yml"] + }, + { + "id": "sp1", "workflow": "verify-measurements.yml", "jobs": ["detect measurement-affecting changes", "verify vkeys match source"], + "patterns": ["proofs/measured/sp1-programs/**", "proofs/measured/core/**", "proofs/measured/kona-client/**", "proofs/backends/sp1/elfs/**", "proofs/protocol/**", "proofs/measurements.json", "Cargo.toml", "Cargo.lock", "Justfile", "justfiles/proof.just", "rust-toolchain.toml", ".cargo/**", ".github/workflows/verify-measurements.yml"] + }, + { + "id": "nitro", "workflow": "verify-measurements.yml", "jobs": ["detect measurement-affecting changes", "verify PCRs match source"], + "patterns": ["proofs/measured/nitro-enclave/**", "proofs/measured/core/**", "proofs/measured/kona-client/**", "proofs/measurements.json", "flake.nix", "flake.lock", "rust-toolchain.toml", "scripts/build-eif.sh", "Justfile", "justfiles/proof.just", ".github/actions/install-nix/**", ".github/workflows/verify-measurements.yml"] + }, + { + "id": "supply-chain", "workflow": "supply-chain.yml", "jobs": ["audit measured enclave dependencies"], + "patterns": ["proofs/measured/**", "justfiles/proof.just", ".github/workflows/supply-chain.yml"] + }, + { "id": "policy", "workflow": "review-policy-tests.yml", "jobs": ["review-policy-tests"], "patterns": ["**"] }, + { "id": "large-files", "workflow": "large-files.yml", "jobs": ["check-large-files"], "patterns": ["**"] } + ] +} diff --git a/.github/workflows/acceptance-tests.yml b/.github/workflows/acceptance-tests.yml index ebcfbbcd2..8429b8cac 100644 --- a/.github/workflows/acceptance-tests.yml +++ b/.github/workflows/acceptance-tests.yml @@ -64,15 +64,15 @@ jobs: include_in_all: true rpc_url: https://wc-node-sepolia.worldcoin.dev acceptance_profile: smoke - bundler_rpc_url: https://rundler-stage.worldcoin.dev + bundler_rpc_url: "" erc4337_rpc_url: https://worldchain-mainnet.g.alchemy.com/public entry_point: "0x0000000071727De22E5E9d8BAf0edAc6f37da032" safe_4337_module: "0x70673A08a5B1086585d39979Fb2d84FDC0bB6Aaf" safe_4337_wallet_deployer: "0xd1f0B51940DbD6e73891D2a41Ef14483fDC5Cb6e" expected_chain_id: "4801" - karst_enabled: "false" - karst_deposit_enabled: "false" - optimism_portal: "" + karst_enabled: "true" + karst_deposit_enabled: "true" + optimism_portal: "0xFf6EBa109271fe6d4237EeeD4bAb1dD9A77dD1A4" allow_failure: false - network: betanet environment: dev diff --git a/.github/workflows/benchmarks.yml b/.github/workflows/benchmarks.yml deleted file mode 100644 index e2e904823..000000000 --- a/.github/workflows/benchmarks.yml +++ /dev/null @@ -1,263 +0,0 @@ -name: Benchmark Regression Check - -on: - pull_request: - paths: - - 'crates/payload/**' - - 'crates/validator/**' - - 'crates/builder/**' - - 'Cargo.toml' - - 'Cargo.lock' - - 'rust-toolchain.toml' - - '.cargo/**' - - '.github/workflows/benchmarks.yml' - workflow_dispatch: - -permissions: - contents: read - pull-requests: write - id-token: write - -env: - CARGO_TERM_COLOR: always - BENCH_NAME: flashblock_validation_synthetic - AWS_REGION: us-east-1 - -jobs: - benchmark: - runs-on: arc-public-8xlarge-amd64-runner - environment: - name: dev - deployment: false - timeout-minutes: 60 - env: - RUSTC_WRAPPER: sccache - SCCACHE_BUCKET: crypto-dev-us-east-1-workflow-build-cache - SCCACHE_REGION: us-east-1 - steps: - - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 - with: - fetch-depth: 0 - - - uses: dtolnay/rust-toolchain@2c7215f132e9ebf062739d9130488b56d53c060c # master - with: - toolchain: nightly-2026-07-01 - - - name: Setup mold - uses: rui314/setup-mold@9c9c13bf4c3f1adef0cc596abc155580bcb04444 # v1 - - - name: Configure AWS credentials - uses: aws-actions/configure-aws-credentials@7474bc4690e29a8392af63c5b98e7449536d5c3a # v4 - with: - aws-region: ${{ env.AWS_REGION }} - role-to-assume: arn:aws:iam::348981876543:role/oidc/github-deploy - - - name: Setup sccache - uses: mozilla-actions/sccache-action@89e9040de88b577a072e3760aaf59f585da083af # v0.0.5 - - - name: Cache - uses: actions/cache@caa296126883cff596d87d8935842f9db880ef25 # v5 - continue-on-error: false - with: - path: | - ~/.cargo/registry/index/ - ~/.cargo/registry/cache/ - ~/.cargo/git/db/ - key: cargo-bench-${{ hashFiles('**/Cargo.lock') }} - restore-keys: | - cargo-bench- - cargo-test- - - - name: Install critcmp - run: cargo install critcmp --locked - - # Benchmark the base revision and the PR revision in the same job so - # both measurements run on the same machine under similar conditions. - - name: Run base benchmarks - if: github.event_name == 'pull_request' - env: - BASE_SHA: ${{ github.event.pull_request.base.sha }} - run: | - git checkout --detach "$BASE_SHA" - if [ -f "crates/validator/benches/${BENCH_NAME}.rs" ]; then - BENCH_PACKAGE=world-chain-validator - elif [ -f "crates/builder/benches/${BENCH_NAME}.rs" ]; then - BENCH_PACKAGE=world-chain-builder - else - echo "::error::Could not find ${BENCH_NAME} benchmark" - exit 1 - fi - echo "Running ${BENCH_NAME} from ${BENCH_PACKAGE}" - mold -run cargo bench --package "$BENCH_PACKAGE" --bench "$BENCH_NAME" -- --save-baseline base - - - name: Run PR benchmarks - if: github.event_name == 'pull_request' - env: - PR_SHA: ${{ github.sha }} - run: | - git checkout --detach "$PR_SHA" - if [ -f "crates/validator/benches/${BENCH_NAME}.rs" ]; then - BENCH_PACKAGE=world-chain-validator - elif [ -f "crates/builder/benches/${BENCH_NAME}.rs" ]; then - BENCH_PACKAGE=world-chain-builder - else - echo "::error::Could not find ${BENCH_NAME} benchmark" - exit 1 - fi - echo "Running ${BENCH_NAME} from ${BENCH_PACKAGE}" - mold -run cargo bench --package "$BENCH_PACKAGE" --bench "$BENCH_NAME" -- --save-baseline pr - - - name: Run benchmarks - if: github.event_name == 'workflow_dispatch' - run: | - if [ -f "crates/validator/benches/${BENCH_NAME}.rs" ]; then - BENCH_PACKAGE=world-chain-validator - elif [ -f "crates/builder/benches/${BENCH_NAME}.rs" ]; then - BENCH_PACKAGE=world-chain-builder - else - echo "::error::Could not find ${BENCH_NAME} benchmark" - exit 1 - fi - echo "Running ${BENCH_NAME} from ${BENCH_PACKAGE}" - mold -run cargo bench --package "$BENCH_PACKAGE" --bench "$BENCH_NAME" - - # Compare against main baseline if available - - name: Check for regressions - if: github.event_name == 'pull_request' - run: | - echo "=== Full Benchmark Comparison ===" - critcmp base pr - - echo "" - echo "=== Checking for >10% regressions ===" - filtered=$(critcmp base pr --threshold 10 2>&1 || true) - - # critcmp always exits 0 - we must parse output to detect regressions. - # In the output, the FASTER baseline gets ratio 1.00. - # If 'base' shows 1.00 in a data row, 'pr' is slower (regression). - # Data rows start after the header (line 1) and separator (line 2). - regressions=$(echo "$filtered" | awk 'NR > 2 && NF > 0' | grep -E '^\S+\s+1\.00\s' || true) - - if [ -n "$regressions" ]; then - echo "" - echo "Regressions detected (>10% slower than base):" - echo "$filtered" - echo "" - echo "::error::Performance regression detected - pr is >10% slower than the base branch in the same workflow run" - exit 1 - fi - - echo "No significant regressions detected." - - # Post results as PR comment - - name: Post benchmark comparison - if: always() && github.event_name == 'pull_request' - uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7 - env: - THRESHOLD: '10' - with: - script: | - const { execSync } = require('child_process'); - const threshold = Number(process.env.THRESHOLD); - - // Parse critcmp's column output into structured rows. Each data row - // holds a benchmark name followed by, per baseline, a ratio (the - // fastest baseline is 1.00) and an estimate token containing "±". - // We anchor on the "±" tokens so any optional throughput columns - // are skipped reliably. - function parse(output) { - const rows = []; - for (const line of output.split('\n')) { - const tokens = line.trim().split(/\s+/).filter(Boolean); - const timeIdx = tokens.flatMap((t, i) => (t.includes('±') ? [i] : [])); - if (timeIdx.length !== 2) continue; // header/separator/blank - const [bi, pi] = timeIdx; - const name = tokens.slice(0, bi - 1).join(' '); - if (!name) continue; - rows.push({ - name, - baseRatio: Number(tokens[bi - 1]), - baseTime: tokens[bi], - prRatio: Number(tokens[pi - 1]), - prTime: tokens[pi], - }); - } - return rows; - } - - function render(rows) { - const header = - '| Benchmark | Base | PR | Change |\n| --- | --- | --- | --- |'; - const lines = rows.map((r) => { - // Ratios are relative to the fastest baseline; PR vs base delta. - const pct = - Number.isFinite(r.baseRatio) && r.baseRatio > 0 - ? (r.prRatio / r.baseRatio - 1) * 100 - : NaN; - let change = 'n/a'; - if (Number.isFinite(pct)) { - const sign = pct >= 0 ? '+' : ''; - let icon = '🟢'; // faster - if (pct > threshold) icon = '🔴'; - else if (pct > 0) icon = '🟡'; - change = `${icon} ${sign}${pct.toFixed(2)}%`; - } - return `| \`${r.name}\` | ${r.baseTime} | ${r.prTime} | ${change} |`; - }); - return [header, ...lines].join('\n'); - } - - try { - const output = execSync('critcmp base pr --color never', { - encoding: 'utf-8', - }); - const rows = parse(output); - const table = rows.length - ? render(rows) - : '_Could not parse benchmark output; see raw results below._'; - - const body = [ - '## Benchmark Results', - '', - 'Base and PR measured on the same runner in the same workflow run.', - '', - table, - '', - `> 🔴 regression > ${threshold}%  ·  🟡 slower  ·  🟢 faster. A regression > ${threshold}% fails the check.`, - '', - '
Raw critcmp output', - '', - '```', - output.trimEnd(), - '```', - '', - '
', - ].join('\n'); - - // Check for existing comment to update - const { data: comments } = await github.rest.issues.listComments({ - issue_number: context.issue.number, - owner: context.repo.owner, - repo: context.repo.repo, - }); - const existing = comments.find((c) => - c.body.startsWith('## Benchmark Results') - ); - if (existing) { - await github.rest.issues.updateComment({ - comment_id: existing.id, - owner: context.repo.owner, - repo: context.repo.repo, - body, - }); - } else { - await github.rest.issues.createComment({ - issue_number: context.issue.number, - owner: context.repo.owner, - repo: context.repo.repo, - body, - }); - } - } catch (e) { - console.log('Could not post benchmark comment:', e.message); - } diff --git a/.github/workflows/deploy-alphanet-build.yml b/.github/workflows/deploy-alphanet-build.yml index 68ff98d0e..19f679030 100644 --- a/.github/workflows/deploy-alphanet-build.yml +++ b/.github/workflows/deploy-alphanet-build.yml @@ -122,6 +122,7 @@ jobs: context: source dockerfile: source/Dockerfile cache_scope: ${{ steps.target.outputs.cache_scope }} + no_cache_filters: runtime merge: name: merge multi-arch manifest diff --git a/.github/workflows/docker-e2e-withdrawal.yml b/.github/workflows/docker-e2e-withdrawal.yml new file mode 100644 index 000000000..3bc0e39a1 --- /dev/null +++ b/.github/workflows/docker-e2e-withdrawal.yml @@ -0,0 +1,96 @@ +name: docker-e2e-withdrawal + +on: + workflow_dispatch: + push: + branches: [main] + paths: + - "e2e-tests/e2e-withdrawal/**" + - "**/Cargo.toml" + - "**/Cargo.lock" + - "rust-toolchain.toml" + - ".cargo/**" + - "Dockerfile.e2e-withdrawal" + - ".dockerignore" + - ".github/workflows/docker-e2e-withdrawal.yml" + - ".github/actions/docker-build-push-digest/**" + - ".github/actions/docker-merge-manifest/**" + +env: + IMAGE_NAME: ${{ github.repository }}-e2e-withdrawal + REGISTRY: ghcr.io + AWS_REGION: us-east-1 + SCCACHE_BUCKET: crypto-dev-us-east-1-workflow-build-cache + +permissions: + contents: read + +concurrency: + group: docker-e2e-withdrawal-${{ github.sha }} + cancel-in-progress: false + +jobs: + build-and-push: + if: github.repository == 'worldcoin/world-chain' + timeout-minutes: 120 + environment: + name: dev + deployment: false + permissions: + contents: read + packages: write + id-token: write + strategy: + fail-fast: false + matrix: + include: + - runner: arc-public-8xlarge-amd64-runner + platform: linux/amd64 + - runner: ubuntu-24.04-arm + platform: linux/arm64 + runs-on: ${{ matrix.runner }} + steps: + - name: Check out source + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + ref: ${{ github.sha }} + persist-credentials: false + - name: Build and push digest + uses: ./.github/actions/docker-build-push-digest + with: + platform: ${{ matrix.platform }} + registry: ${{ env.REGISTRY }} + image_name: ${{ env.IMAGE_NAME }} + aws_region: ${{ env.AWS_REGION }} + sccache_bucket: ${{ env.SCCACHE_BUCKET }} + dockerfile: Dockerfile.e2e-withdrawal + git_sha: ${{ github.sha }} + + merge: + needs: build-and-push + runs-on: ubuntu-latest + timeout-minutes: 15 + permissions: + contents: read + packages: write + steps: + - name: Check out workflow actions + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + ref: ${{ github.sha }} + persist-credentials: false + - name: Merge multi-architecture manifest + id: merge + uses: ./.github/actions/docker-merge-manifest + with: + registry: ${{ env.REGISTRY }} + image_name: ${{ env.IMAGE_NAME }} + tags: type=raw,value=sha-${{ github.sha }} + - name: Summarize published image + env: + IMAGE: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} + SHA: ${{ github.sha }} + DIGEST: ${{ steps.merge.outputs.digest }} + run: | + printf 'Image: `%s:sha-%s`\n\nManifest: `%s@%s`\n' \ + "$IMAGE" "$SHA" "$IMAGE" "$DIGEST" >> "$GITHUB_STEP_SUMMARY" diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 77678be10..18b0d21f2 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -72,6 +72,7 @@ jobs: image_name: ${{ env.IMAGE_NAME }} aws_region: ${{ env.AWS_REGION }} sccache_bucket: ${{ env.SCCACHE_BUCKET }} + no_cache_filters: runtime merge: runs-on: ubuntu-latest diff --git a/.github/workflows/foundry.yml b/.github/workflows/foundry.yml index 735024ec5..9ee671095 100644 --- a/.github/workflows/foundry.yml +++ b/.github/workflows/foundry.yml @@ -8,11 +8,15 @@ on: paths: - "pkg/contracts/**" - ".gitmodules" + - "Justfile" + - "justfiles/contracts.just" - ".github/workflows/foundry.yml" pull_request: paths: - "pkg/contracts/**" - ".gitmodules" + - "Justfile" + - "justfiles/contracts.just" - ".github/workflows/foundry.yml" workflow_dispatch: diff --git a/.github/workflows/fuzz.yml b/.github/workflows/fuzz.yml index dc6b73ed9..56246b8db 100644 --- a/.github/workflows/fuzz.yml +++ b/.github/workflows/fuzz.yml @@ -44,7 +44,7 @@ jobs: - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 - uses: dtolnay/rust-toolchain@2c7215f132e9ebf062739d9130488b56d53c060c # master with: - toolchain: nightly-2026-07-01 + toolchain: nightly-2026-10-10 targets: x86_64-unknown-linux-gnu - uses: arduino/setup-protoc@c65c819552d16ad3c9b72d9dfd5ba5237b9c906b # v3 with: @@ -80,7 +80,7 @@ jobs: - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 - uses: dtolnay/rust-toolchain@2c7215f132e9ebf062739d9130488b56d53c060c # master with: - toolchain: nightly-2026-07-01 + toolchain: nightly-2026-10-10 targets: x86_64-unknown-linux-gnu - uses: arduino/setup-protoc@c65c819552d16ad3c9b72d9dfd5ba5237b9c906b # v3 with: diff --git a/.github/workflows/release-proof.yml b/.github/workflows/release-proof.yml index 9baf9637d..2eebe6637 100644 --- a/.github/workflows/release-proof.yml +++ b/.github/workflows/release-proof.yml @@ -246,7 +246,7 @@ jobs: # https://sp1.succinct.xyz bootstrap script, which fetches sp1up from `main` unpinned. - name: Install SP1 toolchain env: - SP1_VERSION: "v6.3.1" + SP1_VERSION: "v6.8.1" SP1UP_SHA256: 55d4f6ef8e79e04a7ccd064f75c6a6b44a1694b21cd41aa8e7d0d53eb880a71d run: | set -euo pipefail diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 935ea6b5f..142381470 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -112,6 +112,7 @@ jobs: sccache_bucket: ${{ env.SCCACHE_BUCKET }} git_sha: ${{ needs.prepare-release.outputs.SHA }} cache_scope: ${{ inputs.ref }} + no_cache_filters: runtime merge: runs-on: ubuntu-latest diff --git a/.github/workflows/review-policy-events.yml b/.github/workflows/review-policy-events.yml new file mode 100644 index 000000000..2bf746cad --- /dev/null +++ b/.github/workflows/review-policy-events.yml @@ -0,0 +1,15 @@ +name: Review policy events + +on: + pull_request_review: + types: [submitted, edited, dismissed] + +permissions: {} + +jobs: + notify: + runs-on: ubuntu-latest + timeout-minutes: 2 + steps: + # The privileged controller reads live API state, never this run's artifacts or code. + - run: 'true' diff --git a/.github/workflows/review-policy-tests.yml b/.github/workflows/review-policy-tests.yml new file mode 100644 index 000000000..c1ed556ca --- /dev/null +++ b/.github/workflows/review-policy-tests.yml @@ -0,0 +1,41 @@ +name: Review policy tests + +on: + pull_request: + push: + branches: [main] + workflow_dispatch: + +permissions: + contents: read + +jobs: + test: + name: review-policy-tests + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + persist-credentials: false + - name: Test policy and GitHub orchestration + run: node --test scripts/review-policy/*.test.cjs + - name: Install actionlint + run: | + archive="$RUNNER_TEMP/actionlint.tar.gz" + curl --fail --location --retry 3 --connect-timeout 10 --max-time 60 \ + https://github.com/rhysd/actionlint/releases/download/v1.7.12/actionlint_1.7.12_linux_amd64.tar.gz \ + --output "$archive" + printf '%s %s\n' '8aca8db96f1b94770f1b0d72b6dddcb1ebb8123cb3712530b08cc387b349a3d8' "$archive" | sha256sum --check + mkdir -p "$RUNNER_TEMP/actionlint-bin" + tar -xzf "$archive" -C "$RUNNER_TEMP/actionlint-bin" actionlint + echo "$RUNNER_TEMP/actionlint-bin" >> "$GITHUB_PATH" + - name: Lint review and affected CI workflows + run: >- + actionlint -shellcheck='' -pyflakes='' + .github/workflows/review-policy.yml + .github/workflows/review-policy-events.yml + .github/workflows/review-policy-tests.yml + .github/workflows/rust-ci.yml + .github/workflows/foundry.yml + .github/workflows/verify-measurements.yml diff --git a/.github/workflows/review-policy.yml b/.github/workflows/review-policy.yml new file mode 100644 index 000000000..c94e64698 --- /dev/null +++ b/.github/workflows/review-policy.yml @@ -0,0 +1,108 @@ +name: Review policy + +on: + push: + branches: [main] + pull_request_target: + branches: [main] + types: [opened, synchronize, reopened, ready_for_review, edited] + issue_comment: + types: [created, edited, deleted] + check_run: + types: [created, completed, rerequested] + workflow_run: + workflows: ["Review policy events", "Rust CI", "CI", "verify-measurements", "Review policy tests", "supply-chain", "Large Files"] + types: [in_progress, completed] + workflow_dispatch: + inputs: + pr: + description: Pull request number to re-evaluate + type: string + required: true + +permissions: {} + +jobs: + request: + if: github.event_name == 'pull_request_target' + name: request-review-policy + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + actions: write + steps: + - uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7 + with: + script: | + await github.rest.actions.createWorkflowDispatch({ + ...context.repo, + workflow_id: 'review-policy.yml', + ref: 'main', + inputs: { pr: String(context.payload.pull_request.number) }, + request: { timeout: 20000 }, + }); + + targets: + if: >- + github.event_name != 'pull_request_target' && + (github.event_name != 'issue_comment' || github.event.issue.pull_request != null) && + (github.event_name != 'check_run' || github.event.check_run.app.slug == 'cursor') && + (github.event_name != 'workflow_run' || github.event.action == 'completed' || + (github.event.action == 'in_progress' && github.event.workflow_run.run_attempt > 1)) + runs-on: ubuntu-latest + timeout-minutes: 70 + permissions: + contents: read + pull-requests: read + outputs: + prs: ${{ steps.targets.outputs.prs }} + base: ${{ steps.base.outputs.sha }} + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + ref: main + persist-credentials: false + - id: base + run: echo "sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT" + - id: targets + uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7 + with: + script: | + const { targets } = require('./scripts/review-policy/github.cjs'); + core.setOutput('prs', JSON.stringify(await targets({ github, context, core }))); + + evaluate: + needs: targets + if: needs.targets.outputs.prs != '' && needs.targets.outputs.prs != '[]' + strategy: + fail-fast: false + matrix: + pr: ${{ fromJSON(needs.targets.outputs.prs) }} + concurrency: + group: review-policy-pr-${{ matrix.pr }} + cancel-in-progress: true + runs-on: ubuntu-latest + timeout-minutes: 105 + permissions: + actions: read + checks: write + contents: read + issues: read + pull-requests: read + statuses: write + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + ref: ${{ needs.targets.outputs.base }} + persist-credentials: false + - uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7 + env: + REVIEW_POLICY_BASE_SHA: ${{ needs.targets.outputs.base }} + REVIEW_POLICY_PR: ${{ matrix.pr }} + REVIEW_POLICY_TEAM_TOKEN: ${{ secrets.REVIEW_POLICY_TEAM_TOKEN }} + with: + script: | + const { evaluate } = require('./scripts/review-policy/github.cjs'); + const token = process.env.REVIEW_POLICY_TEAM_TOKEN; + const teamGithub = token ? new github.constructor({ auth: token }) : undefined; + await evaluate({ github, teamGithub, context, core, number: Number(process.env.REVIEW_POLICY_PR) }); diff --git a/.github/workflows/rust-ci.yml b/.github/workflows/rust-ci.yml index e5bc6effd..75aa02a70 100644 --- a/.github/workflows/rust-ci.yml +++ b/.github/workflows/rust-ci.yml @@ -6,26 +6,36 @@ on: paths: - "**/*.rs" - "**/Cargo.toml" - - "Cargo.lock" + - "**/Cargo.lock" - "rust-toolchain.toml" - ".cargo/**" - ".config/nextest.toml" - "clippy.toml" - "rustfmt.toml" - "Justfile" + - "justfiles/rust.just" + - "justfiles/contracts.just" + - "justfiles/proof.just" + - "pkg/contracts/src/**" + - "crates/**/res/**" - ".github/workflows/rust-ci.yml" merge_group: pull_request: paths: - "**/*.rs" - "**/Cargo.toml" - - "Cargo.lock" + - "**/Cargo.lock" - "rust-toolchain.toml" - ".cargo/**" - ".config/nextest.toml" - "clippy.toml" - "rustfmt.toml" - "Justfile" + - "justfiles/rust.just" + - "justfiles/contracts.just" + - "justfiles/proof.just" + - "pkg/contracts/src/**" + - "crates/**/res/**" - ".github/workflows/rust-ci.yml" workflow_dispatch: @@ -60,7 +70,7 @@ jobs: - name: Install Rust toolchain uses: dtolnay/rust-toolchain@2c7215f132e9ebf062739d9130488b56d53c060c # master with: - toolchain: nightly-2026-07-01 + toolchain: nightly-2026-10-10 - uses: taiki-e/install-action@18b1216eba7f8039b0f8d131d5473787f0edce68 # v2.85.3 with: tool: just @@ -90,7 +100,7 @@ jobs: with: tool: nextest - name: tests - run: mold -run just test --profile ci + run: mold -run just test --profile ci --locked cargo-clippy: runs-on: arc-public-8xlarge-amd64-runner @@ -110,7 +120,7 @@ jobs: tool: just - uses: dtolnay/rust-toolchain@2c7215f132e9ebf062739d9130488b56d53c060c # master with: - toolchain: nightly-2026-07-01 + toolchain: nightly-2026-10-10 components: rustfmt, clippy - uses: arduino/setup-protoc@c65c819552d16ad3c9b72d9dfd5ba5237b9c906b # v3 with: @@ -133,9 +143,9 @@ jobs: key: cargo-test-${{ hashFiles('**/Cargo.lock') }} restore-keys: cargo-test- - name: fmt - run: cargo +nightly-2026-07-01 fmt --all -- --check + run: cargo +nightly-2026-10-10 fmt --all -- --check - name: clippy - run: cargo +nightly-2026-07-01 clippy --workspace --all-targets --all-features -- -D warnings + run: cargo +nightly-2026-10-10 clippy --workspace --all-targets --all-features --locked -- -D warnings cargo-docs: runs-on: arc-public-8xlarge-amd64-runner @@ -153,7 +163,7 @@ jobs: - name: Install Rust toolchain uses: dtolnay/rust-toolchain@2c7215f132e9ebf062739d9130488b56d53c060c # master with: - toolchain: nightly-2026-07-01 + toolchain: nightly-2026-10-10 - uses: arduino/setup-protoc@c65c819552d16ad3c9b72d9dfd5ba5237b9c906b # v3 with: repo-token: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/supply-chain.yml b/.github/workflows/supply-chain.yml index 8d1700395..5d19b5ad7 100644 --- a/.github/workflows/supply-chain.yml +++ b/.github/workflows/supply-chain.yml @@ -31,7 +31,7 @@ jobs: - name: Install Rust toolchain uses: dtolnay/rust-toolchain@2c7215f132e9ebf062739d9130488b56d53c060c # master with: - toolchain: nightly-2026-07-01 + toolchain: nightly-2026-10-10 - uses: taiki-e/install-action@18b1216eba7f8039b0f8d131d5473787f0edce68 # v2.85.3 with: # deny/vet pinned to the versions that generated deny.toml and supply-chain/: diff --git a/.github/workflows/verify-measurements.yml b/.github/workflows/verify-measurements.yml index ee7fec9cc..5f8f10d18 100644 --- a/.github/workflows/verify-measurements.yml +++ b/.github/workflows/verify-measurements.yml @@ -17,6 +17,8 @@ on: - 'proofs/protocol/**' - 'proofs/measurements.json' - 'Cargo.lock' + - 'Cargo.toml' + - '.cargo/**' - 'Justfile' - 'justfiles/proof.just' - 'flake.nix' @@ -48,6 +50,9 @@ jobs: - 'proofs/protocol/**' - 'proofs/measurements.json' - 'Cargo.lock' + - 'Cargo.toml' + - 'rust-toolchain.toml' + - '.cargo/**' - 'Justfile' - 'justfiles/proof.just' - '.github/workflows/verify-measurements.yml' @@ -60,6 +65,8 @@ jobs: - 'flake.lock' - 'rust-toolchain.toml' - 'scripts/build-eif.sh' + - 'Justfile' + - 'justfiles/proof.just' - '.github/actions/install-nix/**' - '.github/workflows/verify-measurements.yml' @@ -76,7 +83,7 @@ jobs: # https://sp1.succinct.xyz bootstrap script, which fetches sp1up from `main` unpinned. - name: Install SP1 toolchain env: - SP1_VERSION: "v6.3.1" + SP1_VERSION: "v6.8.1" SP1UP_SHA256: 55d4f6ef8e79e04a7ccd064f75c6a6b44a1694b21cd41aa8e7d0d53eb880a71d run: | set -euo pipefail diff --git a/ACTIVATIONS.md b/ACTIVATIONS.md new file mode 100644 index 000000000..7785e97fc --- /dev/null +++ b/ACTIVATIONS.md @@ -0,0 +1,25 @@ +# Network activations + +Every hardfork the World Chain node defines, with its status on the networks StreamingFast serves +and its effect on the Firehose block. Review the new or changed entries on every upstream bump, and +again when an activation is announced between bumps. + +Sources: `crates/chainspec/src/{hardfork.rs,spec.rs}` and the superchain-registry data embedded in +`reth-optimism-chainspec` (`superchain/configs/{mainnet,sepolia}/worldchain.toml` at the +`superchain-registry` gitlink `08d6a449` of `streamingfast/optimism` `world-chain-v2.6.0-fh3.1`). + +Checked 2026-10-22 against world-chain `v2.6.0`. + +| Fork | World Chain mainnet | World Chain Sepolia | Effect on the Firehose block | +| --- | --- | --- | --- | +| Bedrock, Regolith, Canyon, Delta, Ecotone | genesis | genesis | none (covered by every earlier release) | +| Fjord | 2024-07-24 13:00 UTC | 2024-07-23 13:00 UTC | none (covered by every earlier release) | +| Granite | 2024-10-01 11:00 UTC | 2024-09-17 11:00 UTC | none (covered by every earlier release) | +| Holocene | 2025-01-30 12:00 UTC | 2025-01-23 12:00 UTC | none (covered by every earlier release) | +| Isthmus (Prague) | 2025-11-25 12:00 UTC | 2025-10-30 12:00 UTC | operator fee vault credits, emitted by `reth-optimism-firehose` `extras.rs` behind the Isthmus gate | +| Jovian | 2026-05-01 00:00 UTC | 2026-04-26 00:00 UTC | none: the op-reth `v2.6.1` bump review found op-revm `reward_beneficiary` and the fee vault formulas unchanged, so `extras.rs` still matches | +| Karst (Osaka) | 2026-09-21 12:00 UTC | 2026-09-08 12:00 UTC | none found; Battlefield `world-chain-devnet` runs with Karst at genesis since `v2.4.3-fh3.1` | +| Tropo | not scheduled | not scheduled | none: only read from a genesis `tropoTime` field, and no execution code checks it at `v2.6.0` | +| Strato | not scheduled | not scheduled | none: only read from a genesis `stratoTime` field, and no execution code checks it at `v2.6.0` | +| OP Lagoon | never | never | `WorldChainSpec::op_fork_activation` maps it to `ForkCondition::Never`. If World Chain ever maps it, Lagoon enables the PostExec transaction type `0x7D`, which `firehose-tracer` 5.5.0 `TxType` does not know: `reth_firehose::mapper` would panic on the first one (`expect("All transaction types handled for now")`) | +| Ethereum Amsterdam (EIP-7928 block access lists) | never | never | none: World Chain configures no Amsterdam timestamp, so blocks carry no access list and the traced engine path executes sequentially. World Chain's own flashblock access lists only feed flashblock validation, which is not traced | diff --git a/AGENTS.md b/AGENTS.md index 45942cb1d..4d75923ce 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,64 +1,73 @@ # AGENTS.md -This repository is the **StreamingFast fork** of `worldcoin/world-chain`, carrying -Firehose instrumentation on top of upstream World Chain. +These instructions apply across the repository. -## Git remotes +## Find the code -| Remote | Points to | Access | -| --- | --- | --- | -| `origin` | `worldcoin/world-chain` | **read-only** — upstream, we cannot push to it | -| `sf` | `streamingfast/world-chain` | read/write — our fork, this is where our work lands | +- `bin/world-chain/` and `crates/`: node, builder, validator, Flashblocks, PBH, and RPC. +- `proofs/`: proof services, workers, backends, and measured SP1/Nitro code. +- `pkg/contracts/`: Solidity contracts and Foundry tests; `opstack/` builds pinned OP Stack artifacts. +- `e2e-tests/`, `crates/test-utils/`, and `xtask/`: integration tests, shared fixtures, and development tools. +- `specs/` and `wips/`: protocol specifications; `docs/`: development and operating guides. -The remote naming is a convention, not a guarantee: on some clones the -StreamingFast fork may be named differently (`streamingfast`, `fork`, ...). Resolve -it by URL rather than by name — pick the remote whose URL points at -`streamingfast/world-chain`: +For WIP-1006 changes, read `wips/wip-1006.md` and `pkg/contracts/README.md`. Use `../world-id-protocol/` for World ID specifications when available. -```bash -git remote -v | grep streamingfast -``` +For live node debugging with temporary log filters, use `.agents/skills/debug-node-tracing/SKILL.md`. -**Never push to `origin`.** Pushing our fork's work to the upstream World Chain -repository is wrong even when permissions would allow it. +## Make focused changes -## Pull requests +- Read the relevant code and tests before editing. State assumptions that affect behavior; ask when the answer changes the implementation. +- Follow existing patterns. Fix the cause with the smallest complete change; avoid unrelated refactors, dependency upgrades, and formatting. +- Preserve existing work. Do not edit vendored contracts under `pkg/contracts/lib/` unless the task requires it. +- Propagate errors or handle them explicitly. Bound remote calls and retries. Never add `.unwrap()` to production Rust. +- Add the smallest useful regression test for changed behavior. Explain why in comments only when the code cannot; keep comments to one line by default. -Always open PRs **against the StreamingFast fork**, targeting its default branch, -which follows the `release/*` pattern (currently `release/2.x`): +## Verify changes -```bash -git push -u sf HEAD -gh pr create --repo streamingfast/world-chain --base release/2.x -``` +Use the toolchain pinned in `rust-toolchain.toml`. Start with affected tests during development. Before every commit, run Rust formatting, Clippy, and workspace tests below. Do not commit while a required check fails or remains unrun; report blockers. -Do not target `main` — on this fork `main` is a stale mirror of upstream and is -not the integration branch. Do not target a branch on `worldcoin/world-chain`. +| Check | Command from the repository root | +| --- | --- | +| Rust formatting | `cargo fmt --all` then `cargo fmt --all -- --check` | +| Rust lint | `cargo clippy --workspace --all-targets --all-features --locked -- -D warnings` | +| Affected Rust tests | `cargo nextest run --locked -p ` | +| Workspace Rust tests | `just test --profile ci --locked` | +| Solidity formatting and tests | `just contracts-fmt` then `just test-contracts -vvv` | -The default branch moves as upstream releases advance (`release/2.x` → -`release/3.x` → ...), so confirm it rather than hardcoding: +For Solidity changes, also run `forge coverage` from `pkg/contracts/`. `just test-contracts` initializes dependencies and builds the required OP Stack artifacts before testing. -```bash -gh repo view streamingfast/world-chain --json defaultBranchRef --jq .defaultBranchRef.name -``` +Check the relevant `.github/workflows/` file for additional requirements. Some tests need Docker or RPC credentials; report missing prerequisites and failed checks. Never claim unrun tests passed. -Note the local `sf/HEAD` symbolic ref is often stale (it may still point at -`sf/main`) — trust the `gh repo view` output above, not `sf/HEAD`. +## Preserve proof boundaries -Rebase onto the current default branch before pushing, so the PR is conflict-free -and the diff shows only our change. +- `proofs/measured/` is excluded from the root workspace. Run its checks with the affected manifest; root workspace checks do not cover it. +- Keep measured dependencies separate from host services. Source, dependency, and toolchain changes can rotate SP1 verification keys or Nitro PCRs. +- Follow `docs/proof/reproducible-builds.md` when measured inputs change. Regenerate affected values in `proofs/measurements.json` through the build recipes; never invent or hand-adjust hashes. +- Use `just verify-proof-vkeys` for SP1 verification. Nitro measurements require Linux x86_64 and Nix; see `.github/workflows/verify-measurements.yml`. +- Read `docs/proof/release.md` before changing proof release or activation behavior. Account for workers serving games pinned to older measurements. -## Fork-specific files +## Protect credentials and deployments -Our additions are suffixed `.sf` so upstream merges stay clean. Keep changes -confined to these files whenever possible: +- Never print or commit private keys, JWTs, authenticated RPC URLs, or secret files. Do not dump the environment. +- Check recipes before running them: proof deployment recipes broadcast by default. Use `dry_run=true` for simulation; broadcast only when authorized for the target environment. +- Keep mocks and devnet deployment scripts out of production procedures. Preserve authorization checks, contract storage compatibility, and protocol invariants. -- `Dockerfile.sf` — Firehose-enabled image -- `CHANGELOG.sf.md` — our changelog; `.github/workflows/sf-release.yml` reads its - top section for release notes -- `.github/workflows/sf-release.yml` — our build/push/release pipeline, triggered - by `v*-fh*` tags and pushes to `release/*` and `firehose/*` branches +## Hand off -Upstream-maintained files (other workflows, crates, etc.) should only be touched -when the Firehose integration genuinely requires it — every edit there is a -future merge conflict. +Keep replies short. State the result, checks run, and any blocker. Commit only when asked; use a one-line conventional commit. Keep PR descriptions within six lines: what changed, why, and how it was verified. + +## PR labels and AI disclosure + +- Apply `ai-generated` when AI generated or materially edited retained code, commits, PR descriptions, or review replies. Include drafts; discarded output and trivial spelling or formatting suggestions do not require it. +- Under `AI usage/prompt(s) (if applicable)`, name each tool and describe what it actually did. Keep this current after review changes. Do not publish requester prompts, hidden instructions, internal reasoning, or secrets. +- Follow these case-sensitive prefixes: `A-` for affected subsystems and `C-` for the change's purpose. Apply at least one of each, plus `ai-generated` when applicable. +- Check labels with `gh label list --repo worldcoin/world-chain --limit 100`. Reuse matching names; create missing required labels with clear descriptions when labeling a PR. Preserve unrelated labels and update your labels when the scope changes. +- Use `S-` status and `P-` priority labels only when supported by the PR's actual state or agreed urgency. + +| Change | Example labels | +| --- | --- | +| RPC bug fix | `A-rpc`, `C-bug`; add `C-regression` for a regression | +| Proof-system feature | `A-proofs`, `C-enhancement` | +| Block-building performance | `A-block-building`, `C-perf` | +| Contract documentation or tests | `A-contracts` with `C-docs` or `C-test` | +| Dependency or CI maintenance | `A-dependencies` or `A-ci`, usually `C-debt` | diff --git a/AGENTS.sf.md b/AGENTS.sf.md new file mode 100644 index 000000000..e303c5b1c --- /dev/null +++ b/AGENTS.sf.md @@ -0,0 +1,72 @@ +# AGENTS.sf.md + +These instructions extend upstream's `AGENTS.md`. Where they disagree, this file wins. + +This repository is the **StreamingFast fork** of `worldcoin/world-chain`, carrying +Firehose instrumentation on top of upstream World Chain. + +## Git remotes + +| Remote | Points to | Access | +| --- | --- | --- | +| `origin` | `worldcoin/world-chain` | **read-only** — upstream, we cannot push to it | +| `sf` | `streamingfast/world-chain` | read/write — our fork, this is where our work lands | + +The remote naming is a convention, not a guarantee: on some clones the +StreamingFast fork may be named differently (`streamingfast`, `fork`, ...). Resolve +it by URL rather than by name — pick the remote whose URL points at +`streamingfast/world-chain`: + +```bash +git remote -v | grep streamingfast +``` + +**Never push to `origin`.** Pushing our fork's work to the upstream World Chain +repository is wrong even when permissions would allow it. + +## Pull requests + +Always open PRs **against the StreamingFast fork**, targeting its default branch, +which follows the `release/*` pattern (currently `release/2.x`): + +```bash +git push -u sf HEAD +gh pr create --repo streamingfast/world-chain --base release/2.x +``` + +The labels and PR rules in upstream's `AGENTS.md` are for `worldcoin/world-chain`; they do not +apply to PRs on the fork. + +Do not target `main` — on this fork `main` is a stale mirror of upstream and is +not the integration branch. Do not target a branch on `worldcoin/world-chain`. + +The default branch moves as upstream releases advance (`release/2.x` → +`release/3.x` → ...), so confirm it rather than hardcoding: + +```bash +gh repo view streamingfast/world-chain --json defaultBranchRef --jq .defaultBranchRef.name +``` + +Note the local `sf/HEAD` symbolic ref is often stale (it may still point at +`sf/main`) — trust the `gh repo view` output above, not `sf/HEAD`. + +Rebase onto the current default branch before pushing, so the PR is conflict-free +and the diff shows only our change. + +## Fork-specific files + +Our additions are suffixed `.sf` so upstream merges stay clean. Keep changes +confined to these files whenever possible: + +- `AGENTS.sf.md` — this file; `CLAUDE.md` imports it after upstream's `AGENTS.md` +- `Dockerfile.sf` — Firehose-enabled image +- `ACTIVATIONS.md` — every hardfork and its effect on the Firehose block; review it on + every upstream bump +- `CHANGELOG.sf.md` — our changelog; `.github/workflows/sf-release.yml` reads its + top section for release notes +- `.github/workflows/sf-release.yml` — our build/push/release pipeline, triggered + by `v*-fh*` tags and pushes to `release/*` and `firehose/*` branches + +Upstream-maintained files (other workflows, crates, etc.) should only be touched +when the Firehose integration genuinely requires it — every edit there is a +future merge conflict. diff --git a/CHANGELOG.sf.md b/CHANGELOG.sf.md index ad2fe02a0..f075083b3 100644 --- a/CHANGELOG.sf.md +++ b/CHANGELOG.sf.md @@ -3,6 +3,34 @@ This changelog tracks changes that the StreamingFast fork applies on top of upstream `worldcoin/world-chain` to produce the Firehose-instrumented node. +## v2.6.0-fh3.1 + +### Changed + +* Merged upstream `worldcoin/world-chain` `v2.6.0` (84 commits since `v2.4.3`, through `v2.4.4` + and `v2.4.5`). Upstream moved reth from `op-rs/reth` `aef8d3ef` to `ethereum-optimism/reth` + `0fbe4285` (reth v2.5.2), the optimism monorepo from `96ffbb2a` to `op-reth/v2.6.0`, revm to 42 + and alloy-evm to 0.38. +* Both Firehose forks moved to the new revs on their `release/world-chain-2.x` branches: + `streamingfast/reth` and `streamingfast/optimism` `world-chain-v2.6.0-fh3.1`. The reth + `[patch]` is now keyed on `https://github.com/ethereum-optimism/reth`, the URL upstream pins. +* `alloy-evm` now comes from `streamingfast/evm` `v0.38.0-sf`, so block traces keep their + `systemCalls`. +* Firehose code changes report the previous code hash and code from revm 42's `CodeChange` journal + entry instead of assuming empty code. A contract creation starts from empty code, so its code + change is reported as before. +* `FIRE INIT` and the genesis block are emitted from the node builder's `on_component_initialized` + hook, before the consensus engine exists. The genesis block used to be emitted from + `on_node_started`, which can run after the engine has traced a block. No Firehose execution + extension (ExEx) is installed; the only ExEx left is upstream's `proofs-history`, when + `--proofs-history` is set. +* `firehose-tracer` stays locked at 5.5.0, the version the forks are built against. + +### Added + +* `ACTIVATIONS.md` lists every World Chain hardfork with its mainnet and Sepolia status and its + effect on the Firehose block. + ## v2.4.3-fh3.1-4 ### Changed diff --git a/CLAUDE.md b/CLAUDE.md index 43c994c2d..b798e8bc1 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1 +1,2 @@ @AGENTS.md +@AGENTS.sf.md diff --git a/CODEOWNERS b/CODEOWNERS index 9ef60255d..27ea4393d 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -1 +1 @@ -* @0xForerunner @Dzejkop @Kemperino @0xOsiris @karankurbur @murph @kilianglas @alessandromazza98 @piohei @cichaczem \ No newline at end of file +* @worldcoin/protocol diff --git a/Cargo.lock b/Cargo.lock index 9430e24f9..8a94c72b4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -117,23 +117,23 @@ checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" [[package]] name = "alloy" -version = "2.1.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9677ab3454c237abe6307805bea17a7912b3a516b606c7b4d3d948b9fede137" +checksum = "f5a08ebfa51fdc243e0c6a662f5cf3428f04d1ad858e3fe77238cc78063eb86d" dependencies = [ - "alloy-consensus 2.1.1", + "alloy-consensus 2.5.0", "alloy-contract", "alloy-core", - "alloy-eips 2.1.1", + "alloy-eips 2.5.0", "alloy-ens", "alloy-genesis", - "alloy-network 2.1.1", + "alloy-network 2.5.0", "alloy-provider", "alloy-rpc-client", "alloy-rpc-types", - "alloy-serde 2.1.1", - "alloy-signer 2.1.1", - "alloy-signer-local 2.1.1", + "alloy-serde 2.5.0", + "alloy-signer 2.5.0", + "alloy-signer-local 2.5.0", "alloy-transport", "alloy-transport-http", "alloy-trie", @@ -148,7 +148,7 @@ dependencies = [ "alloy-primitives", "alloy-rlp", "num_enum 0.7.6", - "phf 0.14.0", + "phf", "serde", ] @@ -181,16 +181,16 @@ dependencies = [ [[package]] name = "alloy-consensus" -version = "2.1.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a6ff0c4adba2abdcd9fb5829ae5f4394c06f8585ed283a9ba79aa33763c802e1" +checksum = "727016fed834c2392d014dd697ea473f3e47bcec31ba31ccffa9c1d18ed904e5" dependencies = [ - "alloy-eips 2.1.1", + "alloy-eips 2.5.0", "alloy-primitives", "alloy-rlp", - "alloy-serde 2.1.1", + "alloy-serde 2.5.0", "alloy-trie", - "alloy-tx-macros 2.3.0", + "alloy-tx-macros 2.5.0", "arbitrary", "auto_impl", "borsh", @@ -223,40 +223,42 @@ dependencies = [ [[package]] name = "alloy-consensus-any" -version = "2.1.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7cdf48932b1db3216175e19a2b476d89d53076e004850ee7983c6807ba0fde74" +checksum = "6ea5ae60bbb3ce9dc52685a70a3755ad4432045fd38079b763cfe5127c706134" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", "alloy-primitives", "alloy-rlp", - "alloy-serde 2.1.1", + "alloy-serde 2.5.0", "arbitrary", "serde", ] [[package]] name = "alloy-contract" -version = "2.1.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee5c8b5baa015ef1d07a33983794e1539cce36954846a9bc6e1050d8a1ebf9b7" +checksum = "8c807c974ae5ac07fa98431310b498d85f029da0d2f9a088b3ea673e5e33bb81" dependencies = [ - "alloy-consensus 2.1.1", + "alloy-consensus 2.5.0", "alloy-dyn-abi", "alloy-json-abi", - "alloy-network 2.1.1", - "alloy-network-primitives 2.1.1", + "alloy-network 2.5.0", + "alloy-network-primitives 2.5.0", "alloy-primitives", "alloy-provider", - "alloy-rpc-types-eth 2.1.1", + "alloy-rpc-types-eth 2.5.0", "alloy-sol-types", "alloy-transport", "futures", "futures-util", "serde_json", "thiserror 2.0.19", + "tokio", "tracing", + "wasmtimer", ] [[package]] @@ -364,6 +366,20 @@ dependencies = [ "thiserror 2.0.19", ] +[[package]] +name = "alloy-eip8141" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36422c14bd57dcd638e276c8c9d7ac09eb16598e3a9dbd34e4b55267d4565b5e" +dependencies = [ + "alloy-primitives", + "alloy-rlp", + "arbitrary", + "borsh", + "serde", + "thiserror 2.0.19", +] + [[package]] name = "alloy-eips" version = "1.8.3" @@ -389,17 +405,18 @@ dependencies = [ [[package]] name = "alloy-eips" -version = "2.1.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea4c0453065b9206acc0f869a258dc8dcbbd595e144b4446f2c493a24a814d1f" +checksum = "e01905444bd2fc330673f11d2466c0f54e8488f7ce3132b6a5e6497916fca765" dependencies = [ "alloy-eip2124", "alloy-eip2930", "alloy-eip7702", "alloy-eip7928 0.4.5", + "alloy-eip8141", "alloy-primitives", "alloy-rlp", - "alloy-serde 2.1.1", + "alloy-serde 2.5.0", "arbitrary", "auto_impl", "borsh", @@ -415,9 +432,9 @@ dependencies = [ [[package]] name = "alloy-ens" -version = "2.1.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "709ddd5c63a05ac3274143ed0589e129119206f65cf094d2e727499da23efae8" +checksum = "22fad0811d511f8bb0d64599b9ea885282f61be924e36cee3362667115482e2b" dependencies = [ "alloy-contract", "alloy-primitives", @@ -429,15 +446,15 @@ dependencies = [ [[package]] name = "alloy-evm" -version = "0.37.0" -source = "git+https://github.com/streamingfast/evm.git?tag=v0.37.0-sf#feee281e0488e5b1459adf06f2dd9035e0c13888" +version = "0.38.0" +source = "git+https://github.com/streamingfast/evm.git?tag=v0.38.0-sf#0ac393245b50497e8b98adca267d050065203fdb" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", "alloy-hardforks", "alloy-primitives", "alloy-rpc-types-engine", - "alloy-rpc-types-eth 2.1.1", + "alloy-rpc-types-eth 2.5.0", "alloy-sol-types", "auto_impl", "derive_more 2.1.1", @@ -448,13 +465,13 @@ dependencies = [ [[package]] name = "alloy-genesis" -version = "2.1.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "027ba57264c5d05e4ff52e6090b3592e7526f5d5f5a844add6bbdd17c071c911" +checksum = "53cfa407c1d874cb306187996e30eb551bd98025e60e913e69e298ed2c8ea045" dependencies = [ - "alloy-eips 2.1.1", + "alloy-eips 2.5.0", "alloy-primitives", - "alloy-serde 2.1.1", + "alloy-serde 2.5.0", "alloy-trie", "borsh", "serde", @@ -504,9 +521,9 @@ dependencies = [ [[package]] name = "alloy-json-rpc" -version = "2.1.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4691c60de5d628533752cd07e102d17c47874c06c04c91af33960fd94c484f4" +checksum = "fff9cb760601d352d1e59aab5803c3fb6dc99824b6883f5c7a781aacd4b54c66" dependencies = [ "alloy-primitives", "alloy-sol-types", @@ -545,20 +562,20 @@ dependencies = [ [[package]] name = "alloy-network" -version = "2.1.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d912bb639bf4ac31e83095afe9e907c8b9774ce0c405966228368309fcfc45f" +checksum = "e11dfba13dac9e54576bf41e1b7461491367e0bce6a2a4293b9e40ffa3ebd5e9" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-consensus-any 2.1.1", - "alloy-eips 2.1.1", - "alloy-json-rpc 2.1.1", - "alloy-network-primitives 2.1.1", + "alloy-consensus 2.5.0", + "alloy-consensus-any 2.5.0", + "alloy-eips 2.5.0", + "alloy-json-rpc 2.5.0", + "alloy-network-primitives 2.5.0", "alloy-primitives", - "alloy-rpc-types-any 2.1.1", - "alloy-rpc-types-eth 2.1.1", - "alloy-serde 2.1.1", - "alloy-signer 2.1.1", + "alloy-rpc-types-any 2.5.0", + "alloy-rpc-types-eth 2.5.0", + "alloy-serde 2.5.0", + "alloy-signer 2.5.0", "alloy-sol-types", "async-trait", "auto_impl", @@ -584,28 +601,29 @@ dependencies = [ [[package]] name = "alloy-network-primitives" -version = "2.1.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d875a11bd98595f57f73890f2e36f4a1cca0fa670623e59c9fb08b2389979c36" +checksum = "3819bf6794d25f679d42c3f2b168e12cae08c56bb41d393cb6249b55e6d5933e" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", "alloy-primitives", - "alloy-serde 2.1.1", + "alloy-serde 2.5.0", "serde", ] [[package]] name = "alloy-op-evm" version = "0.32.0" -source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.4.3-fh3.1-3#e9b250b7a953e08846b95555d54e7cc26a49991f" +source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.6.0-fh3.1#b8bbd08e362e23ddf0b3205723b9c88f5fd1a89b" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", "alloy-evm", "alloy-op-hardforks", "alloy-primitives", "auto_impl", + "metrics", "op-alloy", "op-revm", "revm", @@ -615,7 +633,7 @@ dependencies = [ [[package]] name = "alloy-op-hardforks" version = "0.5.0" -source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.4.3-fh3.1-3#e9b250b7a953e08846b95555d54e7cc26a49991f" +source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.6.0-fh3.1#b8bbd08e362e23ddf0b3205723b9c88f5fd1a89b" dependencies = [ "alloy-chains", "alloy-hardforks", @@ -658,24 +676,24 @@ dependencies = [ [[package]] name = "alloy-provider" -version = "2.1.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e7d526d184d392a8fbcf4293e457789b307bb70646e4f8b902989a246529450" +checksum = "9f8250dbbc93fab5b00fe0d3c1db3ede67d2a5fdbae8255de70b34ae39da244b" dependencies = [ "alloy-chains", - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", - "alloy-json-rpc 2.1.1", - "alloy-network 2.1.1", - "alloy-network-primitives 2.1.1", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", + "alloy-json-rpc 2.5.0", + "alloy-network 2.5.0", + "alloy-network-primitives 2.5.0", "alloy-primitives", "alloy-pubsub", "alloy-rpc-client", "alloy-rpc-types-anvil", "alloy-rpc-types-debug", - "alloy-rpc-types-eth 2.1.1", + "alloy-rpc-types-eth 2.5.0", "alloy-rpc-types-trace", - "alloy-signer 2.1.1", + "alloy-signer 2.5.0", "alloy-sol-types", "alloy-transport", "alloy-transport-http", @@ -688,7 +706,8 @@ dependencies = [ "either", "futures", "futures-utils-wasm", - "lru 0.16.4", + "http 1.5.0", + "lru 0.18.2", "parking_lot", "pin-project", "reqwest 0.13.4", @@ -703,11 +722,11 @@ dependencies = [ [[package]] name = "alloy-pubsub" -version = "2.1.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6fa5976a77e32a63152e937fa90d0dae1f8142b41a9a99a6386d6ea58934cfa6" +checksum = "fcf12a49e488baefa21619f3ec2ce39f20857153aa1e91619fb5c1ce4d69d893" dependencies = [ - "alloy-json-rpc 2.1.1", + "alloy-json-rpc 2.5.0", "alloy-primitives", "alloy-transport", "auto_impl", @@ -747,11 +766,11 @@ dependencies = [ [[package]] name = "alloy-rpc-client" -version = "2.1.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "755447dc13a04c6fa6db8dedb5d32ab5edfa4dd7aa34487ff192a3d873e0e8cf" +checksum = "1f73519dc8f4ab73dafe90ac47aec4b9055c421c762d770d911eed83fcbef28d" dependencies = [ - "alloy-json-rpc 2.1.1", + "alloy-json-rpc 2.5.0", "alloy-primitives", "alloy-pubsub", "alloy-transport", @@ -773,23 +792,23 @@ dependencies = [ [[package]] name = "alloy-rpc-types" -version = "2.1.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96deb317fe224e98a8ae17a7ed7ea63478867385bf50b7abd53642b24cfd811a" +checksum = "e30da7fc40ff208becb4ebe462a149045c8613f60ee84f65731a522c67c351fd" dependencies = [ "alloy-primitives", "alloy-rpc-types-debug", "alloy-rpc-types-engine", - "alloy-rpc-types-eth 2.1.1", - "alloy-serde 2.1.1", + "alloy-rpc-types-eth 2.5.0", + "alloy-serde 2.5.0", "serde", ] [[package]] name = "alloy-rpc-types-admin" -version = "2.1.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3279cb55f7069c2fb1dbcd9ab2c6e79a02d63c92fd0b850addea0a3715d6b05f" +checksum = "8d217ca58fed01c4c96d66767af04af39d57ee0d3af016aaf686a2d600aa66d0" dependencies = [ "alloy-genesis", "alloy-primitives", @@ -799,13 +818,13 @@ dependencies = [ [[package]] name = "alloy-rpc-types-anvil" -version = "2.1.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f89d27756bf3effdac25d07692724e840ce90ca1ff956a6b47dd2ae1612f597" +checksum = "ad4774d898cc10846f65c426a385071f3e2872876d7f0e7836f1f75ffa54d448" dependencies = [ "alloy-primitives", - "alloy-rpc-types-eth 2.1.1", - "alloy-serde 2.1.1", + "alloy-rpc-types-eth 2.5.0", + "alloy-serde 2.5.0", "serde", ] @@ -822,26 +841,26 @@ dependencies = [ [[package]] name = "alloy-rpc-types-any" -version = "2.1.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "911a513723ef0b90c3b072f65eebf54d6ebc8b651d06734e252d024bd89b88ac" +checksum = "9c5d320312e4a9481b18185429e57fa161dbf9468414ba5667aff4ebe7bd37e7" dependencies = [ - "alloy-consensus-any 2.1.1", - "alloy-network-primitives 2.1.1", + "alloy-consensus-any 2.5.0", + "alloy-network-primitives 2.5.0", "alloy-primitives", - "alloy-rpc-types-eth 2.1.1", - "alloy-serde 2.1.1", + "alloy-rpc-types-eth 2.5.0", + "alloy-serde 2.5.0", "serde", "serde_json", ] [[package]] name = "alloy-rpc-types-beacon" -version = "2.1.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "81133671b8da58169589aac996f3c4da23bbdee85b13ecee7098065f3eae718a" +checksum = "01f0837510a7e7789f99cf86bc0d0e3b54cfa663f25de803dad613364eef9fd3" dependencies = [ - "alloy-eips 2.1.1", + "alloy-eips 2.5.0", "alloy-primitives", "alloy-rpc-types-engine", "derive_more 2.1.1", @@ -857,9 +876,9 @@ dependencies = [ [[package]] name = "alloy-rpc-types-debug" -version = "2.1.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9e9c1f9ac81c56b2d96901201db7eb95c4e9fc3c21237a4690f8c652aa62089" +checksum = "ce17ebd75d90c490897ca320e34bd5c95e0d8620d35ba5842aee9e7b5a90ea21" dependencies = [ "alloy-primitives", "alloy-rlp", @@ -870,15 +889,15 @@ dependencies = [ [[package]] name = "alloy-rpc-types-engine" -version = "2.1.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b1f682c4881aa7000ac7cc86d7aeeb3b09836a77a90b329820140233651aeea" +checksum = "77b967576e97165fed3fae1cf6adad964e192293e4ee61d9187afe3ecaa12323" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", "alloy-primitives", "alloy-rlp", - "alloy-serde 2.1.1", + "alloy-serde 2.5.0", "derive_more 2.1.1", "ethereum_ssz", "ethereum_ssz_derive", @@ -911,18 +930,19 @@ dependencies = [ [[package]] name = "alloy-rpc-types-eth" -version = "2.1.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e1bd19904581ee2075b61faabab1a4cefa8b96d8f2c85343adeae8ecf615e2b" +checksum = "32c475e21fe8a8caa02166b326ed22207a1a0597fc9b0dcdfb46e2fe6f80dadf" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-consensus-any 2.1.1", - "alloy-eips 2.1.1", - "alloy-network-primitives 2.1.1", + "alloy-consensus 2.5.0", + "alloy-consensus-any 2.5.0", + "alloy-eips 2.5.0", + "alloy-network-primitives 2.5.0", "alloy-primitives", "alloy-rlp", - "alloy-serde 2.1.1", + "alloy-serde 2.5.0", "alloy-sol-types", + "alloy-trie", "arbitrary", "itertools 0.14.0", "serde", @@ -933,28 +953,28 @@ dependencies = [ [[package]] name = "alloy-rpc-types-mev" -version = "2.1.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "54c635f0c45a871b55c276653e3838d1687d86282eeaf3d83a1914e02563b3f2" +checksum = "8c230cc2e3f19a76889664522ffc10d746292f43fa1f57a3a9e20fe011346203" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", "alloy-primitives", - "alloy-rpc-types-eth 2.1.1", - "alloy-serde 2.1.1", + "alloy-rpc-types-eth 2.5.0", + "alloy-serde 2.5.0", "serde", "serde_json", ] [[package]] name = "alloy-rpc-types-trace" -version = "2.1.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "796729a4e1783904c6040f11a503c4d55ddb16f69dc199ad15e50c4ad039f371" +checksum = "e3d8edefcef7d45a3da4bb869bbee1ee4c71b7437b22b87794f0912c89b5702c" dependencies = [ "alloy-primitives", - "alloy-rpc-types-eth 2.1.1", - "alloy-serde 2.1.1", + "alloy-rpc-types-eth 2.5.0", + "alloy-serde 2.5.0", "serde", "serde_json", "thiserror 2.0.19", @@ -962,13 +982,13 @@ dependencies = [ [[package]] name = "alloy-rpc-types-txpool" -version = "2.1.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8533c450895de79eb581875bfc317d1a239ae71aba79e20ee158fa153268f163" +checksum = "2fcacd9928d9788790afcd1d3fd8d0206329d2ef2391070867bafcc20ecf278f" dependencies = [ "alloy-primitives", - "alloy-rpc-types-eth 2.1.1", - "alloy-serde 2.1.1", + "alloy-rpc-types-eth 2.5.0", + "alloy-serde 2.5.0", "serde", ] @@ -985,9 +1005,9 @@ dependencies = [ [[package]] name = "alloy-serde" -version = "2.1.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1e97b3e0b9f816b25083045dcfa69431bd059a078e828e4d82d296d1949b96c" +checksum = "4f44f297d3b9e3ca2c3039e3c0ed69acde9b35edda15381cf78f725b7263fbe2" dependencies = [ "alloy-primitives", "arbitrary", @@ -1012,9 +1032,9 @@ dependencies = [ [[package]] name = "alloy-signer" -version = "2.1.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6913d06ccc0d9c6ab67e2f82e2fbe292706da1f91442f30cded2d04b56bf0d58" +checksum = "e7de6fd34b5ba1789d482fa800dd97219b34765d6b07633a989a24d2dace770e" dependencies = [ "alloy-dyn-abi", "alloy-primitives", @@ -1048,17 +1068,18 @@ dependencies = [ [[package]] name = "alloy-signer-aws" -version = "2.1.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ddacf5492810b4bc33e341dd3213a30cf1f0cc0c526028368ce618f3f07258c" +checksum = "eb90c0ccca083cbf40570ebf2672a2f2b4476a86b03830d44a7c84762ccf4a1d" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-network 2.1.1", + "alloy-consensus 2.5.0", + "alloy-network 2.5.0", "alloy-primitives", - "alloy-signer 2.1.1", + "alloy-signer 2.5.0", "async-trait", "aws-config", "aws-sdk-kms", + "aws-smithy-types", "k256", "spki", "thiserror 2.0.19", @@ -1083,14 +1104,14 @@ dependencies = [ [[package]] name = "alloy-signer-local" -version = "2.1.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c880813cd26bd1ddf8c2236e31295896efd1fcc5cc761d8894ae894503aeea53" +checksum = "d6909c09d586c7b55eced688754d57dde8a6bcbae2b83e69a9b9250e74cfd79e" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-network 2.1.1", + "alloy-consensus 2.5.0", + "alloy-network 2.5.0", "alloy-primitives", - "alloy-signer 2.1.1", + "alloy-signer 2.5.0", "async-trait", "coins-bip32", "coins-bip39", @@ -1175,11 +1196,11 @@ dependencies = [ [[package]] name = "alloy-transport" -version = "2.1.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "999adfe5c91035c6bf4c4210e0eb8d0caed79d76fbf5e1b70d78721f6097ac04" +checksum = "e10be13ab13ddadcfaec3320cc6cee83548a1ae32ada214ff864604cbf5c6f77" dependencies = [ - "alloy-json-rpc 2.1.1", + "alloy-json-rpc 2.5.0", "auto_impl", "base64 0.22.1", "derive_more 2.1.1", @@ -1198,15 +1219,15 @@ dependencies = [ [[package]] name = "alloy-transport-http" -version = "2.1.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e79a2c1793afc61eed9ca0963da370a988b27d2bbfa67c78013e262d47424c4" +checksum = "df948f2f9530ed0325d789ad98aa08403aaeaf55ddd6eeaf0cda143e02afab39" dependencies = [ - "alloy-json-rpc 2.1.1", + "alloy-json-rpc 2.5.0", "alloy-rpc-types-engine", "alloy-transport", "http-body-util", - "hyper 1.11.0", + "hyper", "hyper-tls", "hyper-util", "itertools 0.14.0", @@ -1220,16 +1241,17 @@ dependencies = [ [[package]] name = "alloy-transport-ipc" -version = "2.1.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c24422d5159996688b0c094babf1969cb0197d453902da483711c92c1624fea2" +checksum = "a757d266eb7927d59a04878c99b450df0da49125e61d641f48fa7c6a82dd4418" dependencies = [ - "alloy-json-rpc 2.1.1", + "alloy-json-rpc 2.5.0", "alloy-pubsub", "alloy-transport", "bytes", "futures", "interprocess", + "memchr", "pin-project", "serde", "serde_json", @@ -1240,18 +1262,18 @@ dependencies = [ [[package]] name = "alloy-transport-ws" -version = "2.1.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1bea36621cd4e4f06c1243e556b32fdc9c4db7b9b09b72a95a87383c0ffcc625" +checksum = "8c799e5804cadb4a09e0ff21be230cc1025e5a21e02a41aa9c0022fdb41f830f" dependencies = [ "alloy-pubsub", "alloy-transport", "futures", "http 1.5.0", - "rustls 0.23.43", + "rustls", "serde_json", "tokio", - "tokio-tungstenite", + "tokio-tungstenite 0.29.0", "tracing", "url", "ws_stream_wasm", @@ -1259,9 +1281,9 @@ dependencies = [ [[package]] name = "alloy-trie" -version = "0.9.5" +version = "0.9.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f14b5d9b2c2173980202c6ff470d96e7c5e202c65a9f67884ad565226df7fbb" +checksum = "b94e3e0a88f8db47250ac8a95fb825d020719f833eb1dc661bd3609c3bbece7d" dependencies = [ "alloy-primitives", "alloy-rlp", @@ -1291,9 +1313,9 @@ dependencies = [ [[package]] name = "alloy-tx-macros" -version = "2.3.0" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b3e2386593cef5b12c7d439dbcf62d7d51c3a50dc943909b42ae34b48f1b69dc" +checksum = "60fa90c57738ace5b38106c9f743f3d6d47de09a82e82ecfc42702c1acf116ee" dependencies = [ "darling 0.23.0", "proc-macro2", @@ -1373,7 +1395,7 @@ version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -1384,7 +1406,7 @@ checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" dependencies = [ "anstyle", "once_cell_polyfill", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -1446,43 +1468,58 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3df4dcc01ff89867cd86b0da835f23c3f02738353aaee7dde7495af71363b8d5" dependencies = [ - "ark-ec", + "ark-ec 0.5.0", "ark-ff 0.5.0", "ark-serialize 0.5.0", "ark-std 0.5.0", ] +[[package]] +name = "ark-bls12-381" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be2ede2c0c96fa37d5d3484e8a59fec566c4a52b8c84bf993eaa6c67d7225a4c" +dependencies = [ + "ark-ec 0.6.0", + "ark-ff 0.6.0", + "ark-serialize 0.6.0", + "ark-std 0.6.0", +] + [[package]] name = "ark-bn254" -version = "0.5.0" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d69eab57e8d2663efa5c63135b2af4f396d66424f88954c21104125ab6b3e6bc" +checksum = "6bc66f96ebe2a17a499475b4f94791d379817592ef494171586967ffdc6f95db" dependencies = [ - "ark-ec", - "ark-ff 0.5.0", + "ark-ec 0.6.0", + "ark-ff 0.6.0", "ark-r1cs-std", - "ark-std 0.5.0", + "ark-std 0.6.0", ] [[package]] name = "ark-crypto-primitives" -version = "0.5.0" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e0c292754729c8a190e50414fd1a37093c786c709899f29c9f7daccecfa855e" +checksum = "31b3409b1846fe459d19c95df039481575ac6d5842ae63858ad75cc31219bfc1" dependencies = [ "ahash", "ark-crypto-primitives-macros", - "ark-ec", - "ark-ff 0.5.0", + "ark-ec 0.6.0", + "ark-ff 0.6.0", + "ark-r1cs-std", "ark-relations", - "ark-serialize 0.5.0", + "ark-serialize 0.6.0", "ark-snark", - "ark-std 0.5.0", + "ark-std 0.6.0", "blake2", + "blake3", "derivative", "digest 0.10.7", "fnv", "merlin", + "num-bigint 0.4.8", "rayon", "sha2 0.10.9", ] @@ -1506,7 +1543,7 @@ checksum = "43d68f2d516162846c1238e755a7c4d131b892b70cc70c471a8e3ca3ed818fce" dependencies = [ "ahash", "ark-ff 0.5.0", - "ark-poly", + "ark-poly 0.5.0", "ark-serialize 0.5.0", "ark-std 0.5.0", "educe", @@ -1516,6 +1553,27 @@ dependencies = [ "num-bigint 0.4.8", "num-integer", "num-traits", + "zeroize", +] + +[[package]] +name = "ark-ec" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8352a2b2aedf6ba2cc38f7520fc51191d518dde96175c729af19f2d059f191c4" +dependencies = [ + "ahash", + "ark-ff 0.6.0", + "ark-poly 0.6.0", + "ark-serialize 0.6.0", + "ark-std 0.6.0", + "educe", + "fnv", + "hashbrown 0.17.1", + "itertools 0.14.0", + "num-bigint 0.4.8", + "num-integer", + "num-traits", "rayon", "zeroize", ] @@ -1575,7 +1633,6 @@ dependencies = [ "num-bigint 0.4.8", "num-traits", "paste", - "rayon", "zeroize", ] @@ -1593,6 +1650,7 @@ dependencies = [ "educe", "num-bigint 0.4.8", "num-traits", + "rayon", "zeroize", ] @@ -1689,17 +1747,18 @@ dependencies = [ [[package]] name = "ark-groth16" -version = "0.5.0" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "88f1d0f3a534bb54188b8dcc104307db6c56cdae574ddc3212aec0625740fc7e" +checksum = "a293328aa422e65527e285614ce5d1dceb0bd7b8b18d18b1b63191ee1f74cb41" dependencies = [ "ark-crypto-primitives", - "ark-ec", - "ark-ff 0.5.0", - "ark-poly", + "ark-ec 0.6.0", + "ark-ff 0.6.0", + "ark-poly 0.6.0", "ark-relations", - "ark-serialize 0.5.0", - "ark-std 0.5.0", + "ark-serialize 0.6.0", + "ark-snark", + "ark-std 0.6.0", "rayon", ] @@ -1716,20 +1775,36 @@ dependencies = [ "educe", "fnv", "hashbrown 0.15.5", +] + +[[package]] +name = "ark-poly" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75f55af10b672002b8d953e230282c51206842e20e5791a94432219b4201de5c" +dependencies = [ + "ahash", + "ark-ff 0.6.0", + "ark-serialize 0.6.0", + "ark-std 0.6.0", + "educe", + "fnv", + "hashbrown 0.17.1", "rayon", ] [[package]] name = "ark-r1cs-std" -version = "0.5.0" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "941551ef1df4c7a401de7068758db6503598e6f01850bdb2cfdb614a1f9dbea1" +checksum = "291f1c6628bfcac79b0dc2adbe401aa9100e2e96daa971645e0b18fc94de9a98" dependencies = [ - "ark-ec", - "ark-ff 0.5.0", + "ark-ec 0.6.0", + "ark-ff 0.6.0", "ark-relations", - "ark-std 0.5.0", + "ark-std 0.6.0", "educe", + "itertools 0.14.0", "num-bigint 0.4.8", "num-integer", "num-traits", @@ -1738,14 +1813,19 @@ dependencies = [ [[package]] name = "ark-relations" -version = "0.5.1" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec46ddc93e7af44bcab5230937635b06fb5744464dd6a7e7b083e80ebd274384" +checksum = "fe4c11c797a64b8a23e22bf4e77bf582ac27bb21395e3183a9a506ba2561e9f9" dependencies = [ - "ark-ff 0.5.0", - "ark-std 0.5.0", + "ark-ff 0.6.0", + "ark-poly 0.6.0", + "ark-serialize 0.6.0", + "ark-std 0.6.0", + "foldhash 0.1.5", + "indexmap 2.14.0", + "rayon", "tracing", - "tracing-subscriber 0.2.25", + "tracing-subscriber", ] [[package]] @@ -1780,7 +1860,6 @@ dependencies = [ "arrayvec", "digest 0.10.7", "num-bigint 0.4.8", - "rayon", ] [[package]] @@ -1793,6 +1872,7 @@ dependencies = [ "ark-std 0.6.0", "digest 0.10.7", "num-bigint 0.4.8", + "rayon", "serde_with", ] @@ -1820,14 +1900,14 @@ dependencies = [ [[package]] name = "ark-snark" -version = "0.5.1" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d368e2848c2d4c129ce7679a7d0d2d612b6a274d3ea6a13bad4445d61b381b88" +checksum = "5bdb461d2be9b2bd6f303c79fffc89f5858790a7b4d33257bca3178e2c071fb9" dependencies = [ - "ark-ff 0.5.0", + "ark-ff 0.6.0", "ark-relations", - "ark-serialize 0.5.0", - "ark-std 0.5.0", + "ark-serialize 0.6.0", + "ark-std 0.6.0", ] [[package]] @@ -1858,7 +1938,6 @@ checksum = "246a225cc6131e9ee4f24619af0f19d67761fff15d7ccc22e42b80846e69449a" dependencies = [ "num-traits", "rand 0.8.7", - "rayon", ] [[package]] @@ -1869,6 +1948,7 @@ checksum = "367c9c827ed431bff6868b7aa926e05b16eb46603cc8b6e768e4a5553fa1d155" dependencies = [ "num-traits", "rand 0.8.7", + "rayon", ] [[package]] @@ -2044,15 +2124,6 @@ dependencies = [ "bytemuck", ] -[[package]] -name = "atomic-polyfill" -version = "1.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8cf2bce30dfe09ef0bfaef228b9d414faaf7e563035494d7fe092dba54b300f4" -dependencies = [ - "critical-section", -] - [[package]] name = "atomic-waker" version = "1.1.2" @@ -2131,9 +2202,9 @@ dependencies = [ [[package]] name = "aws-lc-rs" -version = "1.17.3" +version = "1.18.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00bdb5da18dac48ca2cc7cd4a98e533e8635a58e2361d13a1a4ee3888e0d72f1" +checksum = "faac5829c2b74c28f830747e7818ccfb684261b5f48a1118b1e2a13d36dfab13" dependencies = [ "aws-lc-sys", "untrusted 0.7.1", @@ -2142,9 +2213,9 @@ dependencies = [ [[package]] name = "aws-lc-sys" -version = "0.43.0" +version = "0.46.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43103168cc76fe62678a375e722fc9cb3a0146159ac5828bc4f0dfd755c2224c" +checksum = "f1622d8446a2d4b2ce0c7eefc73dd43a99779028d5ee5c2dd8073a658ba8a2bc" dependencies = [ "cc", "cmake", @@ -2176,6 +2247,7 @@ dependencies = [ "aws-credential-types", "aws-sigv4", "aws-smithy-async", + "aws-smithy-eventstream", "aws-smithy-http", "aws-smithy-runtime", "aws-smithy-runtime-api", @@ -2184,7 +2256,9 @@ dependencies = [ "bytes", "bytes-utils", "fastrand", + "http 0.2.12", "http 1.5.0", + "http-body 0.4.6", "http-body 1.1.0", "percent-encoding", "pin-project-lite", @@ -2218,6 +2292,43 @@ dependencies = [ "tracing", ] +[[package]] +name = "aws-sdk-s3" +version = "1.141.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9f9420d3a2467eed22ed3635ca653653162c386a0b0f65c78189f9bd3c1379e" +dependencies = [ + "arc-swap", + "aws-credential-types", + "aws-runtime", + "aws-sigv4", + "aws-smithy-async", + "aws-smithy-checksums", + "aws-smithy-eventstream", + "aws-smithy-http", + "aws-smithy-json", + "aws-smithy-observability", + "aws-smithy-runtime", + "aws-smithy-runtime-api", + "aws-smithy-schema", + "aws-smithy-types", + "aws-smithy-xml", + "aws-types", + "bytes", + "fastrand", + "hex", + "hmac 0.13.0", + "http 0.2.12", + "http 1.5.0", + "http-body 1.1.0", + "lru 0.16.4", + "percent-encoding", + "regex-lite", + "sha2 0.11.0", + "tracing", + "url", +] + [[package]] name = "aws-sdk-sso" version = "1.105.0" @@ -2304,6 +2415,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "723c2234ad7511ceef63eab016b7ba6ff7c55590fefb96fa8467af014a07309f" dependencies = [ "aws-credential-types", + "aws-smithy-eventstream", "aws-smithy-http", "aws-smithy-runtime-api", "aws-smithy-types", @@ -2330,12 +2442,45 @@ dependencies = [ "tokio", ] +[[package]] +name = "aws-smithy-checksums" +version = "0.65.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67ecd999972b58e67cab052f5129906c08c25883bd0788ceefc55ef97d61307" +dependencies = [ + "aws-smithy-http", + "aws-smithy-types", + "bytes", + "crc-fast", + "hex", + "http 1.5.0", + "http-body 1.1.0", + "http-body-util", + "md-5 0.11.0", + "pin-project-lite", + "sha1 0.11.0", + "sha2 0.11.0", + "tracing", +] + +[[package]] +name = "aws-smithy-eventstream" +version = "0.61.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a9381123ab62d20c13082b151f30f962a3b112b727345394536dfa39a482944" +dependencies = [ + "aws-smithy-types", + "bytes", + "crc32fast", +] + [[package]] name = "aws-smithy-http" version = "0.64.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "37843d9add67c3aff5856f409c6dc315d3cdff60f9c0cb5b670dab1e9920306d" dependencies = [ + "aws-smithy-eventstream", "aws-smithy-runtime-api", "aws-smithy-types", "bytes", @@ -2360,23 +2505,17 @@ dependencies = [ "aws-smithy-async", "aws-smithy-runtime-api", "aws-smithy-types", - "h2 0.3.27", - "h2 0.4.15", - "http 0.2.12", + "h2", "http 1.5.0", - "http-body 0.4.6", - "hyper 0.14.32", - "hyper 1.11.0", - "hyper-rustls 0.24.2", - "hyper-rustls 0.27.9", + "hyper", + "hyper-rustls", "hyper-util", "pin-project-lite", - "rustls 0.21.12", - "rustls 0.23.43", + "rustls", "rustls-native-certs", "rustls-pki-types", "tokio", - "tokio-rustls 0.26.4", + "tokio-rustls", "tower 0.5.3", "tracing", ] @@ -2546,7 +2685,7 @@ dependencies = [ "http 1.5.0", "http-body 1.1.0", "http-body-util", - "hyper 1.11.0", + "hyper", "hyper-util", "itoa", "matchit 0.7.3", @@ -2777,7 +2916,7 @@ dependencies = [ "bitflags 2.13.1", "cexpr", "clang-sys", - "itertools 0.13.0", + "itertools 0.12.1", "proc-macro2", "quote", "regex", @@ -2942,16 +3081,16 @@ dependencies = [ "home", "http 1.5.0", "http-body-util", - "hyper 1.11.0", + "hyper", "hyper-named-pipe", - "hyper-rustls 0.27.9", + "hyper-rustls", "hyper-util", "hyperlocal", "log", "num", "pin-project-lite", "rand 0.9.5", - "rustls 0.23.43", + "rustls", "rustls-native-certs", "rustls-pki-types", "serde", @@ -3311,9 +3450,9 @@ checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" [[package]] name = "chacha20" -version = "0.10.1" +version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d524456ba66e72eb8b115ff89e01e497f8e6d11d78b70b1aa13c0fbd97540a81" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" dependencies = [ "cfg-if", "cpufeatures 0.3.0", @@ -3501,7 +3640,7 @@ dependencies = [ "const-hex", "digest 0.10.7", "generic-array 0.14.7", - "ripemd", + "ripemd 0.1.3", "serde", "sha2 0.10.9", "sha3 0.10.9", @@ -3786,6 +3925,16 @@ version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "217698eaf96b4a3f0bc4f3662aaa55bdf913cd54d7204591faa790070c6d0853" +[[package]] +name = "crc-fast" +version = "1.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e75b2483e97a5a7da73ac68a05b629f9c53cff58d8ed1c77866079e18b00dba5" +dependencies = [ + "digest 0.10.7", + "spin 0.10.1", +] + [[package]] name = "crc32fast" version = "1.5.0" @@ -3987,6 +4136,8 @@ dependencies = [ "curve25519-dalek-derive", "digest 0.10.7", "fiat-crypto", + "group", + "rand_core 0.6.4", "rustc_version 0.4.1", "subtle", "zeroize", @@ -4555,6 +4706,42 @@ dependencies = [ "memmap2", ] +[[package]] +name = "e2e-withdrawal" +version = "2.6.0" +dependencies = [ + "alloy-consensus 2.5.0", + "alloy-contract", + "alloy-eips 2.5.0", + "alloy-json-rpc 2.5.0", + "alloy-network 2.5.0", + "alloy-primitives", + "alloy-provider", + "alloy-rpc-client", + "alloy-rpc-types", + "alloy-signer-aws 2.5.0", + "alloy-signer-local 2.5.0", + "alloy-sol-types", + "alloy-transport-http", + "async-trait", + "aws-config", + "aws-credential-types", + "aws-sdk-kms", + "aws-sdk-s3", + "backoff", + "clap", + "color-eyre", + "reqwest 0.13.4", + "serde", + "serde_json", + "tempfile", + "thiserror 2.0.19", + "tokio", + "tower 0.5.3", + "tracing", + "tracing-subscriber", +] + [[package]] name = "ecdsa" version = "0.16.9" @@ -4749,7 +4936,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -4893,6 +5080,17 @@ dependencies = [ "bytes", ] +[[package]] +name = "fd-lock" +version = "4.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ce92ff622d6dadf7349484f42c93271a0d49b7cc4d466a936405bacbe10aa78" +dependencies = [ + "cfg-if", + "rustix", + "windows-sys 0.59.0", +] + [[package]] name = "fdlimit" version = "0.3.0" @@ -4970,8 +5168,8 @@ version = "5.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a53eb86c6d17bd4e5517e46f56498d33d128d0641d78d15b86cf2c0605c814ee" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", "alloy-genesis", "alloy-primitives", "alloy-rlp", @@ -5416,28 +5614,9 @@ dependencies = [ [[package]] name = "h2" -version = "0.3.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0beca50380b1fc32983fc1cb4587bfa4bb9e78fc259aad4a0032d2080309222d" -dependencies = [ - "bytes", - "fnv", - "futures-core", - "futures-sink", - "futures-util", - "http 0.2.12", - "indexmap 2.14.0", - "slab", - "tokio", - "tokio-util", - "tracing", -] - -[[package]] -name = "h2" -version = "0.4.15" +version = "0.4.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6cb093c84e8bd9b188d4c4a8cb6579fc016968d14c99882163cd3ff402a4f155" +checksum = "a9f37a958b41b3b19ee2707c06439c0e9e547e847223eb791ecb0cb821c65e27" dependencies = [ "atomic-waker", "bytes", @@ -5475,15 +5654,6 @@ version = "0.15.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d23bd4e7b5eda0d0f3a307e8b381fdc8ba9000f26fbe912250c0a4cc3956364a" -[[package]] -name = "hash32" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0c35f58762feb77d74ebe43bdbc3210f09be9fe6742234d573bacc26ed92b67" -dependencies = [ - "byteorder", -] - [[package]] name = "hashbag" version = "0.1.13" @@ -5567,20 +5737,6 @@ dependencies = [ "num-traits", ] -[[package]] -name = "heapless" -version = "0.7.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cdc6457c0eb62c71aac4bc17216026d8410337c4126773b9c5daba343f17964f" -dependencies = [ - "atomic-polyfill", - "hash32", - "rustc_version 0.4.1", - "serde", - "spin 0.9.9", - "stable_deref_trait", -] - [[package]] name = "heck" version = "0.5.0" @@ -5844,30 +6000,6 @@ dependencies = [ "typenum", ] -[[package]] -name = "hyper" -version = "0.14.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41dfc780fdec9373c01bae43289ea34c972e40ee3c9f6b3c8801a35f35586ce7" -dependencies = [ - "bytes", - "futures-channel", - "futures-core", - "futures-util", - "h2 0.3.27", - "http 0.2.12", - "http-body 0.4.6", - "httparse", - "httpdate", - "itoa", - "pin-project-lite", - "socket2 0.5.10", - "tokio", - "tower-service", - "tracing", - "want", -] - [[package]] name = "hyper" version = "1.11.0" @@ -5878,7 +6010,7 @@ dependencies = [ "bytes", "futures-channel", "futures-core", - "h2 0.4.15", + "h2", "http 1.5.0", "http-body 1.1.0", "httparse", @@ -5897,28 +6029,13 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fab3637d6b04a8037af8a266fdf6cf92ea957e8c53981a2bf6136572531025bf" dependencies = [ "hex", - "hyper 1.11.0", + "hyper", "hyper-util", "pin-project-lite", "tokio", "tower-service", ] -[[package]] -name = "hyper-rustls" -version = "0.24.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec3efd23720e2049821a693cbc7e65ea87c72f1c58ff2f9522ff332b1491e590" -dependencies = [ - "futures-util", - "http 0.2.12", - "hyper 0.14.32", - "log", - "rustls 0.21.12", - "tokio", - "tokio-rustls 0.24.1", -] - [[package]] name = "hyper-rustls" version = "0.27.9" @@ -5926,15 +6043,15 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f" dependencies = [ "http 1.5.0", - "hyper 1.11.0", + "hyper", "hyper-util", "log", - "rustls 0.23.43", + "rustls", "rustls-native-certs", "tokio", - "tokio-rustls 0.26.4", + "tokio-rustls", "tower-service", - "webpki-roots 1.0.9", + "webpki-roots 1.0.10", ] [[package]] @@ -5943,7 +6060,7 @@ version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2b90d566bffbce6a75bd8b09a05aa8c2cb1fabb6cb348f8840c9e4c90a0d83b0" dependencies = [ - "hyper 1.11.0", + "hyper", "hyper-util", "pin-project-lite", "tokio", @@ -5958,7 +6075,7 @@ checksum = "70206fc6890eaca9fde8a0bf71caa2ddfc9fe045ac9e5c70df101a7dbde866e0" dependencies = [ "bytes", "http-body-util", - "hyper 1.11.0", + "hyper", "hyper-util", "native-tls", "tokio", @@ -5978,7 +6095,7 @@ dependencies = [ "futures-util", "http 1.5.0", "http-body 1.1.0", - "hyper 1.11.0", + "hyper", "ipnet", "libc", "percent-encoding", @@ -6000,7 +6117,7 @@ checksum = "986c5ce3b994526b3cd75578e62554abd09f0899d6206de48b3e96ab34ccc8c7" dependencies = [ "hex", "http-body-util", - "hyper 1.11.0", + "hyper", "hyper-util", "pin-project-lite", "tokio", @@ -6529,13 +6646,13 @@ dependencies = [ "http 1.5.0", "jsonrpsee-core", "pin-project", - "rustls 0.23.43", + "rustls", "rustls-pki-types", "rustls-platform-verifier 0.5.3", "soketto", "thiserror 2.0.19", "tokio", - "tokio-rustls 0.26.4", + "tokio-rustls", "tokio-util", "tracing", "url", @@ -6577,12 +6694,12 @@ checksum = "790bedefcec85321e007ff3af84b4e417540d5c87b3c9779b9e247d1bcc3dab8" dependencies = [ "base64 0.22.1", "http-body 1.1.0", - "hyper 1.11.0", - "hyper-rustls 0.27.9", + "hyper", + "hyper-rustls", "hyper-util", "jsonrpsee-core", "jsonrpsee-types", - "rustls 0.23.43", + "rustls", "rustls-platform-verifier 0.5.3", "serde", "serde_json", @@ -6615,7 +6732,7 @@ dependencies = [ "http 1.5.0", "http-body 1.1.0", "http-body-util", - "hyper 1.11.0", + "hyper", "hyper-util", "jsonrpsee-core", "jsonrpsee-types", @@ -6746,7 +6863,7 @@ dependencies = [ [[package]] name = "kona-cli" version = "0.3.2" -source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.4.3-fh3.1-3#e9b250b7a953e08846b95555d54e7cc26a49991f" +source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.6.0-fh3.1#b8bbd08e362e23ddf0b3205723b9c88f5fd1a89b" dependencies = [ "alloy-chains", "alloy-primitives", @@ -6760,16 +6877,16 @@ dependencies = [ "thiserror 2.0.19", "tracing", "tracing-appender", - "tracing-subscriber 0.3.23", + "tracing-subscriber", ] [[package]] name = "kona-client" version = "1.0.2" -source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.4.3-fh3.1-3#e9b250b7a953e08846b95555d54e7cc26a49991f" +source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.6.0-fh3.1#b8bbd08e362e23ddf0b3205723b9c88f5fd1a89b" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", "alloy-evm", "alloy-op-evm", "alloy-primitives", @@ -6805,10 +6922,10 @@ dependencies = [ [[package]] name = "kona-derive" version = "0.4.5" -source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.4.3-fh3.1-3#e9b250b7a953e08846b95555d54e7cc26a49991f" +source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.6.0-fh3.1#b8bbd08e362e23ddf0b3205723b9c88f5fd1a89b" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", "alloy-primitives", "alloy-rlp", "alloy-rpc-types-engine", @@ -6827,9 +6944,9 @@ dependencies = [ [[package]] name = "kona-driver" version = "0.4.0" -source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.4.3-fh3.1-3#e9b250b7a953e08846b95555d54e7cc26a49991f" +source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.6.0-fh3.1#b8bbd08e362e23ddf0b3205723b9c88f5fd1a89b" dependencies = [ - "alloy-consensus 2.1.1", + "alloy-consensus 2.5.0", "alloy-evm", "alloy-primitives", "async-trait", @@ -6847,10 +6964,10 @@ dependencies = [ [[package]] name = "kona-executor" version = "0.4.0" -source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.4.3-fh3.1-3#e9b250b7a953e08846b95555d54e7cc26a49991f" +source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.6.0-fh3.1#b8bbd08e362e23ddf0b3205723b9c88f5fd1a89b" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", "alloy-evm", "alloy-op-evm", "alloy-op-hardforks", @@ -6871,11 +6988,11 @@ dependencies = [ [[package]] name = "kona-genesis" version = "0.4.5" -source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.4.3-fh3.1-3#e9b250b7a953e08846b95555d54e7cc26a49991f" +source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.6.0-fh3.1#b8bbd08e362e23ddf0b3205723b9c88f5fd1a89b" dependencies = [ "alloy-chains", - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", "alloy-genesis", "alloy-hardforks", "alloy-op-hardforks", @@ -6890,9 +7007,9 @@ dependencies = [ [[package]] name = "kona-hardforks" version = "0.4.5" -source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.4.3-fh3.1-3#e9b250b7a953e08846b95555d54e7cc26a49991f" +source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.6.0-fh3.1#b8bbd08e362e23ddf0b3205723b9c88f5fd1a89b" dependencies = [ - "alloy-eips 2.1.1", + "alloy-eips 2.5.0", "alloy-primitives", "anyhow", "kona-genesis", @@ -6905,17 +7022,17 @@ dependencies = [ [[package]] name = "kona-host" version = "1.0.2" -source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.4.3-fh3.1-3#e9b250b7a953e08846b95555d54e7cc26a49991f" +source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.6.0-fh3.1#b8bbd08e362e23ddf0b3205723b9c88f5fd1a89b" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", "alloy-op-evm", "alloy-primitives", "alloy-provider", "alloy-rlp", "alloy-rpc-client", "alloy-rpc-types", - "alloy-serde 2.1.1", + "alloy-serde 2.5.0", "alloy-transport", "alloy-transport-http", "anyhow", @@ -6948,24 +7065,23 @@ dependencies = [ "thiserror 2.0.19", "tokio", "tracing", - "tracing-subscriber 0.3.23", + "tracing-subscriber", ] [[package]] name = "kona-interop" version = "0.4.5" -source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.4.3-fh3.1-3#e9b250b7a953e08846b95555d54e7cc26a49991f" +source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.6.0-fh3.1#b8bbd08e362e23ddf0b3205723b9c88f5fd1a89b" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", "alloy-primitives", "alloy-rlp", - "alloy-serde 2.1.1", + "alloy-serde 2.5.0", "alloy-sol-types", "async-trait", "derive_more 2.1.1", "kona-genesis", - "kona-protocol", "kona-registry", "op-alloy-consensus", "serde", @@ -6976,12 +7092,12 @@ dependencies = [ [[package]] name = "kona-macros" version = "0.1.2" -source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.4.3-fh3.1-3#e9b250b7a953e08846b95555d54e7cc26a49991f" +source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.6.0-fh3.1#b8bbd08e362e23ddf0b3205723b9c88f5fd1a89b" [[package]] name = "kona-mpt" version = "0.3.0" -source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.4.3-fh3.1-3#e9b250b7a953e08846b95555d54e7cc26a49991f" +source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.6.0-fh3.1#b8bbd08e362e23ddf0b3205723b9c88f5fd1a89b" dependencies = [ "alloy-primitives", "alloy-rlp", @@ -6993,7 +7109,7 @@ dependencies = [ [[package]] name = "kona-preimage" version = "0.3.0" -source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.4.3-fh3.1-3#e9b250b7a953e08846b95555d54e7cc26a49991f" +source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.6.0-fh3.1#b8bbd08e362e23ddf0b3205723b9c88f5fd1a89b" dependencies = [ "alloy-primitives", "async-channel", @@ -7008,16 +7124,16 @@ dependencies = [ [[package]] name = "kona-proof" version = "0.3.0" -source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.4.3-fh3.1-3#e9b250b7a953e08846b95555d54e7cc26a49991f" +source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.6.0-fh3.1#b8bbd08e362e23ddf0b3205723b9c88f5fd1a89b" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", "alloy-evm", "alloy-op-evm", "alloy-primitives", "alloy-rlp", "alloy-trie", - "ark-bls12-381", + "ark-bls12-381 0.5.0", "ark-ff 0.5.0", "async-trait", "kona-derive", @@ -7045,10 +7161,10 @@ dependencies = [ [[package]] name = "kona-proof-interop" version = "0.2.0" -source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.4.3-fh3.1-3#e9b250b7a953e08846b95555d54e7cc26a49991f" +source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.6.0-fh3.1#b8bbd08e362e23ddf0b3205723b9c88f5fd1a89b" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", "alloy-evm", "alloy-op-evm", "alloy-primitives", @@ -7077,18 +7193,18 @@ dependencies = [ [[package]] name = "kona-protocol" version = "0.4.5" -source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.4.3-fh3.1-3#e9b250b7a953e08846b95555d54e7cc26a49991f" +source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.6.0-fh3.1#b8bbd08e362e23ddf0b3205723b9c88f5fd1a89b" dependencies = [ "alloc-no-stdlib", - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", "alloy-hardforks", "alloy-op-hardforks", "alloy-primitives", "alloy-rlp", "alloy-rpc-types-engine", - "alloy-rpc-types-eth 2.1.1", - "alloy-serde 2.1.1", + "alloy-rpc-types-eth 2.5.0", + "alloy-serde 2.5.0", "ambassador", "async-trait", "brotli-decompressor", @@ -7103,22 +7219,22 @@ dependencies = [ "spin 0.10.1", "thiserror 2.0.19", "tracing", - "tracing-subscriber 0.3.23", + "tracing-subscriber", "unsigned-varint", ] [[package]] name = "kona-providers-alloy" version = "0.3.3" -source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.4.3-fh3.1-3#e9b250b7a953e08846b95555d54e7cc26a49991f" +source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.6.0-fh3.1#b8bbd08e362e23ddf0b3205723b9c88f5fd1a89b" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", "alloy-primitives", "alloy-provider", "alloy-rpc-client", "alloy-rpc-types-engine", - "alloy-serde 2.1.1", + "alloy-serde 2.5.0", "alloy-transport", "alloy-transport-http", "async-trait", @@ -7129,39 +7245,135 @@ dependencies = [ "kona-interop", "kona-macros", "kona-protocol", + "kona-providers-local", "lru 0.18.2", "op-alloy-consensus", "op-alloy-network", "reqwest 0.13.4", "serde", "thiserror 2.0.19", + "tokio-tungstenite 0.28.0", "tower 0.5.3", "tracing", ] [[package]] -name = "kona-registry" -version = "0.4.5" -source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.4.3-fh3.1-3#e9b250b7a953e08846b95555d54e7cc26a49991f" +name = "kona-providers-local" +version = "0.1.0" +source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.6.0-fh3.1#b8bbd08e362e23ddf0b3205723b9c88f5fd1a89b" +dependencies = [ + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", + "alloy-primitives", + "async-trait", + "kona-derive", + "kona-genesis", + "kona-macros", + "kona-protocol", + "lru 0.18.2", + "op-alloy-consensus", + "thiserror 2.0.19", +] + +[[package]] +name = "kona-registry" +version = "0.4.5" +source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.6.0-fh3.1#b8bbd08e362e23ddf0b3205723b9c88f5fd1a89b" +dependencies = [ + "alloy-chains", + "alloy-eips 2.5.0", + "alloy-genesis", + "alloy-hardforks", + "alloy-op-hardforks", + "alloy-primitives", + "kona-genesis", + "lazy_static", + "serde", + "serde_json", + "tabled", + "toml", +] + +[[package]] +name = "kona-sp1-client-utils" +version = "0.0.1" +source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.6.0-fh3.1#b8bbd08e362e23ddf0b3205723b9c88f5fd1a89b" +dependencies = [ + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", + "alloy-evm", + "alloy-op-evm", + "alloy-primitives", + "alloy-rlp", + "alloy-sol-types", + "anyhow", + "async-trait", + "cfg-if", + "kona-derive", + "kona-driver", + "kona-executor", + "kona-genesis", + "kona-interop", + "kona-preimage", + "kona-proof", + "kona-protocol", + "kzg-rs", + "op-alloy-consensus", + "op-revm", + "revm", + "rkyv", + "serde", + "serde_json", + "sha2 0.10.9", + "spin 0.10.1", + "tracing", +] + +[[package]] +name = "kona-sp1-host-utils" +version = "0.0.1" +source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.6.0-fh3.1#b8bbd08e362e23ddf0b3205723b9c88f5fd1a89b" dependencies = [ - "alloy-chains", - "alloy-eips 2.1.1", - "alloy-genesis", - "alloy-hardforks", - "alloy-op-hardforks", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", "alloy-primitives", - "kona-genesis", - "lazy_static", + "alloy-rpc-client", + "alloy-signer 1.8.3", + "alloy-transport-http", + "anyhow", + "async-trait", + "bytes", + "c-kzg", + "http-body-util", + "hyper", + "hyper-util", + "kona-derive", + "kona-preimage", + "kona-proof", + "kona-protocol", + "kona-sp1-client-utils", + "kzg-rs", + "metrics", + "metrics-exporter-prometheus", + "metrics-process", + "opentelemetry 0.32.0", + "opentelemetry-appender-tracing", + "opentelemetry-otlp", + "opentelemetry_sdk 0.32.1", + "rustls", + "rustls-platform-verifier 0.6.2", "serde", - "serde_json", - "tabled", - "toml", + "sp1-sdk", + "strum 0.27.2", + "tokio", + "tracing", + "tracing-subscriber", ] [[package]] name = "kona-std-fpvm" version = "0.2.0" -source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.4.3-fh3.1-3#e9b250b7a953e08846b95555d54e7cc26a49991f" +source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.6.0-fh3.1#b8bbd08e362e23ddf0b3205723b9c88f5fd1a89b" dependencies = [ "async-trait", "buddy_system_allocator", @@ -7173,7 +7385,7 @@ dependencies = [ [[package]] name = "kona-std-fpvm-proc" version = "0.2.0" -source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.4.3-fh3.1-3#e9b250b7a953e08846b95555d54e7cc26a49991f" +source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.6.0-fh3.1#b8bbd08e362e23ddf0b3205723b9c88f5fd1a89b" dependencies = [ "cfg-if", "kona-std-fpvm", @@ -7432,7 +7644,7 @@ dependencies = [ "generator", "scoped-tls", "tracing", - "tracing-subscriber 0.3.23", + "tracing-subscriber", ] [[package]] @@ -7664,15 +7876,15 @@ dependencies = [ "base64 0.22.1", "evmap", "http-body-util", - "hyper 1.11.0", - "hyper-rustls 0.27.9", + "hyper", + "hyper-rustls", "hyper-util", "indexmap 2.14.0", "ipnet", "metrics", "metrics-util", "quanta", - "rustls 0.23.43", + "rustls", "thiserror 2.0.19", "tokio", "tracing", @@ -8035,7 +8247,7 @@ version = "0.50.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -8191,7 +8403,7 @@ version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8" dependencies = [ - "proc-macro-crate 3.5.0", + "proc-macro-crate 1.3.1", "proc-macro2", "quote", "syn 2.0.119", @@ -8294,7 +8506,7 @@ checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e" [[package]] name = "op-alloy" version = "2.0.0" -source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.4.3-fh3.1-3#e9b250b7a953e08846b95555d54e7cc26a49991f" +source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.6.0-fh3.1#b8bbd08e362e23ddf0b3205723b9c88f5fd1a89b" dependencies = [ "op-alloy-consensus", "op-alloy-network", @@ -8306,15 +8518,15 @@ dependencies = [ [[package]] name = "op-alloy-consensus" version = "2.0.0" -source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.4.3-fh3.1-3#e9b250b7a953e08846b95555d54e7cc26a49991f" +source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.6.0-fh3.1#b8bbd08e362e23ddf0b3205723b9c88f5fd1a89b" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", - "alloy-network 2.1.1", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", + "alloy-network 2.5.0", "alloy-primitives", "alloy-rlp", - "alloy-rpc-types-eth 2.1.1", - "alloy-serde 2.1.1", + "alloy-rpc-types-eth 2.5.0", + "alloy-serde 2.5.0", "arbitrary", "bytes", "derive_more 2.1.1", @@ -8337,12 +8549,12 @@ checksum = "a79f352fc3893dcd670172e615afef993a41798a1d3fc0db88a3e60ef2e70ecc" [[package]] name = "op-alloy-network" version = "2.0.0" -source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.4.3-fh3.1-3#e9b250b7a953e08846b95555d54e7cc26a49991f" +source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.6.0-fh3.1#b8bbd08e362e23ddf0b3205723b9c88f5fd1a89b" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-network 2.1.1", + "alloy-consensus 2.5.0", + "alloy-network 2.5.0", "alloy-provider", - "alloy-rpc-types-eth 2.1.1", + "alloy-rpc-types-eth 2.5.0", "op-alloy-consensus", "op-alloy-rpc-types", ] @@ -8350,9 +8562,9 @@ dependencies = [ [[package]] name = "op-alloy-provider" version = "2.0.0" -source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.4.3-fh3.1-3#e9b250b7a953e08846b95555d54e7cc26a49991f" +source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.6.0-fh3.1#b8bbd08e362e23ddf0b3205723b9c88f5fd1a89b" dependencies = [ - "alloy-network 2.1.1", + "alloy-network 2.5.0", "alloy-primitives", "alloy-provider", "alloy-rpc-types-engine", @@ -8364,7 +8576,7 @@ dependencies = [ [[package]] name = "op-alloy-rpc-jsonrpsee" version = "2.0.0" -source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.4.3-fh3.1-3#e9b250b7a953e08846b95555d54e7cc26a49991f" +source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.6.0-fh3.1#b8bbd08e362e23ddf0b3205723b9c88f5fd1a89b" dependencies = [ "alloy-primitives", "jsonrpsee", @@ -8373,16 +8585,16 @@ dependencies = [ [[package]] name = "op-alloy-rpc-types" version = "2.0.0" -source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.4.3-fh3.1-3#e9b250b7a953e08846b95555d54e7cc26a49991f" +source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.6.0-fh3.1#b8bbd08e362e23ddf0b3205723b9c88f5fd1a89b" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", - "alloy-network 2.1.1", - "alloy-network-primitives 2.1.1", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", + "alloy-network 2.5.0", + "alloy-network-primitives 2.5.0", "alloy-primitives", - "alloy-rpc-types-eth 2.1.1", - "alloy-serde 2.1.1", - "alloy-signer 2.1.1", + "alloy-rpc-types-eth 2.5.0", + "alloy-serde 2.5.0", + "alloy-signer 2.5.0", "derive_more 2.1.1", "op-alloy-consensus", "reth-rpc-traits", @@ -8394,14 +8606,14 @@ dependencies = [ [[package]] name = "op-alloy-rpc-types-engine" version = "2.0.0" -source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.4.3-fh3.1-3#e9b250b7a953e08846b95555d54e7cc26a49991f" +source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.6.0-fh3.1#b8bbd08e362e23ddf0b3205723b9c88f5fd1a89b" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", "alloy-primitives", "alloy-rlp", "alloy-rpc-types-engine", - "alloy-serde 2.1.1", + "alloy-serde 2.5.0", "ethereum_ssz", "ethereum_ssz_derive", "op-alloy-consensus", @@ -8413,9 +8625,9 @@ dependencies = [ [[package]] name = "op-revm" version = "20.0.0" -source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.4.3-fh3.1-3#e9b250b7a953e08846b95555d54e7cc26a49991f" +source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.6.0-fh3.1#b8bbd08e362e23ddf0b3205723b9c88f5fd1a89b" dependencies = [ - "alloy-eips 2.1.1", + "alloy-eips 2.5.0", "auto_impl", "op-alloy-consensus", "revm", @@ -8513,6 +8725,18 @@ dependencies = [ "tracing", ] +[[package]] +name = "opentelemetry-appender-tracing" +version = "0.32.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c0080f0dc1d7c786f467cd85a4e395fcab11ee852004f39a29a18ab7c25d837" +dependencies = [ + "opentelemetry 0.32.0", + "tracing", + "tracing-core", + "tracing-subscriber", +] + [[package]] name = "opentelemetry-datadog" version = "0.19.0" @@ -8635,6 +8859,8 @@ dependencies = [ "portable-atomic", "rand 0.9.5", "thiserror 2.0.19", + "tokio", + "tokio-stream", ] [[package]] @@ -9170,58 +9396,40 @@ dependencies = [ "rustc_version 0.4.1", ] -[[package]] -name = "phf" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf" -dependencies = [ - "phf_macros", - "phf_shared 0.13.1", - "serde", -] - [[package]] name = "phf" version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "010378780309880b08997fae13be7834dba947d36393bd372f2b1556deb2a2f6" dependencies = [ - "phf_shared 0.14.0", + "phf_macros", + "phf_shared", + "serde", ] [[package]] name = "phf_generator" -version = "0.13.1" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737" +checksum = "aeb62e0959d5a1bebc965f4d15d9e2b7cea002b6b0f5ba8cde6cc26738467100" dependencies = [ "fastrand", - "phf_shared 0.13.1", + "phf_shared", ] [[package]] name = "phf_macros" -version = "0.13.1" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef" +checksum = "5fa8d0ca26d424d27630da600c6624696e7dec8bf7b3b492b383c5dc49e5e085" dependencies = [ "phf_generator", - "phf_shared 0.13.1", + "phf_shared", "proc-macro2", "quote", "syn 2.0.119", ] -[[package]] -name = "phf_shared" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266" -dependencies = [ - "siphasher", -] - [[package]] name = "phf_shared" version = "0.14.0" @@ -9343,7 +9551,6 @@ dependencies = [ "cobs", "embedded-io 0.4.0", "embedded-io 0.6.1", - "heapless", "serde", ] @@ -9596,7 +9803,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "be769465445e8c1474e9c5dac2018218498557af32d9ed057325ec9a41ae81bf" dependencies = [ "heck", - "itertools 0.14.0", + "itertools 0.12.1", "log", "multimap", "once_cell", @@ -9616,7 +9823,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8a56d757972c98b346a9b766e3f02746cde6dd1cd1d1d563472929fdd74bec4d" dependencies = [ "anyhow", - "itertools 0.14.0", + "itertools 0.12.1", "proc-macro2", "quote", "syn 2.0.119", @@ -9629,7 +9836,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b570b25f7617e43d59005d0990ccb79e950a423952cea19671b7a876da390adf" dependencies = [ "anyhow", - "itertools 0.14.0", + "itertools 0.12.1", "proc-macro2", "quote", "syn 2.0.119", @@ -9706,7 +9913,7 @@ dependencies = [ "quinn-proto", "quinn-udp", "rustc-hash", - "rustls 0.23.43", + "rustls", "socket2 0.6.5", "thiserror 2.0.19", "tokio", @@ -9728,7 +9935,7 @@ dependencies = [ "rand_pcg", "ring", "rustc-hash", - "rustls 0.23.43", + "rustls", "rustls-pki-types", "slab", "thiserror 2.0.19", @@ -9748,7 +9955,7 @@ dependencies = [ "once_cell", "socket2 0.6.5", "tracing", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -10123,22 +10330,22 @@ dependencies = [ "http 1.5.0", "http-body 1.1.0", "http-body-util", - "hyper 1.11.0", - "hyper-rustls 0.27.9", + "hyper", + "hyper-rustls", "hyper-util", "js-sys", "log", "percent-encoding", "pin-project-lite", "quinn", - "rustls 0.23.43", + "rustls", "rustls-pki-types", "serde", "serde_json", "serde_urlencoded", "sync_wrapper", "tokio", - "tokio-rustls 0.26.4", + "tokio-rustls", "tokio-util", "tower 0.5.3", "tower-http", @@ -10148,7 +10355,7 @@ dependencies = [ "wasm-bindgen-futures", "wasm-streams 0.4.2", "web-sys", - "webpki-roots 1.0.9", + "webpki-roots 1.0.10", ] [[package]] @@ -10165,15 +10372,15 @@ dependencies = [ "http 1.5.0", "http-body 1.1.0", "http-body-util", - "hyper 1.11.0", - "hyper-rustls 0.27.9", + "hyper", + "hyper-rustls", "hyper-util", "js-sys", "log", "percent-encoding", "pin-project-lite", "quinn", - "rustls 0.23.43", + "rustls", "rustls-pki-types", "rustls-platform-verifier 0.7.0", "serde", @@ -10181,7 +10388,7 @@ dependencies = [ "serde_urlencoded", "sync_wrapper", "tokio", - "tokio-rustls 0.26.4", + "tokio-rustls", "tokio-util", "tower 0.5.3", "tower-http", @@ -10216,11 +10423,11 @@ checksum = "1e061d1b48cb8d38042de4ae0a7a6401009d6143dc80d2e2d6f31f0bdd6470c7" [[package]] name = "reth-basic-payload-builder" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", "alloy-primitives", "futures-core", "futures-util", @@ -10243,20 +10450,19 @@ dependencies = [ [[package]] name = "reth-chain-state" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", "alloy-primitives", - "alloy-signer 2.1.1", - "alloy-signer-local 2.1.1", + "alloy-signer 2.5.0", + "alloy-signer-local 2.5.0", "derive_more 2.1.1", "metrics", "parking_lot", "pin-project", "rand 0.9.5", - "rayon", "reth-chainspec", "reth-errors", "reth-ethereum-primitives", @@ -10264,7 +10470,6 @@ dependencies = [ "reth-metrics", "reth-primitives-traits", "reth-storage-api", - "reth-tasks", "reth-trie", "reth-trie-sparse", "revm", @@ -10276,12 +10481,12 @@ dependencies = [ [[package]] name = "reth-chainspec" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ "alloy-chains", - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", "alloy-evm", "alloy-genesis", "alloy-primitives", @@ -10296,8 +10501,8 @@ dependencies = [ [[package]] name = "reth-cli" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ "alloy-genesis", "clap", @@ -10309,12 +10514,12 @@ dependencies = [ [[package]] name = "reth-cli-commands" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ "alloy-chains", - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", "alloy-primitives", "alloy-rlp", "backon", @@ -10393,8 +10598,8 @@ dependencies = [ [[package]] name = "reth-cli-runner" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ "reth-tasks", "tokio", @@ -10403,10 +10608,10 @@ dependencies = [ [[package]] name = "reth-cli-util" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ - "alloy-eips 2.1.1", + "alloy-eips 2.5.0", "alloy-primitives", "cfg-if", "eyre", @@ -10420,12 +10625,12 @@ dependencies = [ [[package]] name = "reth-codecs" -version = "0.5.2" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb43f4858fef4e3b42b80954d2edf1ff67c8ad7498347083cdc7d0f6eff2f081" +checksum = "1f0dd7f542fbcae0e490ebe13f3eababcc05547375246ff7f62700b533cf3f01" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", "alloy-genesis", "alloy-primitives", "alloy-trie", @@ -10441,9 +10646,9 @@ dependencies = [ [[package]] name = "reth-codecs-derive" -version = "0.5.2" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5798ae4d6b264764bc0d742468bd32c7fb515e774645d4930f95ff6311f3ae14" +checksum = "e7e508fcbb8cb775639dbbb56b81b62756d4322f28e76c60a52aa32575f993fe" dependencies = [ "proc-macro2", "quote", @@ -10452,11 +10657,12 @@ dependencies = [ [[package]] name = "reth-config" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ "eyre", "humantime-serde", + "reth-network-peers", "reth-network-types", "reth-prune-types", "reth-stages-types", @@ -10468,10 +10674,10 @@ dependencies = [ [[package]] name = "reth-consensus" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ - "alloy-consensus 2.1.1", + "alloy-consensus 2.5.0", "alloy-eip7928 0.4.5", "alloy-primitives", "auto_impl", @@ -10482,11 +10688,11 @@ dependencies = [ [[package]] name = "reth-consensus-common" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", "alloy-primitives", "reth-chainspec", "reth-consensus", @@ -10495,12 +10701,12 @@ dependencies = [ [[package]] name = "reth-consensus-debug-client" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", - "alloy-json-rpc 2.1.1", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", + "alloy-json-rpc 2.5.0", "alloy-primitives", "alloy-provider", "alloy-rpc-types-engine", @@ -10520,8 +10726,8 @@ dependencies = [ [[package]] name = "reth-db" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ "alloy-primitives", "derive_more 2.1.1", @@ -10549,10 +10755,10 @@ dependencies = [ [[package]] name = "reth-db-api" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ - "alloy-consensus 2.1.1", + "alloy-consensus 2.5.0", "alloy-primitives", "arbitrary", "arrayvec", @@ -10575,10 +10781,10 @@ dependencies = [ [[package]] name = "reth-db-common" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ - "alloy-consensus 2.1.1", + "alloy-consensus 2.5.0", "alloy-genesis", "alloy-primitives", "boyer-moore-magiclen", @@ -10605,10 +10811,10 @@ dependencies = [ [[package]] name = "reth-db-models" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ - "alloy-eips 2.1.1", + "alloy-eips 2.5.0", "alloy-primitives", "arbitrary", "bytes", @@ -10620,8 +10826,8 @@ dependencies = [ [[package]] name = "reth-discv4" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ "alloy-primitives", "alloy-rlp", @@ -10645,8 +10851,8 @@ dependencies = [ [[package]] name = "reth-discv5" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ "alloy-primitives", "alloy-rlp", @@ -10669,8 +10875,8 @@ dependencies = [ [[package]] name = "reth-dns-discovery" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ "alloy-primitives", "dashmap", @@ -10693,11 +10899,11 @@ dependencies = [ [[package]] name = "reth-downloaders" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", "alloy-primitives", "alloy-rlp", "async-compression", @@ -10728,19 +10934,19 @@ dependencies = [ [[package]] name = "reth-e2e-test-utils" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", - "alloy-network 2.1.1", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", + "alloy-network 2.5.0", "alloy-primitives", "alloy-provider", "alloy-rlp", "alloy-rpc-types-engine", - "alloy-rpc-types-eth 2.1.1", - "alloy-signer 2.1.1", - "alloy-signer-local 2.1.1", + "alloy-rpc-types-eth 2.5.0", + "alloy-signer 2.5.0", + "alloy-signer-local 2.5.0", "derive_more 2.1.1", "eyre", "futures-util", @@ -10785,8 +10991,8 @@ dependencies = [ [[package]] name = "reth-ecies" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ "aes", "alloy-primitives", @@ -10812,10 +11018,10 @@ dependencies = [ [[package]] name = "reth-engine-local" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ - "alloy-consensus 2.1.1", + "alloy-consensus 2.5.0", "alloy-primitives", "alloy-rpc-types-engine", "eyre", @@ -10835,11 +11041,11 @@ dependencies = [ [[package]] name = "reth-engine-primitives" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", "alloy-primitives", "alloy-rpc-types-engine", "auto_impl", @@ -10862,12 +11068,12 @@ dependencies = [ [[package]] name = "reth-engine-tree" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ - "alloy-consensus 2.1.1", + "alloy-consensus 2.5.0", "alloy-eip7928 0.4.5", - "alloy-eips 2.1.1", + "alloy-eips 2.5.0", "alloy-evm", "alloy-primitives", "alloy-rlp", @@ -10878,6 +11084,7 @@ dependencies = [ "indexmap 2.14.0", "metrics", "moka", + "parking_lot", "rayon", "reth-chain-state", "reth-chainspec", @@ -10902,11 +11109,11 @@ dependencies = [ "reth-stages", "reth-stages-api", "reth-static-file", + "reth-storage-overlay", "reth-tasks", "reth-tracing", "reth-trie", "reth-trie-common", - "reth-trie-db", "reth-trie-parallel", "reth-trie-sparse", "revm", @@ -10918,10 +11125,10 @@ dependencies = [ [[package]] name = "reth-engine-util" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ - "alloy-consensus 2.1.1", + "alloy-consensus 2.5.0", "alloy-primitives", "alloy-rlp", "alloy-rpc-types-engine", @@ -10948,11 +11155,11 @@ dependencies = [ [[package]] name = "reth-era" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", "alloy-primitives", "alloy-rlp", "alloy-rpc-types-beacon", @@ -10966,8 +11173,8 @@ dependencies = [ [[package]] name = "reth-era-downloader" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ "alloy-primitives", "bytes", @@ -10982,14 +11189,15 @@ dependencies = [ [[package]] name = "reth-era-utils" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ - "alloy-consensus 2.1.1", + "alloy-consensus 2.5.0", "alloy-primitives", "alloy-rlp", "eyre", "futures-util", + "reth-codecs", "reth-db-api", "reth-era", "reth-era-downloader", @@ -11005,8 +11213,8 @@ dependencies = [ [[package]] name = "reth-errors" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ "reth-consensus", "reth-execution-errors", @@ -11016,8 +11224,8 @@ dependencies = [ [[package]] name = "reth-eth-wire" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ "alloy-chains", "alloy-primitives", @@ -11044,16 +11252,17 @@ dependencies = [ [[package]] name = "reth-eth-wire-types" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ "alloy-chains", - "alloy-consensus 2.1.1", + "alloy-consensus 2.5.0", "alloy-eip7928 0.4.5", - "alloy-eips 2.1.1", + "alloy-eips 2.5.0", "alloy-hardforks", "alloy-primitives", "alloy-rlp", + "alloy-trie", "bytes", "derive_more 2.1.1", "reth-chainspec", @@ -11066,8 +11275,8 @@ dependencies = [ [[package]] name = "reth-ethereum" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ "reth-chainspec", "reth-eth-wire", @@ -11080,11 +11289,11 @@ dependencies = [ [[package]] name = "reth-ethereum-consensus" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", "alloy-primitives", "reth-chainspec", "reth-consensus", @@ -11096,10 +11305,10 @@ dependencies = [ [[package]] name = "reth-ethereum-engine-primitives" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ - "alloy-eips 2.1.1", + "alloy-eips 2.5.0", "alloy-primitives", "alloy-rpc-types-engine", "reth-engine-primitives", @@ -11112,8 +11321,8 @@ dependencies = [ [[package]] name = "reth-ethereum-forks" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ "alloy-eip2124", "alloy-hardforks", @@ -11125,11 +11334,11 @@ dependencies = [ [[package]] name = "reth-ethereum-payload-builder" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", "alloy-primitives", "alloy-rlp", "alloy-rpc-types-engine", @@ -11155,13 +11364,13 @@ dependencies = [ [[package]] name = "reth-ethereum-primitives" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", "alloy-primitives", - "alloy-rpc-types-eth 2.1.1", + "alloy-rpc-types-eth 2.5.0", "reth-codecs", "reth-primitives-traits", "serde", @@ -11169,8 +11378,8 @@ dependencies = [ [[package]] name = "reth-etl" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ "rayon", "reth-db-api", @@ -11179,16 +11388,17 @@ dependencies = [ [[package]] name = "reth-evm" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ - "alloy-consensus 2.1.1", + "alloy-consensus 2.5.0", "alloy-eip7928 0.4.5", - "alloy-eips 2.1.1", + "alloy-eips 2.5.0", "alloy-evm", "alloy-primitives", "auto_impl", "derive_more 2.1.1", + "fixed-cache", "futures-util", "metrics", "rayon", @@ -11204,11 +11414,11 @@ dependencies = [ [[package]] name = "reth-evm-ethereum" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", "alloy-evm", "alloy-primitives", "alloy-rpc-types-engine", @@ -11224,8 +11434,8 @@ dependencies = [ [[package]] name = "reth-execution-cache" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ "alloy-primitives", "fixed-cache", @@ -11242,8 +11452,8 @@ dependencies = [ [[package]] name = "reth-execution-errors" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ "alloy-evm", "alloy-primitives", @@ -11255,11 +11465,11 @@ dependencies = [ [[package]] name = "reth-execution-types" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", "alloy-evm", "alloy-primitives", "alloy-rlp", @@ -11274,11 +11484,11 @@ dependencies = [ [[package]] name = "reth-exex" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", "alloy-primitives", "eyre", "futures", @@ -11312,10 +11522,10 @@ dependencies = [ [[package]] name = "reth-exex-types" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ - "alloy-eips 2.1.1", + "alloy-eips 2.5.0", "alloy-primitives", "reth-chain-state", "reth-execution-types", @@ -11326,25 +11536,22 @@ dependencies = [ [[package]] name = "reth-firehose" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ - "alloy-consensus 2.1.1", + "alloy-consensus 2.5.0", "alloy-eip7928 0.4.5", - "alloy-eips 2.1.1", + "alloy-eips 2.5.0", "alloy-evm", "alloy-genesis", "alloy-primitives", "alloy-rlp", "eyre", "firehose-tracer", - "futures", "reth-chainspec", - "reth-ethereum-forks", "reth-ethereum-primitives", "reth-evm", "reth-execution-types", - "reth-exex", "reth-node-api", "reth-primitives-traits", "reth-provider", @@ -11354,8 +11561,8 @@ dependencies = [ [[package]] name = "reth-fs-util" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ "serde", "serde_json", @@ -11364,10 +11571,10 @@ dependencies = [ [[package]] name = "reth-invalid-block-hooks" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ - "alloy-consensus 2.1.1", + "alloy-consensus 2.5.0", "alloy-primitives", "alloy-rlp", "alloy-rpc-types-debug", @@ -11390,8 +11597,8 @@ dependencies = [ [[package]] name = "reth-ipc" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ "bytes", "futures", @@ -11410,8 +11617,8 @@ dependencies = [ [[package]] name = "reth-libmdbx" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ "bitflags 2.13.1", "byteorder", @@ -11427,8 +11634,8 @@ dependencies = [ [[package]] name = "reth-mdbx-sys" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ "bindgen", "cc", @@ -11436,10 +11643,11 @@ dependencies = [ [[package]] name = "reth-metrics" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ "futures", + "libc", "metrics", "metrics-derive", "reth-primitives-traits", @@ -11449,8 +11657,8 @@ dependencies = [ [[package]] name = "reth-net-banlist" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ "alloy-primitives", "ipnet", @@ -11458,8 +11666,8 @@ dependencies = [ [[package]] name = "reth-net-nat" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ "futures-util", "if-addrs", @@ -11472,11 +11680,11 @@ dependencies = [ [[package]] name = "reth-network" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", "alloy-primitives", "alloy-rlp", "aquamarine", @@ -11502,6 +11710,7 @@ dependencies = [ "reth-eth-wire-types", "reth-ethereum-forks", "reth-ethereum-primitives", + "reth-evm", "reth-evm-ethereum", "reth-fs-util", "reth-metrics", @@ -11530,13 +11739,13 @@ dependencies = [ [[package]] name = "reth-network-api" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ - "alloy-consensus 2.1.1", + "alloy-consensus 2.5.0", "alloy-primitives", "alloy-rpc-types-admin", - "alloy-rpc-types-eth 2.1.1", + "alloy-rpc-types-eth 2.5.0", "auto_impl", "derive_more 2.1.1", "enr", @@ -11555,12 +11764,12 @@ dependencies = [ [[package]] name = "reth-network-p2p" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ - "alloy-consensus 2.1.1", + "alloy-consensus 2.5.0", "alloy-eip7928 0.4.5", - "alloy-eips 2.1.1", + "alloy-eips 2.5.0", "alloy-primitives", "auto_impl", "derive_more 2.1.1", @@ -11579,8 +11788,8 @@ dependencies = [ [[package]] name = "reth-network-peers" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ "alloy-primitives", "alloy-rlp", @@ -11594,8 +11803,8 @@ dependencies = [ [[package]] name = "reth-network-types" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ "alloy-eip2124", "humantime-serde", @@ -11608,8 +11817,8 @@ dependencies = [ [[package]] name = "reth-nippy-jar" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ "anyhow", "bincode 1.3.3", @@ -11625,8 +11834,8 @@ dependencies = [ [[package]] name = "reth-node-api" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ "alloy-rpc-types-engine", "eyre", @@ -11649,11 +11858,11 @@ dependencies = [ [[package]] name = "reth-node-builder" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", "alloy-primitives", "alloy-provider", "alloy-rpc-types", @@ -11704,11 +11913,11 @@ dependencies = [ "reth-rpc-layer", "reth-stages", "reth-static-file", + "reth-storage-overlay", "reth-tasks", "reth-tokio-util", "reth-tracing", "reth-transaction-pool", - "reth-trie-db", "secp256k1 0.30.0", "serde_json", "tokio", @@ -11718,11 +11927,11 @@ dependencies = [ [[package]] name = "reth-node-core" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", "alloy-primitives", "alloy-rpc-types-engine", "clap", @@ -11773,15 +11982,15 @@ dependencies = [ [[package]] name = "reth-node-ethereum" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", - "alloy-network 2.1.1", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", + "alloy-network 2.5.0", "alloy-primitives", "alloy-rpc-types-engine", - "alloy-rpc-types-eth 2.1.1", + "alloy-rpc-types-eth 2.5.0", "ethereum_ssz", "ethereum_ssz_derive", "eyre", @@ -11822,10 +12031,10 @@ dependencies = [ [[package]] name = "reth-node-ethstats" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ - "alloy-consensus 2.1.1", + "alloy-consensus 2.5.0", "alloy-primitives", "chrono", "futures-util", @@ -11839,18 +12048,18 @@ dependencies = [ "thiserror 2.0.19", "tokio", "tokio-stream", - "tokio-tungstenite", + "tokio-tungstenite 0.29.0", "tracing", "url", ] [[package]] name = "reth-node-events" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", "alloy-primitives", "alloy-rpc-types-engine", "derive_more 2.1.1", @@ -11870,8 +12079,8 @@ dependencies = [ [[package]] name = "reth-node-metrics" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ "bytes", "eyre", @@ -11893,8 +12102,8 @@ dependencies = [ [[package]] name = "reth-node-types" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ "reth-chainspec", "reth-db-api", @@ -11906,11 +12115,11 @@ dependencies = [ [[package]] name = "reth-optimism-chainspec" version = "1.11.3" -source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.4.3-fh3.1-3#e9b250b7a953e08846b95555d54e7cc26a49991f" +source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.6.0-fh3.1#b8bbd08e362e23ddf0b3205723b9c88f5fd1a89b" dependencies = [ "alloy-chains", - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", "alloy-genesis", "alloy-hardforks", "alloy-primitives", @@ -11938,16 +12147,18 @@ dependencies = [ [[package]] name = "reth-optimism-consensus" version = "1.11.3" -source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.4.3-fh3.1-3#e9b250b7a953e08846b95555d54e7cc26a49991f" +source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.6.0-fh3.1#b8bbd08e362e23ddf0b3205723b9c88f5fd1a89b" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", "alloy-primitives", "alloy-trie", + "op-alloy-consensus", "reth-chainspec", "reth-consensus", "reth-consensus-common", "reth-execution-types", + "reth-metrics", "reth-optimism-chainspec", "reth-optimism-forks", "reth-optimism-primitives", @@ -11963,14 +12174,14 @@ dependencies = [ [[package]] name = "reth-optimism-evm" version = "1.11.3" -source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.4.3-fh3.1-3#e9b250b7a953e08846b95555d54e7cc26a49991f" +source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.6.0-fh3.1#b8bbd08e362e23ddf0b3205723b9c88f5fd1a89b" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", "alloy-evm", "alloy-op-evm", "alloy-primitives", - "alloy-rpc-types-eth 2.1.1", + "alloy-rpc-types-eth 2.5.0", "op-alloy-consensus", "op-alloy-rpc-types", "op-alloy-rpc-types-engine", @@ -11979,6 +12190,7 @@ dependencies = [ "reth-evm", "reth-execution-errors", "reth-execution-types", + "reth-metrics", "reth-optimism-chainspec", "reth-optimism-consensus", "reth-optimism-forks", @@ -11988,15 +12200,16 @@ dependencies = [ "reth-storage-errors", "revm", "thiserror 2.0.19", + "tracing", ] [[package]] name = "reth-optimism-exex" version = "1.11.3" -source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.4.3-fh3.1-3#e9b250b7a953e08846b95555d54e7cc26a49991f" +source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.6.0-fh3.1#b8bbd08e362e23ddf0b3205723b9c88f5fd1a89b" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", "eyre", "futures-util", "reth-execution-types", @@ -12011,10 +12224,10 @@ dependencies = [ [[package]] name = "reth-optimism-firehose" version = "2.3.0" -source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.4.3-fh3.1-3#e9b250b7a953e08846b95555d54e7cc26a49991f" +source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.6.0-fh3.1#b8bbd08e362e23ddf0b3205723b9c88f5fd1a89b" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", "alloy-evm", "alloy-op-evm", "alloy-primitives", @@ -12037,13 +12250,14 @@ dependencies = [ "reth-node-builder", "reth-optimism-evm", "reth-optimism-primitives", + "reth-payload-builder", "reth-payload-primitives", "reth-primitives-traits", "reth-provider", "reth-revm", + "reth-storage-overlay", "reth-tasks", "reth-trie", - "reth-trie-db", "tokio", "tracing", ] @@ -12051,10 +12265,10 @@ dependencies = [ [[package]] name = "reth-optimism-flashblocks" version = "1.11.3" -source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.4.3-fh3.1-3#e9b250b7a953e08846b95555d54e7cc26a49991f" +source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.6.0-fh3.1#b8bbd08e362e23ddf0b3205723b9c88f5fd1a89b" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", "alloy-primitives", "alloy-rpc-types", "alloy-rpc-types-engine", @@ -12080,10 +12294,10 @@ dependencies = [ "reth-tasks", "reth-trie-common", "ringbuffer", - "rustls 0.23.43", + "rustls", "serde_json", "tokio", - "tokio-tungstenite", + "tokio-tungstenite 0.28.0", "tracing", "url", ] @@ -12091,7 +12305,7 @@ dependencies = [ [[package]] name = "reth-optimism-forks" version = "1.11.3" -source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.4.3-fh3.1-3#e9b250b7a953e08846b95555d54e7cc26a49991f" +source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.6.0-fh3.1#b8bbd08e362e23ddf0b3205723b9c88f5fd1a89b" dependencies = [ "alloy-op-hardforks", "alloy-primitives", @@ -12102,25 +12316,28 @@ dependencies = [ [[package]] name = "reth-optimism-node" version = "1.11.3" -source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.4.3-fh3.1-3#e9b250b7a953e08846b95555d54e7cc26a49991f" +source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.6.0-fh3.1#b8bbd08e362e23ddf0b3205723b9c88f5fd1a89b" dependencies = [ - "alloy-consensus 2.1.1", + "alloy-consensus 2.5.0", "alloy-genesis", "alloy-primitives", "alloy-rpc-types-engine", - "alloy-rpc-types-eth 2.1.1", + "alloy-rpc-types-eth 2.5.0", "clap", "eyre", "futures-util", + "metrics", "op-alloy-consensus", "op-alloy-rpc-types-engine", "op-revm", + "reth-chain-state", "reth-chainspec", "reth-consensus", "reth-db", "reth-db-api", "reth-e2e-test-utils", "reth-evm", + "reth-metrics", "reth-network", "reth-node-api", "reth-node-builder", @@ -12141,6 +12358,7 @@ dependencies = [ "reth-primitives-traits", "reth-provider", "reth-rpc-api", + "reth-rpc-builder", "reth-rpc-engine-api", "reth-rpc-server-types", "reth-tasks", @@ -12158,10 +12376,10 @@ dependencies = [ [[package]] name = "reth-optimism-payload-builder" version = "1.11.3" -source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.4.3-fh3.1-3#e9b250b7a953e08846b95555d54e7cc26a49991f" +source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.6.0-fh3.1#b8bbd08e362e23ddf0b3205723b9c88f5fd1a89b" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", "alloy-evm", "alloy-primitives", "alloy-rlp", @@ -12199,10 +12417,10 @@ dependencies = [ [[package]] name = "reth-optimism-post-exec-replay" version = "1.11.3" -source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.4.3-fh3.1-3#e9b250b7a953e08846b95555d54e7cc26a49991f" +source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.6.0-fh3.1#b8bbd08e362e23ddf0b3205723b9c88f5fd1a89b" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", "alloy-primitives", "op-alloy-consensus", "reth-evm", @@ -12219,10 +12437,10 @@ dependencies = [ [[package]] name = "reth-optimism-primitives" version = "1.11.3" -source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.4.3-fh3.1-3#e9b250b7a953e08846b95555d54e7cc26a49991f" +source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.6.0-fh3.1#b8bbd08e362e23ddf0b3205723b9c88f5fd1a89b" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", "alloy-primitives", "alloy-rlp", "op-alloy-consensus", @@ -12234,20 +12452,19 @@ dependencies = [ [[package]] name = "reth-optimism-rpc" version = "1.11.3" -source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.4.3-fh3.1-3#e9b250b7a953e08846b95555d54e7cc26a49991f" +source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.6.0-fh3.1#b8bbd08e362e23ddf0b3205723b9c88f5fd1a89b" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", "alloy-hardforks", - "alloy-json-rpc 2.1.1", + "alloy-json-rpc 2.5.0", "alloy-op-evm", "alloy-primitives", - "alloy-rlp", "alloy-rpc-client", "alloy-rpc-types-debug", "alloy-rpc-types-engine", - "alloy-rpc-types-eth 2.1.1", - "alloy-serde 2.1.1", + "alloy-rpc-types-eth 2.5.0", + "alloy-serde 2.5.0", "alloy-transport", "alloy-transport-http", "async-trait", @@ -12307,9 +12524,9 @@ dependencies = [ [[package]] name = "reth-optimism-storage" version = "1.11.3" -source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.4.3-fh3.1-3#e9b250b7a953e08846b95555d54e7cc26a49991f" +source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.6.0-fh3.1#b8bbd08e362e23ddf0b3205723b9c88f5fd1a89b" dependencies = [ - "alloy-consensus 2.1.1", + "alloy-consensus 2.5.0", "reth-optimism-primitives", "reth-storage-api", ] @@ -12317,9 +12534,9 @@ dependencies = [ [[package]] name = "reth-optimism-trie" version = "1.11.3" -source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.4.3-fh3.1-3#e9b250b7a953e08846b95555d54e7cc26a49991f" +source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.6.0-fh3.1#b8bbd08e362e23ddf0b3205723b9c88f5fd1a89b" dependencies = [ - "alloy-eips 2.1.1", + "alloy-eips 2.5.0", "alloy-primitives", "auto_impl", "bincode 2.0.1", @@ -12352,15 +12569,15 @@ dependencies = [ [[package]] name = "reth-optimism-txpool" version = "1.11.3" -source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.4.3-fh3.1-3#e9b250b7a953e08846b95555d54e7cc26a49991f" +source = "git+https://github.com/streamingfast/optimism.git?tag=world-chain-v2.6.0-fh3.1#b8bbd08e362e23ddf0b3205723b9c88f5fd1a89b" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", - "alloy-json-rpc 2.1.1", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", + "alloy-json-rpc 2.5.0", "alloy-primitives", "alloy-rpc-client", - "alloy-rpc-types-eth 2.1.1", - "alloy-serde 2.1.1", + "alloy-rpc-types-eth 2.5.0", + "alloy-serde 2.5.0", "async-trait", "c-kzg", "derive_more 2.1.1", @@ -12391,10 +12608,10 @@ dependencies = [ [[package]] name = "reth-payload-builder" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ - "alloy-consensus 2.1.1", + "alloy-consensus 2.5.0", "alloy-primitives", "alloy-rpc-types", "derive_more 2.1.1", @@ -12415,8 +12632,8 @@ dependencies = [ [[package]] name = "reth-payload-builder-primitives" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ "pin-project", "reth-payload-primitives", @@ -12427,11 +12644,11 @@ dependencies = [ [[package]] name = "reth-payload-primitives" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", "alloy-primitives", "alloy-rlp", "alloy-rpc-types-engine", @@ -12450,36 +12667,36 @@ dependencies = [ [[package]] name = "reth-payload-util" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ - "alloy-consensus 2.1.1", + "alloy-consensus 2.5.0", "alloy-primitives", "reth-transaction-pool", ] [[package]] name = "reth-payload-validator" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ - "alloy-consensus 2.1.1", + "alloy-consensus 2.5.0", "alloy-rpc-types-engine", "reth-primitives-traits", ] [[package]] name = "reth-primitives-traits" -version = "0.5.2" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f59c928b2865af5bcdbce94800270b7f7798f27a22ca0aabdd2b7d3e6587c9ce" +checksum = "4666a8d5b246650b23e6767a45e46334d352557f473e91c2ea7211cc29291cca" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", "alloy-genesis", "alloy-primitives", "alloy-rlp", - "alloy-rpc-types-eth 2.1.1", + "alloy-rpc-types-eth 2.5.0", "alloy-trie", "arbitrary", "byteorder", @@ -12503,17 +12720,18 @@ dependencies = [ [[package]] name = "reth-provider" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ - "alloy-consensus 2.1.1", + "alloy-consensus 2.5.0", "alloy-eip7928 0.4.5", - "alloy-eips 2.1.1", + "alloy-eips 2.5.0", "alloy-genesis", "alloy-primitives", "alloy-rpc-types-engine", "eyre", "itertools 0.14.0", + "libc", "metrics", "notify", "parking_lot", @@ -12537,6 +12755,7 @@ dependencies = [ "reth-static-file-types", "reth-storage-api", "reth-storage-errors", + "reth-storage-overlay", "reth-tasks", "reth-tokio-util", "reth-trie", @@ -12551,10 +12770,10 @@ dependencies = [ [[package]] name = "reth-prune" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ - "alloy-consensus 2.1.1", + "alloy-consensus 2.5.0", "alloy-primitives", "itertools 0.14.0", "metrics", @@ -12578,8 +12797,8 @@ dependencies = [ [[package]] name = "reth-prune-types" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ "alloy-primitives", "arbitrary", @@ -12594,8 +12813,8 @@ dependencies = [ [[package]] name = "reth-revm" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ "alloy-primitives", "alloy-rlp", @@ -12609,16 +12828,16 @@ dependencies = [ [[package]] name = "reth-rpc" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ - "alloy-consensus 2.1.1", + "alloy-consensus 2.5.0", "alloy-dyn-abi", "alloy-eip7928 0.4.5", - "alloy-eips 2.1.1", + "alloy-eips 2.5.0", "alloy-evm", "alloy-genesis", - "alloy-network 2.1.1", + "alloy-network 2.5.0", "alloy-primitives", "alloy-rlp", "alloy-rpc-client", @@ -12627,13 +12846,13 @@ dependencies = [ "alloy-rpc-types-beacon", "alloy-rpc-types-debug", "alloy-rpc-types-engine", - "alloy-rpc-types-eth 2.1.1", + "alloy-rpc-types-eth 2.5.0", "alloy-rpc-types-mev", "alloy-rpc-types-trace", "alloy-rpc-types-txpool", - "alloy-serde 2.1.1", - "alloy-signer 2.1.1", - "alloy-signer-local 2.1.1", + "alloy-serde 2.5.0", + "alloy-signer 2.5.0", + "alloy-signer-local 2.5.0", "async-trait", "derive_more 2.1.1", "dyn-clone", @@ -12650,7 +12869,6 @@ dependencies = [ "reth-engine-primitives", "reth-errors", "reth-ethereum-engine-primitives", - "reth-ethereum-primitives", "reth-evm", "reth-evm-ethereum", "reth-execution-types", @@ -12687,12 +12905,12 @@ dependencies = [ [[package]] name = "reth-rpc-api" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ - "alloy-eips 2.1.1", + "alloy-eips 2.5.0", "alloy-genesis", - "alloy-json-rpc 2.1.1", + "alloy-json-rpc 2.5.0", "alloy-primitives", "alloy-rpc-types", "alloy-rpc-types-admin", @@ -12700,11 +12918,11 @@ dependencies = [ "alloy-rpc-types-beacon", "alloy-rpc-types-debug", "alloy-rpc-types-engine", - "alloy-rpc-types-eth 2.1.1", + "alloy-rpc-types-eth 2.5.0", "alloy-rpc-types-mev", "alloy-rpc-types-trace", "alloy-rpc-types-txpool", - "alloy-serde 2.1.1", + "alloy-serde 2.5.0", "jsonrpsee", "reth-chain-state", "reth-engine-primitives", @@ -12717,10 +12935,10 @@ dependencies = [ [[package]] name = "reth-rpc-builder" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ - "alloy-network 2.1.1", + "alloy-network 2.5.0", "alloy-provider", "dyn-clone", "http 1.5.0", @@ -12760,15 +12978,15 @@ dependencies = [ [[package]] name = "reth-rpc-convert" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ - "alloy-consensus 2.1.1", + "alloy-consensus 2.5.0", "alloy-evm", - "alloy-json-rpc 2.1.1", - "alloy-network 2.1.1", + "alloy-json-rpc 2.5.0", + "alloy-network 2.5.0", "alloy-primitives", - "alloy-rpc-types-eth 2.1.1", + "alloy-rpc-types-eth 2.5.0", "auto_impl", "dyn-clone", "jsonrpsee-types", @@ -12780,10 +12998,10 @@ dependencies = [ [[package]] name = "reth-rpc-engine-api" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ - "alloy-eips 2.1.1", + "alloy-eips 2.5.0", "alloy-primitives", "alloy-rlp", "alloy-rpc-types-engine", @@ -12811,21 +13029,21 @@ dependencies = [ [[package]] name = "reth-rpc-eth-api" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ - "alloy-consensus 2.1.1", + "alloy-consensus 2.5.0", "alloy-dyn-abi", "alloy-eip7928 0.4.5", - "alloy-eips 2.1.1", + "alloy-eips 2.5.0", "alloy-evm", - "alloy-json-rpc 2.1.1", - "alloy-network 2.1.1", + "alloy-json-rpc 2.5.0", + "alloy-network 2.5.0", "alloy-primitives", "alloy-rlp", - "alloy-rpc-types-eth 2.1.1", + "alloy-rpc-types-eth 2.5.0", "alloy-rpc-types-mev", - "alloy-serde 2.1.1", + "alloy-serde 2.5.0", "async-trait", "auto_impl", "dyn-clone", @@ -12858,19 +13076,19 @@ dependencies = [ [[package]] name = "reth-rpc-eth-types" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ "alloy-chains", - "alloy-consensus 2.1.1", + "alloy-consensus 2.5.0", "alloy-eip7928 0.4.5", - "alloy-eips 2.1.1", + "alloy-eips 2.5.0", "alloy-evm", - "alloy-network 2.1.1", + "alloy-network 2.5.0", "alloy-primitives", "alloy-rpc-client", - "alloy-rpc-types-eth 2.1.1", - "alloy-serde 2.1.1", + "alloy-rpc-types-eth 2.5.0", + "alloy-serde 2.5.0", "alloy-sol-types", "alloy-transport", "derive_more 2.1.1", @@ -12909,8 +13127,8 @@ dependencies = [ [[package]] name = "reth-rpc-layer" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ "alloy-rpc-types-engine", "http 1.5.0", @@ -12923,10 +13141,10 @@ dependencies = [ [[package]] name = "reth-rpc-server-types" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ - "alloy-eips 2.1.1", + "alloy-eips 2.5.0", "alloy-primitives", "alloy-rpc-types-engine", "jsonrpsee-core", @@ -12939,25 +13157,25 @@ dependencies = [ [[package]] name = "reth-rpc-traits" -version = "0.5.2" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ace77dbcdd59c014fda4565ebfec76cd1fe6f5d98584b4655e8d22a947b9eee3" +checksum = "b417a50d3fa9b58bb1a22e46fb47e0866006f24abffa1fbe75ae60116b5b2efa" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-network 2.1.1", + "alloy-consensus 2.5.0", + "alloy-network 2.5.0", "alloy-primitives", - "alloy-rpc-types-eth 2.1.1", - "alloy-signer 2.1.1", + "alloy-rpc-types-eth 2.5.0", + "alloy-signer 2.5.0", "reth-primitives-traits", "thiserror 2.0.19", ] [[package]] name = "reth-stages" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ - "alloy-consensus 2.1.1", + "alloy-consensus 2.5.0", "alloy-primitives", "alloy-rlp", "eyre", @@ -13005,10 +13223,10 @@ dependencies = [ [[package]] name = "reth-stages-api" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ - "alloy-eips 2.1.1", + "alloy-eips 2.5.0", "alloy-primitives", "aquamarine", "auto_impl", @@ -13033,8 +13251,8 @@ dependencies = [ [[package]] name = "reth-stages-types" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ "alloy-primitives", "arbitrary", @@ -13047,8 +13265,8 @@ dependencies = [ [[package]] name = "reth-static-file" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ "alloy-primitives", "parking_lot", @@ -13067,8 +13285,8 @@ dependencies = [ [[package]] name = "reth-static-file-types" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ "alloy-primitives", "clap", @@ -13082,12 +13300,12 @@ dependencies = [ [[package]] name = "reth-storage-api" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ - "alloy-consensus 2.1.1", + "alloy-consensus 2.5.0", "alloy-eip7928 0.4.5", - "alloy-eips 2.1.1", + "alloy-eips 2.5.0", "alloy-primitives", "alloy-rpc-types-engine", "auto_impl", @@ -13108,10 +13326,10 @@ dependencies = [ [[package]] name = "reth-storage-errors" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ - "alloy-eips 2.1.1", + "alloy-eips 2.5.0", "alloy-primitives", "alloy-rlp", "derive_more 2.1.1", @@ -13123,10 +13341,37 @@ dependencies = [ "thiserror 2.0.19", ] +[[package]] +name = "reth-storage-overlay" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" +dependencies = [ + "alloy-eips 2.5.0", + "alloy-primitives", + "metrics", + "parking_lot", + "rayon", + "reth-chain-state", + "reth-db-api", + "reth-errors", + "reth-ethereum-primitives", + "reth-metrics", + "reth-primitives-traits", + "reth-prune-types", + "reth-stages-types", + "reth-storage-api", + "reth-storage-errors", + "reth-tasks", + "reth-trie", + "reth-trie-common", + "reth-trie-db", + "tracing", +] + [[package]] name = "reth-tasks" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ "crossbeam-utils", "dashmap", @@ -13146,11 +13391,11 @@ dependencies = [ [[package]] name = "reth-testing-utils" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", "alloy-genesis", "alloy-primitives", "rand 0.8.7", @@ -13162,8 +13407,8 @@ dependencies = [ [[package]] name = "reth-tokio-util" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ "tokio", "tokio-stream", @@ -13172,8 +13417,8 @@ dependencies = [ [[package]] name = "reth-tracing" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ "clap", "eyre", @@ -13185,13 +13430,13 @@ dependencies = [ "tracing-journald", "tracing-logfmt", "tracing-samply", - "tracing-subscriber 0.3.23", + "tracing-subscriber", ] [[package]] name = "reth-tracing-otlp" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ "base64 0.22.1", "clap", @@ -13202,17 +13447,17 @@ dependencies = [ "opentelemetry_sdk 0.32.1", "tracing", "tracing-opentelemetry 0.33.0", - "tracing-subscriber 0.3.23", + "tracing-subscriber", "url", ] [[package]] name = "reth-transaction-pool" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", "alloy-primitives", "alloy-rlp", "aquamarine", @@ -13251,11 +13496,11 @@ dependencies = [ [[package]] name = "reth-trie" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", "alloy-primitives", "alloy-rlp", "alloy-trie", @@ -13270,20 +13515,21 @@ dependencies = [ "reth-storage-errors", "reth-trie-common", "reth-trie-sparse", + "revm", "tracing", "triehash", ] [[package]] name = "reth-trie-common" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ - "alloy-consensus 2.1.1", + "alloy-consensus 2.5.0", "alloy-primitives", "alloy-rlp", - "alloy-rpc-types-eth 2.1.1", - "alloy-serde 2.1.1", + "alloy-rpc-types-eth 2.5.0", + "alloy-serde 2.5.0", "alloy-trie", "arbitrary", "arrayvec", @@ -13303,15 +13549,12 @@ dependencies = [ [[package]] name = "reth-trie-db" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ "alloy-primitives", - "metrics", - "parking_lot", "reth-db-api", "reth-execution-errors", - "reth-metrics", "reth-primitives-traits", "reth-storage-api", "reth-storage-errors", @@ -13322,8 +13565,8 @@ dependencies = [ [[package]] name = "reth-trie-parallel" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ "alloy-evm", "alloy-primitives", @@ -13346,8 +13589,8 @@ dependencies = [ [[package]] name = "reth-trie-sparse" -version = "2.4.0" -source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.4.3-fh3.1-3#3dc4a4ac1efc8b41861de045888f5f148902a0f2" +version = "2.5.2" +source = "git+https://github.com/streamingfast/reth.git?tag=world-chain-v2.6.0-fh3.1#29828ae274269dd8a3ae07d56b0fb5602474177f" dependencies = [ "alloy-primitives", "alloy-trie", @@ -13368,18 +13611,18 @@ dependencies = [ [[package]] name = "reth-zstd-compressors" -version = "0.5.2" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e1bd4ae4f54a2ba813eef082910bc646bd31cab8ed134308fa71f1068331fb84" +checksum = "80addacffc5df9398c55919f8993922d2b688f2aa5753708fdd658ca3cc63e39" dependencies = [ "zstd", ] [[package]] name = "revm" -version = "41.0.0" +version = "42.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d51c254839fb36357d0b02d02e46ba57e683d7b017e2da33b47ae74685a9e59" +checksum = "b7c7fcd426beab3b91300a6d0d5eb8d583c0fad0fba451126e19fd51443eca62" dependencies = [ "revm-bytecode", "revm-context", @@ -13396,21 +13639,21 @@ dependencies = [ [[package]] name = "revm-bytecode" -version = "41.0.0" +version = "42.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e33493cf6d996e9242db4f2002caef48ec9aa8c4f3fff3b18aed10ef3942eec7" +checksum = "537356bdec80dbc04e4e6bb688b3441ff7cf18eecdcf3cac23150633c46467f1" dependencies = [ "bitvec", - "phf 0.13.1", + "phf", "revm-primitives", "serde", ] [[package]] name = "revm-context" -version = "41.0.0" +version = "42.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "86e48fc736d9542c082ea5305be44b6a14b53a615f0147ad57f62189fd813068" +checksum = "cc6512f05f83378e29b2b016fa5bd7f5a533e3625548be4113732e1a536c2564" dependencies = [ "bitvec", "cfg-if", @@ -13425,9 +13668,9 @@ dependencies = [ [[package]] name = "revm-context-interface" -version = "41.0.0" +version = "42.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac68282a454318246817486835a446519291dd0a8167d09de14c7e96f2147696" +checksum = "103fff818b10311034c0c11ff8760294ee0e3c320daab3c5717990fe8ee2617b" dependencies = [ "alloy-eip2930", "alloy-eip7702", @@ -13441,11 +13684,11 @@ dependencies = [ [[package]] name = "revm-database" -version = "41.0.0" +version = "42.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d761681a43e48408ea23f7f66ff56ff7b6128cadb8f9135d1b94787d0c0fc6b4" +checksum = "df72760eab0852100e748c7cb03ce0221626d60ac14534118c84c5cc894fb4c9" dependencies = [ - "alloy-eips 2.1.1", + "alloy-eips 2.5.0", "alloy-provider", "alloy-transport", "derive_more 2.1.1", @@ -13460,9 +13703,9 @@ dependencies = [ [[package]] name = "revm-database-interface" -version = "41.0.0" +version = "42.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b96e37d62fa60b45987b408486c84ebef4af4e7ddf1b3b96b4955a7263fd4e92" +checksum = "d9286c059a11be1dee814cafdc3a3ade57521c8caa050785a52c19a9d894f400" dependencies = [ "auto_impl", "either", @@ -13475,9 +13718,9 @@ dependencies = [ [[package]] name = "revm-handler" -version = "41.0.0" +version = "42.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f5e043ebfc0899c435e44475796285898e4f822e637bd67856da79cc170bd9df" +checksum = "09126175c3fa482e71e80cc28c6bb17e681911e472b94d4f7f73dd6780411798" dependencies = [ "auto_impl", "derive-where", @@ -13494,9 +13737,9 @@ dependencies = [ [[package]] name = "revm-inspector" -version = "41.0.0" +version = "42.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e470b2a5e177918944d8cd26174455b61b8fbfbbe7fe411d28b4097e410d11e" +checksum = "4aa55b208b52f0c083ea68147c78866eeecadd7c0071a614f477de316b60648e" dependencies = [ "auto_impl", "either", @@ -13512,12 +13755,12 @@ dependencies = [ [[package]] name = "revm-inspectors" -version = "0.41.2" +version = "0.42.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "54e22e1aa328f78e8c3dea6a3a860a3a3c3a77c4a7e775e3fdd3dcbb24a152ac" +checksum = "90c136a072540987ee442e9824631835520b13e5756f20780a637ba2e11f9c28" dependencies = [ "alloy-primitives", - "alloy-rpc-types-eth 2.1.1", + "alloy-rpc-types-eth 2.5.0", "alloy-rpc-types-trace", "alloy-sol-types", "anstyle", @@ -13530,9 +13773,9 @@ dependencies = [ [[package]] name = "revm-interpreter" -version = "41.0.0" +version = "42.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa5547f653f9e4c47b4f9a9075a0b7c0faea5fa29b7873f392733a943837825d" +checksum = "fd310927437752ce4bac6997b385772823b84843f04c82e151993bec1265a5ed" dependencies = [ "revm-bytecode", "revm-context-interface", @@ -13543,15 +13786,15 @@ dependencies = [ [[package]] name = "revm-precompile" -version = "41.0.0" +version = "42.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6d785931e4b8750cf9d79c808c22f05979c8d191baafc8badd4651db82584c1c" +checksum = "f2431091420999795df6a200b9f7933defe3d654710560a895e6bcabbd9954a5" dependencies = [ - "ark-bls12-381", - "ark-bn254", - "ark-ec", - "ark-ff 0.5.0", - "ark-serialize 0.5.0", + "ark-bls12-381 0.6.0", + "ark-bn254", + "ark-ec 0.6.0", + "ark-ff 0.6.0", + "ark-serialize 0.6.0", "arrayref", "aurora-engine-modexp", "aws-lc-rs", @@ -13562,16 +13805,16 @@ dependencies = [ "p256", "revm-context-interface", "revm-primitives", - "ripemd", + "ripemd 0.2.0", "secp256k1 0.31.1", - "sha2 0.10.9", + "sha2 0.11.0", ] [[package]] name = "revm-primitives" -version = "41.0.0" +version = "42.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "66f39151a31afe93d97f7ac894dd9dcc989368d5ccba19ce079bfc1d73b77452" +checksum = "2ef5564c1bce219fd08beca43d4f39fdcbc19193fa4f604c0c6b58950a13194a" dependencies = [ "alloy-primitives", "once_cell", @@ -13580,9 +13823,9 @@ dependencies = [ [[package]] name = "revm-state" -version = "41.0.0" +version = "42.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73ef2fffc28acc41e8ef7525f2b1d16288a10f80579a1b33e7e62abc9892314a" +checksum = "2c4ae66db3abfcb565854dbfc95513bfa440b3dc390ddf8e50b0363d12a6fa79" dependencies = [ "alloy-eip7928 0.4.5", "bitflags 2.13.1", @@ -13631,6 +13874,15 @@ dependencies = [ "digest 0.10.7", ] +[[package]] +name = "ripemd" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4dd4211456b4172d7e44261920c25acf07367c4f04bb5f5d54fc21b090d9b159" +dependencies = [ + "digest 0.11.3", +] + [[package]] name = "rkyv" version = "0.8.18" @@ -13841,19 +14093,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys 0.61.2", -] - -[[package]] -name = "rustls" -version = "0.21.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f56a14d1f48b391359b22f731fd4bd7e43c97f3c50eee276f3aa09c94784d3e" -dependencies = [ - "log", - "ring", - "rustls-webpki 0.101.7", - "sct", + "windows-sys 0.52.0", ] [[package]] @@ -13867,7 +14107,7 @@ dependencies = [ "once_cell", "ring", "rustls-pki-types", - "rustls-webpki 0.103.13", + "rustls-webpki", "subtle", "zeroize", ] @@ -13914,16 +14154,37 @@ dependencies = [ "jni 0.21.1", "log", "once_cell", - "rustls 0.23.43", + "rustls", "rustls-native-certs", "rustls-platform-verifier-android", - "rustls-webpki 0.103.13", + "rustls-webpki", "security-framework", "security-framework-sys", "webpki-root-certs 0.26.11", "windows-sys 0.59.0", ] +[[package]] +name = "rustls-platform-verifier" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d99feebc72bae7ab76ba994bb5e121b8d83d910ca40b36e0921f53becc41784" +dependencies = [ + "core-foundation 0.10.1", + "core-foundation-sys", + "jni 0.21.1", + "log", + "once_cell", + "rustls", + "rustls-native-certs", + "rustls-platform-verifier-android", + "rustls-webpki", + "security-framework", + "security-framework-sys", + "webpki-root-certs 1.0.10", + "windows-sys 0.52.0", +] + [[package]] name = "rustls-platform-verifier" version = "0.7.0" @@ -13935,14 +14196,14 @@ dependencies = [ "jni 0.22.4", "log", "once_cell", - "rustls 0.23.43", + "rustls", "rustls-native-certs", "rustls-platform-verifier-android", - "rustls-webpki 0.103.13", + "rustls-webpki", "security-framework", "security-framework-sys", - "webpki-root-certs 1.0.9", - "windows-sys 0.61.2", + "webpki-root-certs 1.0.10", + "windows-sys 0.52.0", ] [[package]] @@ -13953,19 +14214,9 @@ checksum = "f87165f0995f63a9fbeea62b64d10b4d9d8e78ec6d7d51fb2125fda7bb36788f" [[package]] name = "rustls-webpki" -version = "0.101.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b6275d1ee7a1cd780b64aca7726599a1dbc893b1e64144529e55c3c2f745765" -dependencies = [ - "ring", - "untrusted 0.9.0", -] - -[[package]] -name = "rustls-webpki" -version = "0.103.13" +version = "0.103.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" dependencies = [ "aws-lc-rs", "ring", @@ -14110,16 +14361,6 @@ version = "1.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d68f2ec51b097e4c1a75b681a8bec621909b5e91f15bb7b840c4f2f7b01148b2" -[[package]] -name = "sct" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da046153aa2352493d6cb7da4b6e5c0c057d8a1d0a9aa8560baffdd945acd414" -dependencies = [ - "ring", - "untrusted 0.9.0", -] - [[package]] name = "sec1" version = "0.7.3" @@ -14201,17 +14442,16 @@ dependencies = [ [[package]] name = "semaphore-rs" -version = "0.5.4" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0938bceb786a91913d5c0adae287d6da573f8fdcae7b05f62b59637367335fb7" +checksum = "f890beebbc8378b63bc84558afa165db97a6bd5087207e3de3d483badd13dc97" dependencies = [ "ark-bn254", - "ark-ec", - "ark-ff 0.5.0", + "ark-ec 0.6.0", + "ark-ff 0.6.0", "ark-groth16", "ark-relations", - "ark-std 0.5.0", - "bincode 1.3.3", + "ark-std 0.6.0", "bytemuck", "color-eyre", "hex", @@ -14222,7 +14462,6 @@ dependencies = [ "once_cell", "rand 0.8.7", "rayon", - "reqwest 0.12.28", "ruint", "semaphore-rs-ark-circom", "semaphore-rs-ark-zkey", @@ -14245,18 +14484,18 @@ dependencies = [ [[package]] name = "semaphore-rs-ark-circom" -version = "0.5.4" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "116b57b4e401f2aa86f045f2d42c3f82afded7d8dd1144f90dd69eb444768a77" +checksum = "68b7086229a7c6ae2ca6f43a342f98eec747c73b41258620f0a2ed1ab37cd1e1" dependencies = [ "ark-bn254", "ark-crypto-primitives", - "ark-ff 0.5.0", + "ark-ff 0.6.0", "ark-groth16", - "ark-poly", + "ark-poly 0.6.0", "ark-relations", - "ark-serialize 0.5.0", - "ark-std 0.5.0", + "ark-serialize 0.6.0", + "ark-std 0.6.0", "byteorder", "num-bigint 0.4.8", "num-traits", @@ -14267,16 +14506,16 @@ dependencies = [ [[package]] name = "semaphore-rs-ark-zkey" -version = "0.5.4" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "17ea8cab73554eee8a47eb3638fd0c381bb582bea7dfd87e41ca78b66f8895e1" +checksum = "d232b793bb44d2194c86047bac6905bc63294677bdf295b1dc415d7beb82abf7" dependencies = [ "ark-bn254", - "ark-ec", - "ark-ff 0.5.0", + "ark-ec 0.6.0", + "ark-ff 0.6.0", "ark-groth16", "ark-relations", - "ark-serialize 0.5.0", + "ark-serialize 0.6.0", "color-eyre", "memmap2", "semaphore-rs-ark-circom", @@ -14284,15 +14523,15 @@ dependencies = [ [[package]] name = "semaphore-rs-depth-config" -version = "0.5.4" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "204a0e85b7991bf85d81f72e2846182ebb2eaca266ba008f3af13b017c5beb7c" +checksum = "e1182bb2e1c3eafc62896cbb557e7e3e5701f302aca7e0a7be4d64afdadf0bac" [[package]] name = "semaphore-rs-depth-macros" -version = "0.5.4" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f1b5a4957dcd7499423bd2194fae4cf803b520f457e6995fb7e24f33de53565" +checksum = "b2f8c729ddc394204515cbfb8ad92c6f7ecae84e476bc83154dc0d29abbedc7a" dependencies = [ "itertools 0.13.0", "proc-macro2", @@ -14303,18 +14542,18 @@ dependencies = [ [[package]] name = "semaphore-rs-hasher" -version = "0.5.4" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fde97d6304ca689d3e45d822dd171ab8d47157b2328793d05c34b33a25ffc58a" +checksum = "0048be8cc87ca0176d0fb63bbe1dea1bedd585e21a06b5698b72c77991dc5965" dependencies = [ "bytemuck", ] [[package]] name = "semaphore-rs-keccak" -version = "0.5.4" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f093607abd8c9eaebb4118f1bb02ceb9da67948a800133fda659f22a60a6668" +checksum = "abbea1cf1a5c4268743222d23c09c6e9e8456d4907483302055b34b5690aedaf" dependencies = [ "semaphore-rs-hasher", "tiny-keccak", @@ -14322,12 +14561,12 @@ dependencies = [ [[package]] name = "semaphore-rs-poseidon" -version = "0.5.4" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eae3cb9405ccdedb5e79db5ce88dc2599315977ce80ad157af8d9d809ca2e9df" +checksum = "8a33bc286ea7609af279bfd0558a9f44e67ae7e12c831b75ed9713a4b40b4ba0" dependencies = [ "ark-bn254", - "ark-ff 0.5.0", + "ark-ff 0.6.0", "once_cell", "ruint", "semaphore-rs-hasher", @@ -14335,13 +14574,13 @@ dependencies = [ [[package]] name = "semaphore-rs-proof" -version = "0.5.4" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10cd9c6b4713969e402e7c458364c3c634881392193b3e168d5a24dbf43f74fe" +checksum = "6394dbd24c5a6e61c468a78340e1595f2f9814c200120f26f967cbfd493e9534" dependencies = [ "alloy-core", "ark-bn254", - "ark-ec", + "ark-ec 0.6.0", "ark-groth16", "getrandom 0.2.17", "hex", @@ -14355,9 +14594,9 @@ dependencies = [ [[package]] name = "semaphore-rs-storage" -version = "0.5.4" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4a15c8745fed3af44f790a73e488da41475ef66b39c9856a45d3822a119853c6" +checksum = "c58c20585a4f3a0a112a539b8d10df3da4adb181185ce5a4ad9fbd4891c110c0" dependencies = [ "bytemuck", "color-eyre", @@ -14367,16 +14606,16 @@ dependencies = [ [[package]] name = "semaphore-rs-trees" -version = "0.5.4" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3000eb83f0a055ee94adfa9d06d6cc237602867260c9821d116426c71906301" +checksum = "42ca17f302fb03333d0e47ff8556e26ed2ab45ebc3ddf75525f7c5a3e2836e40" dependencies = [ "ark-bn254", - "ark-ec", - "ark-ff 0.5.0", + "ark-ec 0.6.0", + "ark-ff 0.6.0", "ark-groth16", "ark-relations", - "ark-std 0.5.0", + "ark-std 0.6.0", "bytemuck", "color-eyre", "derive-where", @@ -14398,9 +14637,9 @@ dependencies = [ [[package]] name = "semaphore-rs-utils" -version = "0.5.4" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70ec593b345141d07b4f2bd2bddb6f25ca6763e9493db929f176b37255bd294b" +checksum = "04ce32cd02f3217ea3096e2d07d7ac99317e6a1d5388c838eeddacdbc01bbbfe" dependencies = [ "hex", "serde", @@ -14409,13 +14648,13 @@ dependencies = [ [[package]] name = "semaphore-rs-witness" -version = "0.5.4" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d718b42a3dab78df3de1478d2c2e1a59cdc2bc6d1724e578ab2e690ba9dd369" +checksum = "1abbd35e58c2f6fee33fa6c961e59e99849e25cca44c4599daf4556cb8b09c25" dependencies = [ "ark-bn254", - "ark-ff 0.5.0", - "ark-serialize 0.5.0", + "ark-ff 0.6.0", + "ark-serialize 0.6.0", "byteorder", "color-eyre", "cxx-build", @@ -14840,18 +15079,18 @@ checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" [[package]] name = "slop-air" -version = "6.3.1" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "447a04cb85d3dabad2bb07034e9393419566a5f0bf9c34f746a04469782be963" +checksum = "c6593a86d09bddebc8a9b894b528a5762fc775d2b83034a207c97630a7306e7f" dependencies = [ "p3-air", ] [[package]] name = "slop-algebra" -version = "6.3.1" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8c112cafd4c5c374d267a48c8976d12fca3b0f2cc2e44e6fb1343808310b4fc6" +checksum = "733d477823f02646fa8025c5e2d4227ed806ca33a469def68994f63122f9f106" dependencies = [ "itertools 0.14.0", "p3-field", @@ -14860,9 +15099,9 @@ dependencies = [ [[package]] name = "slop-alloc" -version = "6.3.1" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1eaa537343a6b95b7c0d4e1f5355a4da7428ae5e2f65b62167295226a9a6f7a5" +checksum = "140e458c2ee44d8d061f417e19715af7ba7a1e0432b09566a9ad61b57419a425" dependencies = [ "serde", "slop-algebra", @@ -14871,9 +15110,9 @@ dependencies = [ [[package]] name = "slop-baby-bear" -version = "6.3.1" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "129dff87e6accaf7238f605c536d76049c2bff1f6fa6d032ac56985c27c646be" +checksum = "b4ee5356138711b134dee8a730a7fd7514d55db4311f24c76113fd52eafb962d" dependencies = [ "lazy_static", "p3-baby-bear", @@ -14886,9 +15125,9 @@ dependencies = [ [[package]] name = "slop-basefold" -version = "6.3.1" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee7b22007e82917494db0e87fbb277d6c1796106572333ed53019be629ad5cd3" +checksum = "c4da5c8d86bf73032dec5e9725c1e51ad03bdfa1cd3b4c5b5a66f940fe840d12" dependencies = [ "derive-where", "itertools 0.14.0", @@ -14909,9 +15148,9 @@ dependencies = [ [[package]] name = "slop-basefold-prover" -version = "6.3.1" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e5bb7b2f76cd38f1ecc42caeaee66841a9cb7cf802df1b5257874b5e773a3ec" +checksum = "d4228cc21ec3ccb015bcd3d8627455a09ebecda7d934e927496ff3f239113af7" dependencies = [ "derive-where", "itertools 0.14.0", @@ -14921,7 +15160,6 @@ dependencies = [ "slop-alloc", "slop-baby-bear", "slop-basefold", - "slop-bn254", "slop-challenger", "slop-commit", "slop-dft", @@ -14936,9 +15174,9 @@ dependencies = [ [[package]] name = "slop-bn254" -version = "6.3.1" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea991a652ea2e55f0523649f5c9efbfb32cf9fdcc2bf3b3580b4343a94379503" +checksum = "0207095beb89a56e3875a0ca43e5782a2efc8637124b43ce453df42410e12a4c" dependencies = [ "ff", "p3-bn254-fr", @@ -14951,11 +15189,10 @@ dependencies = [ [[package]] name = "slop-challenger" -version = "6.3.1" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33b33f1eaadcd4159157758b0edcf1c14f470915f85c648e660e4740ff83e921" +checksum = "cfc4121b9b84df835c8a6677a90dc9935562172a4a370758987407c793633334" dependencies = [ - "futures", "p3-challenger", "serde", "slop-algebra", @@ -14964,9 +15201,9 @@ dependencies = [ [[package]] name = "slop-commit" -version = "6.3.1" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "076e7f6d03a74a62024342eb5ef13719eae1adcfebb5232cfe8858ebc67f4d33" +checksum = "ebb108e80118a5df3aa7fe8185d32f83bf01f9fa6493f847180b6821c84044cc" dependencies = [ "p3-commit", "serde", @@ -14975,9 +15212,9 @@ dependencies = [ [[package]] name = "slop-dft" -version = "6.3.1" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2c742ca70828453dd3c154ad63816a987d27a7c454c19e9428b03fbdf4f118c" +checksum = "967949400f2bc80c6d5cafe93601b4fcc018724af345a6926305172c563f5c72" dependencies = [ "p3-dft", "serde", @@ -14989,18 +15226,18 @@ dependencies = [ [[package]] name = "slop-fri" -version = "6.3.1" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "274f15a2a2508af5e1071ac890b672ad5b7727efba4bc1b33b33efd06045c02c" +checksum = "068417681d6f0a727248a6a4e433caa4ab37e37e7a5c8b9e492676aca7b7f514" dependencies = [ "p3-fri", ] [[package]] name = "slop-futures" -version = "6.3.1" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04717ab01c1202613436caf70948f3e7157bb4c35084817879787c98d62c87e9" +checksum = "121bb5d17da3e897dc1566e53da1f7cdbb06edda23ed70cb8a6d75ecb8e24f4a" dependencies = [ "crossbeam", "futures", @@ -15013,12 +15250,10 @@ dependencies = [ [[package]] name = "slop-jagged" -version = "6.3.1" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5aaf578d92dc05de1cd4fa7dc9ffeca918df20cda868326528ec0e81d9c153b1" +checksum = "c61650d72b5489fd7f8d2a85f992e640d42be93738a1297dd395eaa1943434d4" dependencies = [ - "derive-where", - "futures", "itertools 0.14.0", "num_cpus", "rand 0.8.7", @@ -15032,7 +15267,6 @@ dependencies = [ "slop-bn254", "slop-challenger", "slop-commit", - "slop-futures", "slop-koala-bear", "slop-merkle-tree", "slop-multilinear", @@ -15047,18 +15281,18 @@ dependencies = [ [[package]] name = "slop-keccak-air" -version = "6.3.1" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9d2c1565483d5363ffa431b510778c5bef7c423ed21cee95440721de0372213" +checksum = "65f349d2b3ef84b275abc8b2729a4418a61b376deef4e7f23ec5ef5a55e0bd8f" dependencies = [ "p3-keccak-air", ] [[package]] name = "slop-koala-bear" -version = "6.3.1" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8795ee9a92ecf0a604c0e3ed20e80bbc38772310c0622f94a2e1b66ca2455cb8" +checksum = "b27fec4aae6811dbf6a384cc7993e74621aede443356ef67c301c19c1f302865" dependencies = [ "lazy_static", "p3-koala-bear", @@ -15071,29 +15305,28 @@ dependencies = [ [[package]] name = "slop-matrix" -version = "6.3.1" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50770150d6d5efc2ac3d20def5a6db2ca9d021defc74a414613174cfe40d96e1" +checksum = "b668966ea5646cfc06a1eb6f637c8c6f338daca2dbb653c9a189ef5af0a831b8" dependencies = [ "p3-matrix", ] [[package]] name = "slop-maybe-rayon" -version = "6.3.1" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9dc27cfc5036caca9642a71827c6b99b917fcd195285788d04f9b25f5df590e" +checksum = "0b8cf2b701f28e73aa2ebbb7a416d1e28725f58a8ad7d8b8db386dd60bd2f5aa" dependencies = [ "p3-maybe-rayon", ] [[package]] name = "slop-merkle-tree" -version = "6.3.1" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9bb16c7104504683851c4aea91b9b4d28ac8fc643ecd21d798da894889c261df" +checksum = "58ce5396280532acb12643e11b0f9d662c915dd9d58bf5ed4c80fdda46a2797a" dependencies = [ - "derive-where", "itertools 0.14.0", "p3-merkle-tree", "serde", @@ -15106,7 +15339,6 @@ dependencies = [ "slop-futures", "slop-koala-bear", "slop-matrix", - "slop-poseidon2", "slop-symmetric", "slop-tensor", "slop-utils", @@ -15115,12 +15347,11 @@ dependencies = [ [[package]] name = "slop-multilinear" -version = "6.3.1" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e46a58b8c6c7ab9fbb7dc55c68269b1d1d722beb23af8d6a1091c15877328145" +checksum = "c973e169c7c9584ec77c0a281b4a29ec20de9c3968796bbcea6002547cedabe2" dependencies = [ "derive-where", - "futures", "num_cpus", "rand 0.8.7", "rayon", @@ -15129,37 +15360,32 @@ dependencies = [ "slop-alloc", "slop-challenger", "slop-commit", - "slop-futures", "slop-matrix", "slop-tensor", ] [[package]] name = "slop-poseidon2" -version = "6.3.1" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25561d9ecf4bcf1aa2e800560ac557bff6dad943b9dc5cd0e8427fceca1e8c65" +checksum = "13388d3c92bac6214ef7585869b968cf895d2715ebbb8b1a0e1464dd2ada30b2" dependencies = [ "p3-poseidon2", ] [[package]] name = "slop-primitives" -version = "6.3.1" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6b24ad70b49f40d6acfe7b1ccf042db25820abe305a4c2232f15204f63f0227" -dependencies = [ - "slop-algebra", -] +checksum = "93f569cac42b24e672f6b06ffde272d4086c2c2620f16d31c1d1ce88cddff681" [[package]] name = "slop-stacked" -version = "6.3.1" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e7197d135a012724c2988e2c3a643a54eddbdaa0570b2540b55f39337b437cf" +checksum = "bc9b17529d7484d1c8d7a869db83c5aa741d8bfdfa9ed7903fc9c028410f4503" dependencies = [ "derive-where", - "futures", "itertools 0.14.0", "serde", "slop-algebra", @@ -15168,7 +15394,6 @@ dependencies = [ "slop-basefold-prover", "slop-challenger", "slop-commit", - "slop-futures", "slop-merkle-tree", "slop-multilinear", "slop-tensor", @@ -15177,11 +15402,10 @@ dependencies = [ [[package]] name = "slop-sumcheck" -version = "6.3.1" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4bcf5bf842f895678f170cc36ac7c4bc6521e7c119d24b2c0793f4bbcbe0d3d4" +checksum = "9d87410940ec3d14912b44a86a420ea2973a94e805b9e318fb127cd5ee4d6de3" dependencies = [ - "futures", "itertools 0.14.0", "rayon", "serde", @@ -15195,18 +15419,18 @@ dependencies = [ [[package]] name = "slop-symmetric" -version = "6.3.1" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94e580d03bb5383aca1c12579a8a24b838afb12eb356439e740cba34904b6864" +checksum = "693b50b55c3f5a2bb20dd3b975da79b80e4bf15b839b90f82e5dc7ba7262d3dc" dependencies = [ "p3-symmetric", ] [[package]] name = "slop-tensor" -version = "6.3.1" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4d4288b17090a89f1669437b7d4435b48da0e4a904669205c9b5d85afbf47176" +checksum = "3582c1eee176cbcc4d42dbfff1a8aea254c48ca907d0d1687729822491756a48" dependencies = [ "arrayvec", "derive-where", @@ -15216,7 +15440,6 @@ dependencies = [ "serde", "slop-algebra", "slop-alloc", - "slop-futures", "slop-matrix", "thiserror 1.0.69", "transpose", @@ -15224,32 +15447,31 @@ dependencies = [ [[package]] name = "slop-uni-stark" -version = "6.3.1" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "632cac9d74df33a49efd2ba559ab51171020d9a27c375abb29846f078fa50ad6" +checksum = "4afe09c7813c51c06d5a6df9a6e03590e3149db853526d3e110925a950df6232" dependencies = [ "p3-uni-stark", ] [[package]] name = "slop-utils" -version = "6.3.1" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c772904088f4b52275b7faedfa70fdb14dba514c3c4165b8ddb6bbad3b0eb67b" +checksum = "085f402d3f3ce1c843fdabf9d750e266e982186f3701fc56ce204fbf06bf18f0" dependencies = [ "p3-util", "tracing-forest", - "tracing-subscriber 0.3.23", + "tracing-subscriber", ] [[package]] name = "slop-whir" -version = "6.3.1" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52f5c2e680078bfcfa0b782ce3512c06b8fcf8e3bc373c6c291e32395580e780" +checksum = "2b7f6246ea3143f45dd48c224452943a0ca992a4c4766b537522b5f1eeef07ea" dependencies = [ "derive-where", - "futures", "itertools 0.14.0", "rand 0.8.7", "rayon", @@ -15257,7 +15479,6 @@ dependencies = [ "slop-algebra", "slop-alloc", "slop-baby-bear", - "slop-basefold", "slop-challenger", "slop-commit", "slop-dft", @@ -15266,7 +15487,6 @@ dependencies = [ "slop-matrix", "slop-merkle-tree", "slop-multilinear", - "slop-stacked", "slop-tensor", "slop-utils", "thiserror 1.0.69", @@ -15324,7 +15544,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -15345,9 +15565,9 @@ dependencies = [ [[package]] name = "sp1-build" -version = "6.3.1" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b86f0b3b6f39976825b472e2967e212b4e36f6dc395c74076b25b2ed52c605dd" +checksum = "40672b22ed12ff30619b043c1cbb2290f51261a1862e21a5a96270efda3583bd" dependencies = [ "anyhow", "cargo_metadata", @@ -15359,20 +15579,17 @@ dependencies = [ [[package]] name = "sp1-core-executor" -version = "6.3.1" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4dcb59c94af4b470b005468d7c089208bc2ac834363193a8cdc2418e60a211a" +checksum = "f45ca924caf27ceee7b00adfd4b3858c2cbaa1f394fb00cb4e584a62223d8d02" dependencies = [ "bincode 1.3.3", - "bytemuck", "cfg-if", - "clap", "deepsize2", "elf", "enum-map", "eyre", "hashbrown 0.14.5", - "hex", "itertools 0.14.0", "memmap2", "num", @@ -15393,16 +15610,16 @@ dependencies = [ "subenum", "thiserror 1.0.69", "tiny-keccak", + "tokio", "tracing", "typenum", - "vec_map", ] [[package]] name = "sp1-core-executor-runner" -version = "6.3.1" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "170ac89e5233e23cff58ad32f7cbbeced26c3ce190207d6b1c7c1f699525b655" +checksum = "20d74373eee66ec16ceb1e9aaa28d9d703210f13a3f1fe6b514c194df5b246f9" dependencies = [ "base64 0.22.1", "bincode 1.3.3", @@ -15422,9 +15639,9 @@ dependencies = [ [[package]] name = "sp1-core-executor-runner-binary" -version = "6.3.1" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "704fef851e9f123f669ef04045fcff122453b0ca6942cd00b61d27c291c71a87" +checksum = "211f1b73314b13fe4da22fe91d9a1a77d64df6be3172132f96c94aa0019babdf" dependencies = [ "bincode 1.3.3", "crash-handler", @@ -15432,19 +15649,17 @@ dependencies = [ "serde", "sp1-core-executor", "sp1-jit", - "tracing-subscriber 0.3.23", + "tracing-subscriber", ] [[package]] name = "sp1-core-machine" -version = "6.3.1" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20eaef541ed947056b37a7c16a149090a8c2a3e0d1e5f31fd1b0d688f1e9d96e" +checksum = "13e440279541a50a1e166ea008b70c0d30a64830418b829d9e36b920eea1eb7c" dependencies = [ "bincode 1.3.3", "cfg-if", - "enum-map", - "futures", "generic-array 1.1.0", "hashbrown 0.14.5", "itertools 0.14.0", @@ -15458,12 +15673,10 @@ dependencies = [ "slop-air", "slop-algebra", "slop-challenger", - "slop-futures", "slop-keccak-air", "slop-matrix", "slop-maybe-rayon", "slop-uni-stark", - "snowbridge-amcl", "sp1-core-executor", "sp1-core-executor-runner", "sp1-curves", @@ -15475,25 +15688,26 @@ dependencies = [ "struct-reflection", "strum 0.27.2", "sysinfo 0.30.13", - "tempfile", "thiserror 1.0.69", "tokio", "tracing", "tracing-forest", - "tracing-subscriber 0.3.23", + "tracing-subscriber", "typenum", ] [[package]] name = "sp1-curves" -version = "6.3.1" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93c3a16e1af983f60fb99176d340a401581677e63b7b1439ca034e83ca29476d" +checksum = "ac61970510b3b965a58935e986e0dd04815f82247966c5823dbe3cc451db6e8f" dependencies = [ "cfg-if", + "curve25519-dalek", "dashu", "elliptic-curve", "generic-array 1.1.0", + "group", "itertools 0.14.0", "k256", "num", @@ -15507,9 +15721,9 @@ dependencies = [ [[package]] name = "sp1-derive" -version = "6.3.1" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a34fe6b15dd14b498a3a4491c86ec2415bb70bac23571b18df1d15ac63c7bf8" +checksum = "7cbe5112430ab736c540513cf18d7e4e69d715ac347b90cefb45c4280f5da880" dependencies = [ "proc-macro2", "quote", @@ -15518,14 +15732,13 @@ dependencies = [ [[package]] name = "sp1-hypercube" -version = "6.3.1" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0a088f69335f9a594783d9ad3453be5f6f3abcc90b2387be57fb819acc3da203" +checksum = "422e4ae52c18e39f07a7f38b4593c4b002339193dc6d9f51e993b5cc2a5718df" dependencies = [ "arrayref", "deepsize2", "derive-where", - "futures", "hashbrown 0.14.5", "itertools 0.14.0", "num-bigint 0.4.8", @@ -15538,7 +15751,6 @@ dependencies = [ "slop-algebra", "slop-alloc", "slop-basefold", - "slop-basefold-prover", "slop-bn254", "slop-challenger", "slop-commit", @@ -15567,9 +15779,9 @@ dependencies = [ [[package]] name = "sp1-jit" -version = "6.3.1" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65367f7b364358c1d7514a063177fa8131219a5cf24beb1be5547b0a043ff5ba" +checksum = "5d0fc35717922ed7133f18a48c2cf257c31a3c09190e7951239b0fad2a1f8632" dependencies = [ "dynasmrt", "hashbrown 0.14.5", @@ -15584,9 +15796,9 @@ dependencies = [ [[package]] name = "sp1-lib" -version = "6.3.1" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "629b673d6aa3c666b41e14d699323413fa90195c906365ba8c49d1b8e4531151" +checksum = "1d4bc4b2a4b6e5fd3105912c722f51de9d66e2440a44e4ddffaad04bfba42bdf" dependencies = [ "bincode 1.3.3", "serde", @@ -15595,9 +15807,9 @@ dependencies = [ [[package]] name = "sp1-primitives" -version = "6.3.1" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "421b4590a89bf7c263f8a64844a4034ee8cb73c351498911ce0acd18da6b5ed2" +checksum = "d387e4babbee68d30774ef52aad88aad3607eda8145a0badfa823e1759187c0c" dependencies = [ "bincode 1.3.3", "blake3", @@ -15619,17 +15831,17 @@ dependencies = [ [[package]] name = "sp1-prover" -version = "6.3.1" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee3b14f599150ddbd3d3829ec4080dc9e10d6dac66e9741260d5a5a116fbcb02" +checksum = "2f0f1d58a3144090a2250f48d4743e3319e861a6537d3262d848380e2d284e59" dependencies = [ "anyhow", "bincode 1.3.3", "clap", "dirs", "either", - "enum-map", "eyre", + "fd-lock", "futures", "hashbrown 0.14.5", "hex", @@ -15639,7 +15851,6 @@ dependencies = [ "mti", "num-bigint 0.4.8", "opentelemetry 0.23.0", - "pin-project", "rand 0.8.7", "reqwest 0.12.28", "serde", @@ -15652,14 +15863,10 @@ dependencies = [ "slop-bn254", "slop-challenger", "slop-futures", - "slop-jagged", - "slop-multilinear", - "slop-stacked", "slop-symmetric", "sp1-core-executor", "sp1-core-executor-runner", "sp1-core-machine", - "sp1-derive", "sp1-hypercube", "sp1-jit", "sp1-primitives", @@ -15671,21 +15878,19 @@ dependencies = [ "sp1-recursion-machine", "sp1-verifier", "static_assertions", - "sysinfo 0.30.13", "tempfile", "thiserror 1.0.69", "tokio", "tonic 0.12.3", "tracing", - "tracing-appender", - "tracing-subscriber 0.3.23", + "tracing-subscriber", ] [[package]] name = "sp1-prover-types" -version = "6.3.1" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a0f0f1c83a25f309c404c61eaca7a0ccb62557042263c8b268f0df1c13d1fd94" +checksum = "9506d53b429a903c028517d325b12153a06015c7a0d698f9bde41b9de2f33072" dependencies = [ "anyhow", "async-scoped", @@ -15707,9 +15912,9 @@ dependencies = [ [[package]] name = "sp1-recursion-circuit" -version = "6.3.1" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10edc1eeca25c63957a49516b4daccfe05e7564f75111a7a2d6642367c7bb5c6" +checksum = "691d4940e635589ef3bc77e82d883c02c93cd6361adde60f5e75715cb3e97e99" dependencies = [ "bincode 1.3.3", "itertools 0.14.0", @@ -15747,9 +15952,9 @@ dependencies = [ [[package]] name = "sp1-recursion-compiler" -version = "6.3.1" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44e968795d47837d58dfec2d650ae72b128722a37096faadff6ac20f5cc716c5" +checksum = "b4e7e8bd9f63df9cbf683fe148ccc1fbe645b211470e470ac7f3b93794064f4d" dependencies = [ "backtrace", "cfg-if", @@ -15768,9 +15973,9 @@ dependencies = [ [[package]] name = "sp1-recursion-executor" -version = "6.3.1" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28918f6630db8b7dfca815ac97fb0e4442319e52aa5edb813e6e368059e28e93" +checksum = "115fa5ab8ff56deb955244f7525628a99b8d951883fb390678ea5bbd0c74f893" dependencies = [ "backtrace", "cfg-if", @@ -15792,14 +15997,13 @@ dependencies = [ [[package]] name = "sp1-recursion-gnark-ffi" -version = "6.3.1" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a0a020c7309bb3c62c34a1c9183106a7923e480b05b66c8a1d3419dc9b78d485" +checksum = "365c2d0b7da67108703dfd9c8f897e28ed24c6460f5af1ce5c7077222303421d" dependencies = [ "anyhow", "bincode 1.3.3", "cfg-if", - "hex", "num-bigint 0.4.8", "serde", "serde_json", @@ -15816,9 +16020,9 @@ dependencies = [ [[package]] name = "sp1-recursion-machine" -version = "6.3.1" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1abf661a1ee1f0abb3737c14086a9e2127cbd88392c290ac1622455bd757d1f" +checksum = "2978f9522abc4e53e55e58a2bd3b5ce812e0e275dce705b55c4c451648c083ea" dependencies = [ "itertools 0.14.0", "rand 0.8.7", @@ -15838,9 +16042,9 @@ dependencies = [ [[package]] name = "sp1-sdk" -version = "6.3.1" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac474619d83bd48d3bec8ffea7e620c6f490223a399f3ff8ad4826c146c25bef" +checksum = "b2e5996edef461e0e7351ed0312423e12b78a2f68d62eeb3aae1a535dca30644" dependencies = [ "alloy-primitives", "alloy-signer 1.8.3", @@ -15853,20 +16057,17 @@ dependencies = [ "backoff", "bincode 1.3.3", "cfg-if", - "dirs", "eventsource-stream", "futures", "hex", - "indicatif", "itertools 0.14.0", "k256", "num-bigint 0.4.8", "prost 0.13.5", "reqwest 0.12.28", "reqwest-middleware", - "rustls 0.23.43", + "rustls", "serde", - "sha2 0.10.9", "sp1-build", "sp1-core-executor", "sp1-core-executor-runner", @@ -15877,7 +16078,6 @@ dependencies = [ "sp1-prover-types", "sp1-recursion-executor", "sp1-verifier", - "strum 0.27.2", "tempfile", "thiserror 1.0.69", "tokio", @@ -15889,14 +16089,13 @@ dependencies = [ [[package]] name = "sp1-verifier" -version = "6.3.1" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6dbb411abb1ea167f9b0b082c95f62ede26ab7ba72349770292a60dc0e9a673" +checksum = "aca7223cc7a77e42536c7229c8016672737aab07f6149097d9c7a26324b29814" dependencies = [ "bincode 1.3.3", "blake3", "cfg-if", - "dirs", "hex", "lazy_static", "serde", @@ -16515,7 +16714,7 @@ dependencies = [ "tracing-opentelemetry 0.32.1", "tracing-opentelemetry-instrumentation-sdk", "tracing-serde 0.1.3", - "tracing-subscriber 0.3.23", + "tracing-subscriber", ] [[package]] @@ -16528,7 +16727,7 @@ dependencies = [ "getrandom 0.4.3", "once_cell", "rustix", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -16834,23 +17033,13 @@ dependencies = [ "tokio", ] -[[package]] -name = "tokio-rustls" -version = "0.24.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c28327cf380ac148141087fbfb9de9d7bd4e84ab5d2c28fbc911d753de8a7081" -dependencies = [ - "rustls 0.21.12", - "tokio", -] - [[package]] name = "tokio-rustls" version = "0.26.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61" dependencies = [ - "rustls 0.23.43", + "rustls", "tokio", ] @@ -16874,12 +17063,28 @@ checksum = "d25a406cddcc431a75d3d9afc6a7c0f7428d4891dd973e4d54c56b46127bf857" dependencies = [ "futures-util", "log", - "rustls 0.23.43", + "rustls", + "rustls-native-certs", + "rustls-pki-types", + "tokio", + "tokio-rustls", + "tungstenite 0.28.0", +] + +[[package]] +name = "tokio-tungstenite" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f72a05e828585856dacd553fba484c242c46e391fb0e58917c942ee9202915c" +dependencies = [ + "futures-util", + "log", + "rustls", "rustls-native-certs", "rustls-pki-types", "tokio", - "tokio-rustls 0.26.4", - "tungstenite", + "tokio-rustls", + "tungstenite 0.29.0", "webpki-roots 0.26.11", ] @@ -17000,11 +17205,11 @@ dependencies = [ "axum 0.7.9", "base64 0.22.1", "bytes", - "h2 0.4.15", + "h2", "http 1.5.0", "http-body 1.1.0", "http-body-util", - "hyper 1.11.0", + "hyper", "hyper-timeout", "hyper-util", "percent-encoding", @@ -17014,7 +17219,7 @@ dependencies = [ "rustls-pemfile", "socket2 0.5.10", "tokio", - "tokio-rustls 0.26.4", + "tokio-rustls", "tokio-stream", "tower 0.4.13", "tower-layer", @@ -17033,11 +17238,11 @@ dependencies = [ "axum 0.8.9", "base64 0.22.1", "bytes", - "h2 0.4.15", + "h2", "http 1.5.0", "http-body 1.1.0", "http-body-util", - "hyper 1.11.0", + "hyper", "hyper-timeout", "hyper-util", "percent-encoding", @@ -17193,7 +17398,7 @@ dependencies = [ "symlink", "thiserror 2.0.19", "time", - "tracing-subscriber 0.3.23", + "tracing-subscriber", ] [[package]] @@ -17215,7 +17420,7 @@ checksum = "bf0a738ed5d6450a9fb96e86a23ad808de2b727fd1394585da5cdd6788ffe724" dependencies = [ "serde_json", "tracing-core", - "tracing-subscriber 0.3.23", + "tracing-subscriber", ] [[package]] @@ -17235,7 +17440,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8b1581020d7a273442f5b45074a6a57d5757ad0a47dac0e9f0bd57b81936f3db" dependencies = [ "tracing", - "tracing-subscriber 0.3.23", + "tracing-subscriber", ] [[package]] @@ -17248,7 +17453,7 @@ dependencies = [ "smallvec", "thiserror 1.0.69", "tracing", - "tracing-subscriber 0.3.23", + "tracing-subscriber", ] [[package]] @@ -17269,7 +17474,7 @@ checksum = "2d3a81ed245bfb62592b1e2bc153e77656d94ee6a0497683a65a12ccaf2438d0" dependencies = [ "libc", "tracing-core", - "tracing-subscriber 0.3.23", + "tracing-subscriber", ] [[package]] @@ -17292,7 +17497,7 @@ dependencies = [ "time", "tracing", "tracing-core", - "tracing-subscriber 0.3.23", + "tracing-subscriber", ] [[package]] @@ -17307,7 +17512,7 @@ dependencies = [ "tracing", "tracing-core", "tracing-log", - "tracing-subscriber 0.3.23", + "tracing-subscriber", "web-time", ] @@ -17323,7 +17528,7 @@ dependencies = [ "tracing", "tracing-core", "tracing-log", - "tracing-subscriber 0.3.23", + "tracing-subscriber", "web-time", ] @@ -17353,7 +17558,7 @@ dependencies = [ "memmap2", "smallvec", "tracing-core", - "tracing-subscriber 0.3.23", + "tracing-subscriber", ] [[package]] @@ -17376,15 +17581,6 @@ dependencies = [ "tracing-core", ] -[[package]] -name = "tracing-subscriber" -version = "0.2.25" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e0d2eaa99c3c2e41547cfa109e910a68ea03823cccad4a0525dcbc9b01e8c71" -dependencies = [ - "tracing-core", -] - [[package]] name = "tracing-subscriber" version = "0.3.23" @@ -17469,13 +17665,31 @@ dependencies = [ "httparse", "log", "rand 0.9.5", - "rustls 0.23.43", + "rustls", "rustls-pki-types", "sha1 0.10.7", "thiserror 2.0.19", "utf-8", ] +[[package]] +name = "tungstenite" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c01152af293afb9c7c2a57e4b559c5620b421f6d133261c60dd2d0cdb38e6b8" +dependencies = [ + "bytes", + "data-encoding", + "http 1.5.0", + "httparse", + "log", + "rand 0.9.5", + "rustls", + "rustls-pki-types", + "sha1 0.10.7", + "thiserror 2.0.19", +] + [[package]] name = "twirp-rs" version = "0.13.0-succinct" @@ -17487,7 +17701,7 @@ dependencies = [ "futures", "http 1.5.0", "http-body-util", - "hyper 1.11.0", + "hyper", "prost 0.13.5", "reqwest 0.12.28", "serde", @@ -17672,7 +17886,7 @@ dependencies = [ "base64 0.22.1", "log", "percent-encoding", - "rustls 0.23.43", + "rustls", "rustls-pki-types", "ureq-proto", "utf8-zero", @@ -17765,9 +17979,6 @@ name = "vec_map" version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f1bddf1187be692e79c5ffeab891132dfb0f236ed36a43c7ed39f1165ee20191" -dependencies = [ - "serde", -] [[package]] name = "vergen" @@ -18011,14 +18222,14 @@ version = "0.26.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "75c7f0ef91146ebfb530314f5f1d24528d7f0767efbfd31dce919275413e393e" dependencies = [ - "webpki-root-certs 1.0.9", + "webpki-root-certs 1.0.10", ] [[package]] name = "webpki-root-certs" -version = "1.0.9" +version = "1.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b96554aa2acc8ccdb7e1c9a58a7a68dd5d13bccc69cd124cb09406db612a1c9b" +checksum = "58ec80e73fd8baf57bf0d9615554c75348bda990d6d5bbeab964dd068319fecb" dependencies = [ "rustls-pki-types", ] @@ -18029,14 +18240,14 @@ version = "0.26.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9" dependencies = [ - "webpki-roots 1.0.9", + "webpki-roots 1.0.10", ] [[package]] name = "webpki-roots" -version = "1.0.9" +version = "1.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a" +checksum = "1c1c8e20c8a38fc7d65abfe74eb7280e4aa667e8eec8bc84996d2874810748d9" dependencies = [ "rustls-pki-types", ] @@ -18085,7 +18296,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.48.0", ] [[package]] @@ -18572,13 +18783,12 @@ checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" [[package]] name = "world-chain" -version = "2.4.3" +version = "2.6.0" dependencies = [ "clap", "color-eyre", "dotenvy", "firehose-tracer", - "reth-chainspec", "reth-cli-util", "reth-firehose", "reth-node-builder", @@ -18596,15 +18806,15 @@ dependencies = [ [[package]] name = "world-chain-builder" -version = "2.4.3" +version = "2.6.0" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", - "alloy-network 2.1.1", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", + "alloy-network 2.5.0", "alloy-op-evm", "alloy-primitives", "alloy-rpc-types-engine", - "alloy-signer-local 2.1.1", + "alloy-signer-local 2.5.0", "color-eyre", "criterion", "crossbeam-channel", @@ -18647,11 +18857,11 @@ dependencies = [ [[package]] name = "world-chain-chainspec" -version = "2.4.3" +version = "2.6.0" dependencies = [ "alloy-chains", - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", "alloy-genesis", "alloy-hardforks", "alloy-primitives", @@ -18669,16 +18879,16 @@ dependencies = [ [[package]] name = "world-chain-challenger" -version = "1.0.0-rc.1" +version = "1.0.0-rc.5" dependencies = [ - "alloy-consensus 2.1.1", + "alloy-consensus 2.5.0", "alloy-contract", - "alloy-eips 2.1.1", - "alloy-network 2.1.1", + "alloy-eips 2.5.0", + "alloy-network 2.5.0", "alloy-primitives", "alloy-provider", - "alloy-rpc-types-eth 2.1.1", - "alloy-signer-local 2.1.1", + "alloy-rpc-types-eth 2.5.0", + "alloy-signer-local 2.5.0", "alloy-transport", "anyhow", "async-trait", @@ -18700,12 +18910,12 @@ dependencies = [ [[package]] name = "world-chain-cli" -version = "2.4.3" +version = "2.6.0" dependencies = [ "alloy-chains", "alloy-genesis", "alloy-primitives", - "alloy-signer-local 2.1.1", + "alloy-signer-local 2.5.0", "clap", "color-eyre", "ed25519-dalek", @@ -18735,7 +18945,7 @@ dependencies = [ [[package]] name = "world-chain-commands" -version = "2.4.3" +version = "2.6.0" dependencies = [ "clap", "color-eyre", @@ -18753,13 +18963,13 @@ dependencies = [ [[package]] name = "world-chain-defender" -version = "1.0.0-rc.1" +version = "1.0.0-rc.5" dependencies = [ "alloy-contract", - "alloy-network 2.1.1", + "alloy-network 2.5.0", "alloy-primitives", "alloy-provider", - "alloy-signer-local 2.1.1", + "alloy-signer-local 2.5.0", "alloy-sol-types", "alloy-transport", "anyhow", @@ -18771,6 +18981,7 @@ dependencies = [ "thiserror 2.0.19", "tokio", "tracing", + "tracing-subscriber", "url", "world-chain-proof-core", "world-chain-proof-metrics", @@ -18781,15 +18992,16 @@ dependencies = [ [[package]] name = "world-chain-devnet" -version = "2.4.3" +version = "2.6.0" dependencies = [ - "alloy-eips 2.1.1", + "alloy-contract", + "alloy-eips 2.5.0", "alloy-genesis", "alloy-hardforks", - "alloy-network 2.1.1", + "alloy-network 2.5.0", "alloy-primitives", "alloy-provider", - "alloy-signer-local 2.1.1", + "alloy-signer-local 2.5.0", "alloy-sol-types", "anyhow", "async-trait", @@ -18838,11 +19050,11 @@ dependencies = [ [[package]] name = "world-chain-evm" -version = "2.4.3" +version = "2.6.0" dependencies = [ - "alloy-consensus 2.1.1", + "alloy-consensus 2.5.0", "alloy-eip7928 0.4.5", - "alloy-eips 2.1.1", + "alloy-eips 2.5.0", "alloy-op-evm", "alloy-primitives", "alloy-rpc-types-debug", @@ -18879,14 +19091,14 @@ dependencies = [ [[package]] name = "world-chain-node" -version = "2.4.3" +version = "2.6.0" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", "alloy-primitives", "alloy-rpc-types", "alloy-rpc-types-engine", - "alloy-rpc-types-eth 2.1.1", + "alloy-rpc-types-eth 2.5.0", "color-eyre", "crossbeam-channel", "ed25519-dalek", @@ -18945,9 +19157,9 @@ dependencies = [ [[package]] name = "world-chain-p2p" -version = "2.4.3" +version = "2.6.0" dependencies = [ - "alloy-eips 2.1.1", + "alloy-eips 2.5.0", "alloy-primitives", "alloy-rlp", "alloy-rpc-types-engine", @@ -18983,9 +19195,9 @@ dependencies = [ [[package]] name = "world-chain-payload" -version = "2.4.3" +version = "2.6.0" dependencies = [ - "alloy-eips 2.1.1", + "alloy-eips 2.5.0", "alloy-primitives", "color-eyre", "futures", @@ -19012,7 +19224,7 @@ dependencies = [ [[package]] name = "world-chain-pbh" -version = "2.4.3" +version = "2.6.0" dependencies = [ "alloy-primitives", "alloy-rlp", @@ -19029,10 +19241,10 @@ dependencies = [ [[package]] name = "world-chain-pool" -version = "2.4.3" +version = "2.6.0" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", "alloy-primitives", "alloy-rlp", "alloy-rpc-types", @@ -19066,17 +19278,17 @@ dependencies = [ [[package]] name = "world-chain-primitives" -version = "2.4.3" +version = "2.6.0" dependencies = [ - "alloy-consensus 2.1.1", + "alloy-consensus 2.5.0", "alloy-eip7928 0.4.5", - "alloy-eips 2.1.1", + "alloy-eips 2.5.0", "alloy-primitives", "alloy-rlp", "alloy-rpc-types-engine", - "alloy-rpc-types-eth 2.1.1", - "alloy-serde 2.1.1", - "alloy-signer-local 2.1.1", + "alloy-rpc-types-eth 2.5.0", + "alloy-serde 2.5.0", + "alloy-signer-local 2.5.0", "blake3", "bytes", "chrono", @@ -19100,20 +19312,13 @@ dependencies = [ [[package]] name = "world-chain-proof-core" -version = "1.0.0-rc.1" +version = "1.0.0-rc.5" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", "alloy-primitives", "alloy-sol-types", - "anyhow", - "async-trait", - "kona-derive", "kona-genesis", - "kona-preimage", "kona-proof", - "kona-protocol", - "kzg-rs", + "kona-sp1-client-utils", "rkyv", "serde", "serde_json", @@ -19123,7 +19328,7 @@ dependencies = [ [[package]] name = "world-chain-proof-it" -version = "1.0.0-rc.1" +version = "1.0.0-rc.5" dependencies = [ "alloy-primitives", "alloy-sol-types", @@ -19144,10 +19349,9 @@ dependencies = [ [[package]] name = "world-chain-proof-kona-client" -version = "1.0.0-rc.1" +version = "1.0.0-rc.5" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", + "alloy-consensus 2.5.0", "alloy-evm", "alloy-op-evm", "alloy-primitives", @@ -19156,17 +19360,12 @@ dependencies = [ "async-trait", "kona-derive", "kona-driver", - "kona-executor", "kona-genesis", "kona-preimage", "kona-proof", - "kona-protocol", - "kzg-rs", - "op-alloy-consensus", + "kona-sp1-client-utils", "op-revm", "revm", - "revm-precompile", - "serde", "spin 0.10.1", "tracing", "world-chain-proof-core", @@ -19174,27 +19373,22 @@ dependencies = [ [[package]] name = "world-chain-proof-kona-host" -version = "1.0.0-rc.1" +version = "1.0.0-rc.5" dependencies = [ - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", + "alloy-consensus 2.5.0", "alloy-primitives", "anyhow", - "async-trait", - "c-kzg", "hex", - "kona-derive", "kona-genesis", "kona-host", "kona-preimage", "kona-proof", "kona-protocol", - "kzg-rs", + "kona-sp1-host-utils", "reqwest 0.12.28", "serde", "serde_json", "tokio", - "tracing", "world-chain-chainspec", "world-chain-proof-core", "world-chain-proof-kona-client", @@ -19202,9 +19396,9 @@ dependencies = [ [[package]] name = "world-chain-proof-metrics" -version = "1.0.0-rc.1" +version = "1.0.0-rc.5" dependencies = [ - "alloy-json-rpc 2.1.1", + "alloy-json-rpc 2.5.0", "alloy-primitives", "alloy-provider", "alloy-rpc-client", @@ -19218,7 +19412,7 @@ dependencies = [ [[package]] name = "world-chain-proof-nitro-enclave" -version = "1.0.0-rc.1" +version = "1.0.0-rc.5" dependencies = [ "alloy-primitives", "alloy-sol-types", @@ -19235,7 +19429,7 @@ dependencies = [ "p384", "rkyv", "rustls-pki-types", - "rustls-webpki 0.103.13", + "rustls-webpki", "serde", "serde_bytes", "sha2 0.10.9", @@ -19243,7 +19437,7 @@ dependencies = [ "tokio", "tokio-vsock", "tracing", - "tracing-subscriber 0.3.23", + "tracing-subscriber", "world-chain-proof-core", "world-chain-proof-kona-client", "x509-parser", @@ -19251,13 +19445,13 @@ dependencies = [ [[package]] name = "world-chain-proof-nitro-register" -version = "1.0.0-rc.1" +version = "1.0.0-rc.5" dependencies = [ "alloy-contract", "alloy-primitives", "alloy-provider", - "alloy-signer 2.1.1", - "alloy-signer-local 2.1.1", + "alloy-signer 2.5.0", + "alloy-signer-local 2.5.0", "alloy-sol-types", "anyhow", "ciborium", @@ -19272,7 +19466,7 @@ dependencies = [ [[package]] name = "world-chain-proof-nitro-worker" -version = "1.0.0-rc.1" +version = "1.0.0-rc.5" dependencies = [ "alloy-primitives", "alloy-provider", @@ -19298,7 +19492,7 @@ dependencies = [ [[package]] name = "world-chain-proof-protocol" -version = "1.0.0-rc.1" +version = "1.0.0-rc.5" dependencies = [ "alloy-contract", "alloy-primitives", @@ -19319,7 +19513,7 @@ dependencies = [ [[package]] name = "world-chain-proof-sp1-elfs" -version = "1.0.0-rc.1" +version = "1.0.0-rc.5" dependencies = [ "sp1-build", "sp1-sdk", @@ -19327,7 +19521,7 @@ dependencies = [ [[package]] name = "world-chain-proof-sp1-guest-builder" -version = "1.0.0-rc.1" +version = "1.0.0-rc.5" dependencies = [ "anyhow", "sp1-build", @@ -19335,7 +19529,7 @@ dependencies = [ [[package]] name = "world-chain-proof-sp1-host" -version = "1.0.0-rc.1" +version = "1.0.0-rc.5" dependencies = [ "alloy-primitives", "alloy-sol-types", @@ -19356,12 +19550,11 @@ dependencies = [ "world-chain-proof-kona-host", "world-chain-proof-sp1-elfs", "world-chain-proof-sp1-types", - "world-chain-prover-service", ] [[package]] name = "world-chain-proof-sp1-types" -version = "1.0.0-rc.1" +version = "1.0.0-rc.5" dependencies = [ "alloy-primitives", "rkyv", @@ -19371,14 +19564,14 @@ dependencies = [ [[package]] name = "world-chain-proof-sp1-worker" -version = "1.0.0-rc.1" +version = "1.0.0-rc.5" dependencies = [ "alloy-contract", - "alloy-network 2.1.1", + "alloy-network 2.5.0", "alloy-primitives", "alloy-provider", - "alloy-signer 2.1.1", - "alloy-signer-local 2.1.1", + "alloy-signer 2.5.0", + "alloy-signer-local 2.5.0", "alloy-sol-types", "anyhow", "async-trait", @@ -19386,7 +19579,7 @@ dependencies = [ "dotenvy", "futures", "reqwest 0.12.28", - "rustls 0.23.43", + "rustls", "serde", "serde_cbor", "serde_json", @@ -19411,13 +19604,13 @@ dependencies = [ [[package]] name = "world-chain-proof-tx-signer" -version = "1.0.0-rc.1" +version = "1.0.0-rc.5" dependencies = [ - "alloy-network 2.1.1", + "alloy-network 2.5.0", "alloy-primitives", "alloy-provider", - "alloy-signer-aws 2.1.1", - "alloy-signer-local 2.1.1", + "alloy-signer-aws 2.5.0", + "alloy-signer-local 2.5.0", "alloy-transport", "aws-config", "aws-sdk-kms", @@ -19428,7 +19621,7 @@ dependencies = [ [[package]] name = "world-chain-proof-worker" -version = "1.0.0-rc.1" +version = "1.0.0-rc.5" dependencies = [ "alloy-primitives", "anyhow", @@ -19443,15 +19636,15 @@ dependencies = [ [[package]] name = "world-chain-proposer" -version = "1.0.0-rc.1" +version = "1.0.0-rc.5" dependencies = [ - "alloy-consensus 2.1.1", + "alloy-consensus 2.5.0", "alloy-contract", - "alloy-eips 2.1.1", - "alloy-network 2.1.1", + "alloy-eips 2.5.0", + "alloy-network 2.5.0", "alloy-primitives", "alloy-provider", - "alloy-signer-local 2.1.1", + "alloy-signer-local 2.5.0", "alloy-transport", "anyhow", "async-trait", @@ -19472,7 +19665,7 @@ dependencies = [ [[package]] name = "world-chain-prover" -version = "1.0.0-rc.1" +version = "1.0.0-rc.5" dependencies = [ "alloy-primitives", "anyhow", @@ -19490,7 +19683,7 @@ dependencies = [ [[package]] name = "world-chain-prover-cli" -version = "1.0.0-rc.1" +version = "1.0.0-rc.5" dependencies = [ "alloy-primitives", "alloy-provider", @@ -19500,7 +19693,7 @@ dependencies = [ "reqwest 0.12.28", "tokio", "tracing", - "tracing-subscriber 0.3.23", + "tracing-subscriber", "world-chain-proof-kona-host", "world-chain-proof-protocol", "world-chain-prover-service", @@ -19508,7 +19701,7 @@ dependencies = [ [[package]] name = "world-chain-prover-nitro" -version = "1.0.0-rc.1" +version = "1.0.0-rc.5" dependencies = [ "anyhow", "clap", @@ -19516,7 +19709,7 @@ dependencies = [ "hex", "serde_json", "tokio", - "tracing-subscriber 0.3.23", + "tracing-subscriber", "world-chain-proof-nitro-enclave", "world-chain-proof-nitro-register", "world-chain-prover", @@ -19524,9 +19717,12 @@ dependencies = [ [[package]] name = "world-chain-prover-service" -version = "1.0.0-rc.1" +version = "1.0.0-rc.5" dependencies = [ "alloy-primitives", + "alloy-provider", + "alloy-sol-types", + "alloy-transport", "anyhow", "async-trait", "auto_impl", @@ -19545,11 +19741,12 @@ dependencies = [ "tracing", "uuid", "world-chain-proof-metrics", + "world-chain-proof-protocol", ] [[package]] name = "world-chain-prover-sp1" -version = "1.0.0-rc.1" +version = "1.0.0-rc.5" dependencies = [ "alloy-primitives", "anyhow", @@ -19569,11 +19766,11 @@ dependencies = [ [[package]] name = "world-chain-rpc" -version = "2.4.3" +version = "2.6.0" dependencies = [ "alloy", - "alloy-consensus 2.1.1", - "alloy-eips 2.1.1", + "alloy-consensus 2.5.0", + "alloy-eips 2.5.0", "alloy-op-evm", "alloy-primitives", "alloy-provider", @@ -19597,7 +19794,6 @@ dependencies = [ "reth-evm", "reth-node-api", "reth-node-builder", - "reth-optimism-evm", "reth-optimism-forks", "reth-optimism-node", "reth-optimism-primitives", @@ -19628,22 +19824,22 @@ dependencies = [ [[package]] name = "world-chain-test-utils" -version = "2.4.3" +version = "2.6.0" dependencies = [ - "alloy-consensus 2.1.1", + "alloy-consensus 2.5.0", "alloy-contract", - "alloy-eips 2.1.1", + "alloy-eips 2.5.0", "alloy-evm", "alloy-genesis", - "alloy-network 2.1.1", + "alloy-network 2.5.0", "alloy-op-evm", "alloy-primitives", "alloy-provider", "alloy-rpc-types", "alloy-rpc-types-engine", - "alloy-rpc-types-eth 2.1.1", - "alloy-signer 2.1.1", - "alloy-signer-local 2.1.1", + "alloy-rpc-types-eth 2.5.0", + "alloy-signer 2.5.0", + "alloy-signer-local 2.5.0", "alloy-sol-types", "alloy-trie", "bon", @@ -19685,6 +19881,7 @@ dependencies = [ "reth-rpc-api", "reth-rpc-server-types", "reth-stages-types", + "reth-storage-errors", "reth-tasks", "reth-tracing", "reth-transaction-pool", @@ -19712,20 +19909,20 @@ dependencies = [ [[package]] name = "world-chain-tests" -version = "2.4.3" +version = "2.6.0" dependencies = [ - "alloy-consensus 2.1.1", + "alloy-consensus 2.5.0", "alloy-contract", - "alloy-eips 2.1.1", - "alloy-network 2.1.1", + "alloy-eips 2.5.0", + "alloy-network 2.5.0", "alloy-primitives", "alloy-provider", "alloy-rpc-client", "alloy-rpc-types", "alloy-rpc-types-engine", - "alloy-rpc-types-eth 2.1.1", - "alloy-signer 2.1.1", - "alloy-signer-local 2.1.1", + "alloy-rpc-types-eth 2.5.0", + "alloy-signer 2.5.0", + "alloy-signer-local 2.5.0", "alloy-sol-types", "alloy-transport", "alloy-transport-http", @@ -19778,11 +19975,11 @@ dependencies = [ [[package]] name = "world-chain-validator" -version = "2.4.3" +version = "2.6.0" dependencies = [ - "alloy-consensus 2.1.1", + "alloy-consensus 2.5.0", "alloy-eip7928 0.4.5", - "alloy-eips 2.1.1", + "alloy-eips 2.5.0", "alloy-op-evm", "alloy-primitives", "alloy-rlp", @@ -19793,6 +19990,8 @@ dependencies = [ "futures", "metrics", "metrics-derive", + "op-alloy-consensus", + "op-revm", "parking_lot", "rayon", "reth-chain-state", @@ -19894,18 +20093,18 @@ checksum = "66fee0b777b0f5ac1c69bb06d361268faafa61cd4682ae064a171c16c433e9e4" [[package]] name = "xtask" -version = "2.4.3" +version = "2.6.0" dependencies = [ - "alloy-consensus 2.1.1", + "alloy-consensus 2.5.0", "alloy-contract", - "alloy-eips 2.1.1", + "alloy-eips 2.5.0", "alloy-primitives", "alloy-provider", "alloy-rlp", "alloy-rpc-client", - "alloy-rpc-types-eth 2.1.1", - "alloy-signer 2.1.1", - "alloy-signer-local 2.1.1", + "alloy-rpc-types-eth 2.5.0", + "alloy-signer 2.5.0", + "alloy-signer-local 2.5.0", "alloy-sol-types", "alloy-transport-http", "bytes", @@ -19929,7 +20128,7 @@ dependencies = [ "tokio", "tracing", "tracing-appender", - "tracing-subscriber 0.3.23", + "tracing-subscriber", "world-chain-chainspec", "world-chain-cli", "world-chain-devnet", diff --git a/Cargo.toml b/Cargo.toml index 578cc7cb3..473b1ae09 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,5 +1,5 @@ [workspace.package] -version = "2.4.3" +version = "2.6.0" edition = "2024" rust-version = "1.95.0" license = "MIT" @@ -47,6 +47,7 @@ members = [ "proofs/debug/bin/prover-cli", "proofs/debug/prover", "e2e-tests", + "e2e-tests/e2e-withdrawal", "xtask", ] @@ -68,7 +69,7 @@ codegen-units = 1 inherits = "release" lto = "fat" strip = "none" -panic = "abort" +panic = "unwind" [profile.dev-tracing] inherits = "dev" @@ -122,111 +123,111 @@ world-chain-defender = { path = "proofs/services/defender", default-features = f world-chain-proof-tx-signer = { path = "proofs/services/tx-signer", default-features = false } # reth crates.io -reth-codecs = { version = "0.5.0", default-features = false } -reth-primitives-traits = { version = "0.5.0", default-features = false } +reth-codecs = { version = "0.6.0", default-features = false } +reth-primitives-traits = { version = "0.6.0", default-features = false } # reth github -reth-trie-parallel = { git = "https://github.com/op-rs/reth", rev = "aef8d3ef92117f91455e16969f0adf5bf7c6e9e1", default-features = false } -reth-execution-cache = { git = "https://github.com/op-rs/reth", rev = "aef8d3ef92117f91455e16969f0adf5bf7c6e9e1", default-features = false } -reth-cli-util = { git = "https://github.com/op-rs/reth", rev = "aef8d3ef92117f91455e16969f0adf5bf7c6e9e1", default-features = false } -reth-cli = { git = "https://github.com/op-rs/reth", rev = "aef8d3ef92117f91455e16969f0adf5bf7c6e9e1", default-features = false } -reth-cli-commands = { git = "https://github.com/op-rs/reth", rev = "aef8d3ef92117f91455e16969f0adf5bf7c6e9e1", default-features = false } -reth-cli-runner = { git = "https://github.com/op-rs/reth", rev = "aef8d3ef92117f91455e16969f0adf5bf7c6e9e1", default-features = false } -reth-engine-primitives = { git = "https://github.com/op-rs/reth", rev = "aef8d3ef92117f91455e16969f0adf5bf7c6e9e1", default-features = false } -reth-evm = { git = "https://github.com/op-rs/reth", rev = "aef8d3ef92117f91455e16969f0adf5bf7c6e9e1", default-features = false } -reth-db = { git = "https://github.com/op-rs/reth", rev = "aef8d3ef92117f91455e16969f0adf5bf7c6e9e1", default-features = false } -reth-db-api = { git = "https://github.com/op-rs/reth", rev = "aef8d3ef92117f91455e16969f0adf5bf7c6e9e1", default-features = false } -reth-provider = { git = "https://github.com/op-rs/reth", rev = "aef8d3ef92117f91455e16969f0adf5bf7c6e9e1", default-features = false } -reth-basic-payload-builder = { git = "https://github.com/op-rs/reth", rev = "aef8d3ef92117f91455e16969f0adf5bf7c6e9e1", default-features = false } -reth-transaction-pool = { git = "https://github.com/op-rs/reth", rev = "aef8d3ef92117f91455e16969f0adf5bf7c6e9e1", default-features = false } -reth-rpc-server-types = { git = "https://github.com/op-rs/reth", rev = "aef8d3ef92117f91455e16969f0adf5bf7c6e9e1", default-features = false } -reth-rpc = { git = "https://github.com/op-rs/reth", rev = "aef8d3ef92117f91455e16969f0adf5bf7c6e9e1", default-features = false } -reth-rpc-api = { git = "https://github.com/op-rs/reth", rev = "aef8d3ef92117f91455e16969f0adf5bf7c6e9e1", default-features = false } -reth-rpc-eth-api = { git = "https://github.com/op-rs/reth", rev = "aef8d3ef92117f91455e16969f0adf5bf7c6e9e1", default-features = false } -reth-rpc-eth-types = { git = "https://github.com/op-rs/reth", rev = "aef8d3ef92117f91455e16969f0adf5bf7c6e9e1", default-features = false } -reth-prune-types = { git = "https://github.com/op-rs/reth", rev = "aef8d3ef92117f91455e16969f0adf5bf7c6e9e1", default-features = false } -reth-trie = { git = "https://github.com/op-rs/reth", rev = "aef8d3ef92117f91455e16969f0adf5bf7c6e9e1", default-features = false } -reth-chain-state = { git = "https://github.com/op-rs/reth", rev = "aef8d3ef92117f91455e16969f0adf5bf7c6e9e1", default-features = false } -reth-ethereum = { git = "https://github.com/op-rs/reth", rev = "aef8d3ef92117f91455e16969f0adf5bf7c6e9e1", default-features = false, features = [ +reth-trie-parallel = { git = "https://github.com/ethereum-optimism/reth", rev = "0fbe428518594611bdd3fdd822eb5968823c8e66", default-features = false } +reth-execution-cache = { git = "https://github.com/ethereum-optimism/reth", rev = "0fbe428518594611bdd3fdd822eb5968823c8e66", default-features = false } +reth-cli-util = { git = "https://github.com/ethereum-optimism/reth", rev = "0fbe428518594611bdd3fdd822eb5968823c8e66", default-features = false } +reth-cli = { git = "https://github.com/ethereum-optimism/reth", rev = "0fbe428518594611bdd3fdd822eb5968823c8e66", default-features = false } +reth-cli-commands = { git = "https://github.com/ethereum-optimism/reth", rev = "0fbe428518594611bdd3fdd822eb5968823c8e66", default-features = false } +reth-cli-runner = { git = "https://github.com/ethereum-optimism/reth", rev = "0fbe428518594611bdd3fdd822eb5968823c8e66", default-features = false } +reth-engine-primitives = { git = "https://github.com/ethereum-optimism/reth", rev = "0fbe428518594611bdd3fdd822eb5968823c8e66", default-features = false } +reth-evm = { git = "https://github.com/ethereum-optimism/reth", rev = "0fbe428518594611bdd3fdd822eb5968823c8e66", default-features = false } +reth-db = { git = "https://github.com/ethereum-optimism/reth", rev = "0fbe428518594611bdd3fdd822eb5968823c8e66", default-features = false } +reth-db-api = { git = "https://github.com/ethereum-optimism/reth", rev = "0fbe428518594611bdd3fdd822eb5968823c8e66", default-features = false } +reth-provider = { git = "https://github.com/ethereum-optimism/reth", rev = "0fbe428518594611bdd3fdd822eb5968823c8e66", default-features = false } +reth-basic-payload-builder = { git = "https://github.com/ethereum-optimism/reth", rev = "0fbe428518594611bdd3fdd822eb5968823c8e66", default-features = false } +reth-transaction-pool = { git = "https://github.com/ethereum-optimism/reth", rev = "0fbe428518594611bdd3fdd822eb5968823c8e66", default-features = false } +reth-rpc-server-types = { git = "https://github.com/ethereum-optimism/reth", rev = "0fbe428518594611bdd3fdd822eb5968823c8e66", default-features = false } +reth-rpc = { git = "https://github.com/ethereum-optimism/reth", rev = "0fbe428518594611bdd3fdd822eb5968823c8e66", default-features = false } +reth-rpc-api = { git = "https://github.com/ethereum-optimism/reth", rev = "0fbe428518594611bdd3fdd822eb5968823c8e66", default-features = false } +reth-rpc-eth-api = { git = "https://github.com/ethereum-optimism/reth", rev = "0fbe428518594611bdd3fdd822eb5968823c8e66", default-features = false } +reth-rpc-eth-types = { git = "https://github.com/ethereum-optimism/reth", rev = "0fbe428518594611bdd3fdd822eb5968823c8e66", default-features = false } +reth-prune-types = { git = "https://github.com/ethereum-optimism/reth", rev = "0fbe428518594611bdd3fdd822eb5968823c8e66", default-features = false } +reth-trie = { git = "https://github.com/ethereum-optimism/reth", rev = "0fbe428518594611bdd3fdd822eb5968823c8e66", default-features = false } +reth-chain-state = { git = "https://github.com/ethereum-optimism/reth", rev = "0fbe428518594611bdd3fdd822eb5968823c8e66", default-features = false } +reth-ethereum = { git = "https://github.com/ethereum-optimism/reth", rev = "0fbe428518594611bdd3fdd822eb5968823c8e66", default-features = false, features = [ "network", ] } -reth-eth-wire = { git = "https://github.com/op-rs/reth", rev = "aef8d3ef92117f91455e16969f0adf5bf7c6e9e1", default-features = false } -reth-eth-wire-types = { git = "https://github.com/op-rs/reth", rev = "aef8d3ef92117f91455e16969f0adf5bf7c6e9e1", default-features = false } -reth-stages-types = { git = "https://github.com/op-rs/reth", rev = "aef8d3ef92117f91455e16969f0adf5bf7c6e9e1", default-features = false } -reth-trie-db = { git = "https://github.com/op-rs/reth", rev = "aef8d3ef92117f91455e16969f0adf5bf7c6e9e1", default-features = false } -reth-node-builder = { git = "https://github.com/op-rs/reth", rev = "aef8d3ef92117f91455e16969f0adf5bf7c6e9e1", default-features = false } -reth-node-metrics = { git = "https://github.com/op-rs/reth", rev = "aef8d3ef92117f91455e16969f0adf5bf7c6e9e1", default-features = false } -reth-engine-local = { git = "https://github.com/op-rs/reth", rev = "aef8d3ef92117f91455e16969f0adf5bf7c6e9e1", default-features = false } -reth-engine-tree = { git = "https://github.com/op-rs/reth", rev = "aef8d3ef92117f91455e16969f0adf5bf7c6e9e1", default-features = false } -reth-node-api = { git = "https://github.com/op-rs/reth", rev = "aef8d3ef92117f91455e16969f0adf5bf7c6e9e1", default-features = false } -reth-payload-builder = { git = "https://github.com/op-rs/reth", rev = "aef8d3ef92117f91455e16969f0adf5bf7c6e9e1", default-features = false } -reth-payload-primitives = { git = "https://github.com/op-rs/reth", rev = "aef8d3ef92117f91455e16969f0adf5bf7c6e9e1", default-features = false } -reth-payload-util = { git = "https://github.com/op-rs/reth", rev = "aef8d3ef92117f91455e16969f0adf5bf7c6e9e1", default-features = false } -reth-payload-validator = { git = "https://github.com/op-rs/reth", rev = "aef8d3ef92117f91455e16969f0adf5bf7c6e9e1", default-features = false } -reth-revm = { git = "https://github.com/op-rs/reth", rev = "aef8d3ef92117f91455e16969f0adf5bf7c6e9e1", default-features = false } -reth-tasks = { git = "https://github.com/op-rs/reth", rev = "aef8d3ef92117f91455e16969f0adf5bf7c6e9e1", default-features = false } -reth-trie-common = { git = "https://github.com/op-rs/reth", rev = "aef8d3ef92117f91455e16969f0adf5bf7c6e9e1", default-features = false } -reth-chainspec = { git = "https://github.com/op-rs/reth", rev = "aef8d3ef92117f91455e16969f0adf5bf7c6e9e1", default-features = false } -reth-rpc-engine-api = { git = "https://github.com/op-rs/reth", rev = "aef8d3ef92117f91455e16969f0adf5bf7c6e9e1", default-features = false } -reth-network = { git = "https://github.com/op-rs/reth", rev = "aef8d3ef92117f91455e16969f0adf5bf7c6e9e1", default-features = false } -reth-network-api = { git = "https://github.com/op-rs/reth", rev = "aef8d3ef92117f91455e16969f0adf5bf7c6e9e1", default-features = false } -reth-network-peers = { git = "https://github.com/op-rs/reth", rev = "aef8d3ef92117f91455e16969f0adf5bf7c6e9e1", default-features = false } -reth-e2e-test-utils = { git = "https://github.com/op-rs/reth", rev = "aef8d3ef92117f91455e16969f0adf5bf7c6e9e1", default-features = false } -reth-consensus = { git = "https://github.com/op-rs/reth", rev = "aef8d3ef92117f91455e16969f0adf5bf7c6e9e1", default-features = false } -reth-node-core = { git = "https://github.com/op-rs/reth", rev = "aef8d3ef92117f91455e16969f0adf5bf7c6e9e1", default-features = false } -reth-tracing = { git = "https://github.com/op-rs/reth", rev = "aef8d3ef92117f91455e16969f0adf5bf7c6e9e1", default-features = false } -reth-rpc-layer = { git = "https://github.com/op-rs/reth", rev = "aef8d3ef92117f91455e16969f0adf5bf7c6e9e1", default-features = false } -reth-node-ethereum = { git = "https://github.com/op-rs/reth", rev = "aef8d3ef92117f91455e16969f0adf5bf7c6e9e1", default-features = false } -reth-storage-api = { git = "https://github.com/op-rs/reth", rev = "aef8d3ef92117f91455e16969f0adf5bf7c6e9e1", default-features = false } -reth-storage-errors = { git = "https://github.com/op-rs/reth", rev = "aef8d3ef92117f91455e16969f0adf5bf7c6e9e1", default-features = false } - -# reth-optimism -reth-optimism-evm = { git = "https://github.com/ethereum-optimism/optimism", rev = "96ffbb2a94f19886fe7e27c45f3310e64ccd18b3", default-features = false } -reth-optimism-node = { git = "https://github.com/ethereum-optimism/optimism", rev = "96ffbb2a94f19886fe7e27c45f3310e64ccd18b3", default-features = false } -reth-optimism-cli = { git = "https://github.com/ethereum-optimism/optimism", rev = "96ffbb2a94f19886fe7e27c45f3310e64ccd18b3", default-features = false } -reth-optimism-rpc = { git = "https://github.com/ethereum-optimism/optimism", rev = "96ffbb2a94f19886fe7e27c45f3310e64ccd18b3", default-features = false } -reth-optimism-consensus = { git = "https://github.com/ethereum-optimism/optimism", rev = "96ffbb2a94f19886fe7e27c45f3310e64ccd18b3", default-features = false } -reth-optimism-chainspec = { git = "https://github.com/ethereum-optimism/optimism", rev = "96ffbb2a94f19886fe7e27c45f3310e64ccd18b3", default-features = false } -reth-optimism-payload-builder = { git = "https://github.com/ethereum-optimism/optimism", rev = "96ffbb2a94f19886fe7e27c45f3310e64ccd18b3", default-features = false } -reth-optimism-forks = { git = "https://github.com/ethereum-optimism/optimism", rev = "96ffbb2a94f19886fe7e27c45f3310e64ccd18b3", default-features = false } -reth-optimism-primitives = { git = "https://github.com/ethereum-optimism/optimism", rev = "96ffbb2a94f19886fe7e27c45f3310e64ccd18b3", default-features = false } -reth-optimism-storage = { git = "https://github.com/ethereum-optimism/optimism", rev = "96ffbb2a94f19886fe7e27c45f3310e64ccd18b3", default-features = false } -reth-optimism-exex = { git = "https://github.com/ethereum-optimism/optimism", rev = "96ffbb2a94f19886fe7e27c45f3310e64ccd18b3", default-features = false } -reth-optimism-flashblocks = { git = "https://github.com/ethereum-optimism/optimism", rev = "96ffbb2a94f19886fe7e27c45f3310e64ccd18b3", default-features = false } -reth-optimism-trie = { git = "https://github.com/ethereum-optimism/optimism", rev = "96ffbb2a94f19886fe7e27c45f3310e64ccd18b3", default-features = false } +reth-eth-wire = { git = "https://github.com/ethereum-optimism/reth", rev = "0fbe428518594611bdd3fdd822eb5968823c8e66", default-features = false } +reth-eth-wire-types = { git = "https://github.com/ethereum-optimism/reth", rev = "0fbe428518594611bdd3fdd822eb5968823c8e66", default-features = false } +reth-stages-types = { git = "https://github.com/ethereum-optimism/reth", rev = "0fbe428518594611bdd3fdd822eb5968823c8e66", default-features = false } +reth-trie-db = { git = "https://github.com/ethereum-optimism/reth", rev = "0fbe428518594611bdd3fdd822eb5968823c8e66", default-features = false } +reth-node-builder = { git = "https://github.com/ethereum-optimism/reth", rev = "0fbe428518594611bdd3fdd822eb5968823c8e66", default-features = false } +reth-node-metrics = { git = "https://github.com/ethereum-optimism/reth", rev = "0fbe428518594611bdd3fdd822eb5968823c8e66", default-features = false } +reth-engine-local = { git = "https://github.com/ethereum-optimism/reth", rev = "0fbe428518594611bdd3fdd822eb5968823c8e66", default-features = false } +reth-engine-tree = { git = "https://github.com/ethereum-optimism/reth", rev = "0fbe428518594611bdd3fdd822eb5968823c8e66", default-features = false } +reth-node-api = { git = "https://github.com/ethereum-optimism/reth", rev = "0fbe428518594611bdd3fdd822eb5968823c8e66", default-features = false } +reth-payload-builder = { git = "https://github.com/ethereum-optimism/reth", rev = "0fbe428518594611bdd3fdd822eb5968823c8e66", default-features = false } +reth-payload-primitives = { git = "https://github.com/ethereum-optimism/reth", rev = "0fbe428518594611bdd3fdd822eb5968823c8e66", default-features = false } +reth-payload-util = { git = "https://github.com/ethereum-optimism/reth", rev = "0fbe428518594611bdd3fdd822eb5968823c8e66", default-features = false } +reth-payload-validator = { git = "https://github.com/ethereum-optimism/reth", rev = "0fbe428518594611bdd3fdd822eb5968823c8e66", default-features = false } +reth-revm = { git = "https://github.com/ethereum-optimism/reth", rev = "0fbe428518594611bdd3fdd822eb5968823c8e66", default-features = false } +reth-tasks = { git = "https://github.com/ethereum-optimism/reth", rev = "0fbe428518594611bdd3fdd822eb5968823c8e66", default-features = false } +reth-trie-common = { git = "https://github.com/ethereum-optimism/reth", rev = "0fbe428518594611bdd3fdd822eb5968823c8e66", default-features = false } +reth-chainspec = { git = "https://github.com/ethereum-optimism/reth", rev = "0fbe428518594611bdd3fdd822eb5968823c8e66", default-features = false } +reth-rpc-engine-api = { git = "https://github.com/ethereum-optimism/reth", rev = "0fbe428518594611bdd3fdd822eb5968823c8e66", default-features = false } +reth-network = { git = "https://github.com/ethereum-optimism/reth", rev = "0fbe428518594611bdd3fdd822eb5968823c8e66", default-features = false } +reth-network-api = { git = "https://github.com/ethereum-optimism/reth", rev = "0fbe428518594611bdd3fdd822eb5968823c8e66", default-features = false } +reth-network-peers = { git = "https://github.com/ethereum-optimism/reth", rev = "0fbe428518594611bdd3fdd822eb5968823c8e66", default-features = false } +reth-e2e-test-utils = { git = "https://github.com/ethereum-optimism/reth", rev = "0fbe428518594611bdd3fdd822eb5968823c8e66", default-features = false } +reth-consensus = { git = "https://github.com/ethereum-optimism/reth", rev = "0fbe428518594611bdd3fdd822eb5968823c8e66", default-features = false } +reth-node-core = { git = "https://github.com/ethereum-optimism/reth", rev = "0fbe428518594611bdd3fdd822eb5968823c8e66", default-features = false } +reth-tracing = { git = "https://github.com/ethereum-optimism/reth", rev = "0fbe428518594611bdd3fdd822eb5968823c8e66", default-features = false } +reth-rpc-layer = { git = "https://github.com/ethereum-optimism/reth", rev = "0fbe428518594611bdd3fdd822eb5968823c8e66", default-features = false } +reth-node-ethereum = { git = "https://github.com/ethereum-optimism/reth", rev = "0fbe428518594611bdd3fdd822eb5968823c8e66", default-features = false } +reth-storage-api = { git = "https://github.com/ethereum-optimism/reth", rev = "0fbe428518594611bdd3fdd822eb5968823c8e66", default-features = false } +reth-storage-errors = { git = "https://github.com/ethereum-optimism/reth", rev = "0fbe428518594611bdd3fdd822eb5968823c8e66", default-features = false } + +# op-reth v2.6.0 +reth-optimism-evm = { git = "https://github.com/ethereum-optimism/optimism", rev = "da6d3252491754837a778061db0cc47236ec13c6", default-features = false } +reth-optimism-node = { git = "https://github.com/ethereum-optimism/optimism", rev = "da6d3252491754837a778061db0cc47236ec13c6", default-features = false } +reth-optimism-cli = { git = "https://github.com/ethereum-optimism/optimism", rev = "da6d3252491754837a778061db0cc47236ec13c6", default-features = false } +reth-optimism-rpc = { git = "https://github.com/ethereum-optimism/optimism", rev = "da6d3252491754837a778061db0cc47236ec13c6", default-features = false } +reth-optimism-consensus = { git = "https://github.com/ethereum-optimism/optimism", rev = "da6d3252491754837a778061db0cc47236ec13c6", default-features = false } +reth-optimism-chainspec = { git = "https://github.com/ethereum-optimism/optimism", rev = "da6d3252491754837a778061db0cc47236ec13c6", default-features = false } +reth-optimism-payload-builder = { git = "https://github.com/ethereum-optimism/optimism", rev = "da6d3252491754837a778061db0cc47236ec13c6", default-features = false } +reth-optimism-forks = { git = "https://github.com/ethereum-optimism/optimism", rev = "da6d3252491754837a778061db0cc47236ec13c6", default-features = false } +reth-optimism-primitives = { git = "https://github.com/ethereum-optimism/optimism", rev = "da6d3252491754837a778061db0cc47236ec13c6", default-features = false } +reth-optimism-storage = { git = "https://github.com/ethereum-optimism/optimism", rev = "da6d3252491754837a778061db0cc47236ec13c6", default-features = false } +reth-optimism-exex = { git = "https://github.com/ethereum-optimism/optimism", rev = "da6d3252491754837a778061db0cc47236ec13c6", default-features = false } +reth-optimism-flashblocks = { git = "https://github.com/ethereum-optimism/optimism", rev = "da6d3252491754837a778061db0cc47236ec13c6", default-features = false } +reth-optimism-trie = { git = "https://github.com/ethereum-optimism/optimism", rev = "da6d3252491754837a778061db0cc47236ec13c6", default-features = false } # alloy op -op-alloy-consensus = { git = "https://github.com/ethereum-optimism/optimism", rev = "96ffbb2a94f19886fe7e27c45f3310e64ccd18b3", default-features = false } -op-alloy-rpc-types = { git = "https://github.com/ethereum-optimism/optimism", rev = "96ffbb2a94f19886fe7e27c45f3310e64ccd18b3", default-features = false } -op-alloy-rpc-types-engine = { git = "https://github.com/ethereum-optimism/optimism", rev = "96ffbb2a94f19886fe7e27c45f3310e64ccd18b3", default-features = false } -op-alloy-network = { git = "https://github.com/ethereum-optimism/optimism", rev = "96ffbb2a94f19886fe7e27c45f3310e64ccd18b3", default-features = false } -alloy-op-hardforks = { git = "https://github.com/ethereum-optimism/optimism", rev = "96ffbb2a94f19886fe7e27c45f3310e64ccd18b3", default-features = false } -op-alloy-provider = { git = "https://github.com/ethereum-optimism/optimism", rev = "96ffbb2a94f19886fe7e27c45f3310e64ccd18b3", default-features = false } +op-alloy-consensus = { git = "https://github.com/ethereum-optimism/optimism", rev = "da6d3252491754837a778061db0cc47236ec13c6", default-features = false } +op-alloy-rpc-types = { git = "https://github.com/ethereum-optimism/optimism", rev = "da6d3252491754837a778061db0cc47236ec13c6", default-features = false } +op-alloy-rpc-types-engine = { git = "https://github.com/ethereum-optimism/optimism", rev = "da6d3252491754837a778061db0cc47236ec13c6", default-features = false } +op-alloy-network = { git = "https://github.com/ethereum-optimism/optimism", rev = "da6d3252491754837a778061db0cc47236ec13c6", default-features = false } +alloy-op-hardforks = { git = "https://github.com/ethereum-optimism/optimism", rev = "da6d3252491754837a778061db0cc47236ec13c6", default-features = false } +op-alloy-provider = { git = "https://github.com/ethereum-optimism/optimism", rev = "da6d3252491754837a778061db0cc47236ec13c6", default-features = false } # alloy -alloy = { version = "=2.1.1" } -alloy-json-rpc = { version = "=2.1.1", default-features = false } +alloy = { version = "2.3.0" } +alloy-json-rpc = { version = "2.3.0", default-features = false } alloy-chains = { version = "0.2.33", default-features = false } -alloy-provider = { version = "=2.1.1", default-features = false } -alloy-rpc-client = { version = "=2.1.1", default-features = false } -alloy-transport-http = { version = "=2.1.1", default-features = false } -alloy-transport = { version = "=2.1.1", default-features = false } -alloy-consensus = { version = "=2.1.1", default-features = false } -alloy-network = { version = "=2.1.1", default-features = false } -alloy-primitives = { version = "1.6.0", default-features = false, features = [ +alloy-provider = { version = "2.3.0", default-features = false } +alloy-rpc-client = { version = "2.3.0", default-features = false } +alloy-transport-http = { version = "2.3.0", default-features = false } +alloy-transport = { version = "2.3.0", default-features = false } +alloy-consensus = { version = "2.3.0", default-features = false } +alloy-network = { version = "2.3.0", default-features = false } +alloy-primitives = { version = "1.6.1", default-features = false, features = [ "std", "map-foldhash", ] } -alloy-contract = { version = "=2.1.1", default-features = false } -alloy-rpc-types-eth = { version = "=2.1.1", default-features = false } -alloy-rpc-types = { version = "=2.1.1", features = [ +alloy-contract = { version = "2.3.0", default-features = false } +alloy-rpc-types-eth = { version = "2.3.0", default-features = false } +alloy-rpc-types = { version = "2.3.0", features = [ "eth", ], default-features = false } -alloy-rpc-types-engine = { version = "=2.1.1", default-features = false } +alloy-rpc-types-engine = { version = "2.3.0", default-features = false } alloy-rlp = { version = "0.3.16", default-features = false, features = [ "derive", ] } -alloy-eips = { version = "=2.1.1", default-features = false, features = [ +alloy-eips = { version = "2.3.0", default-features = false, features = [ "serde", ] } @@ -235,15 +236,15 @@ alloy-eip7928 = { version = "0.4.5", default-features = false, features = [ "rlp", ] } -alloy-genesis = { version = "=2.1.1", default-features = false } -alloy-rpc-types-debug = "=2.1.1" -alloy-signer = { version = "=2.1.1", default-features = false } -alloy-signer-aws = { version = "=2.1.1", default-features = false } -alloy-signer-local = { version = "=2.1.1", default-features = false, features = [ +alloy-genesis = { version = "2.3.0", default-features = false } +alloy-rpc-types-debug = "2.3.0" +alloy-signer = { version = "2.3.0", default-features = false } +alloy-signer-aws = { version = "2.3.0", default-features = false } +alloy-signer-local = { version = "2.3.0", default-features = false, features = [ "mnemonic", ] } -alloy-sol-types = "1.6.0" -alloy-serde = { version = "=2.1.1", default-features = false } +alloy-sol-types = "1.6.1" +alloy-serde = { version = "2.3.0", default-features = false } alloy-hardforks = { version = "0.4.7", default-features = false } alloy-trie = { version = "0.9.4", default-features = false, features = [ "ethereum", @@ -252,40 +253,49 @@ alloy-trie = { version = "0.9.4", default-features = false, features = [ # aws aws-config = { version = "1", default-features = false, features = [ "rt-tokio", - "rustls", + "default-https-client", + "credentials-process", + "sso", ] } +aws-credential-types = { version = "1", default-features = false } aws-sdk-kms = { version = "1", default-features = false, features = [ "rt-tokio", - "rustls", + "default-https-client", +] } +aws-sdk-s3 = { version = "1", default-features = false, features = [ + "rt-tokio", + "default-https-client", + "http-1x", ] } # revm -revm = { version = "41.0.0", default-features = false } -revm-precompile = { version = "41.0.0", default-features = false } -revm-bytecode = { version = "41.0.0", default-features = false } -revm-database = { version = "41.0.0", default-features = false } -revm-state = { version = "41.0.0", default-features = false } -revm-primitives = { version = "41.0.0", default-features = false } -revm-interpreter = { version = "41.0.0", default-features = false } -revm-database-interface = { version = "41.0.0", default-features = false } -op-revm = { git = "https://github.com/ethereum-optimism/optimism", rev = "96ffbb2a94f19886fe7e27c45f3310e64ccd18b3", default-features = false } -revm-inspectors = "0.41.0" - -alloy-op-evm = { git = "https://github.com/ethereum-optimism/optimism", rev = "96ffbb2a94f19886fe7e27c45f3310e64ccd18b3", default-features = false } -alloy-evm = { version = "0.37.0", default-features = false } +revm = { version = "42.0.1", default-features = false } +revm-precompile = { version = "42.0.0", default-features = false } +revm-bytecode = { version = "42.0.0", default-features = false } +revm-database = { version = "42.0.0", default-features = false } +revm-state = { version = "42.0.0", default-features = false } +revm-primitives = { version = "42.0.0", default-features = false } +revm-interpreter = { version = "42.0.0", default-features = false } +revm-database-interface = { version = "42.0.0", default-features = false } +op-revm = { git = "https://github.com/ethereum-optimism/optimism", rev = "da6d3252491754837a778061db0cc47236ec13c6", default-features = false } +revm-inspectors = "0.42.0" + +alloy-op-evm = { git = "https://github.com/ethereum-optimism/optimism", rev = "da6d3252491754837a778061db0cc47236ec13c6", default-features = false } +alloy-evm = { version = "0.38.0", default-features = false } # kona -kona-derive = { git = "https://github.com/ethereum-optimism/optimism", rev = "96ffbb2a94f19886fe7e27c45f3310e64ccd18b3", default-features = false } -kona-driver = { git = "https://github.com/ethereum-optimism/optimism", rev = "96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" } -kona-executor = { git = "https://github.com/ethereum-optimism/optimism", rev = "96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" } -kona-genesis = { git = "https://github.com/ethereum-optimism/optimism", rev = "96ffbb2a94f19886fe7e27c45f3310e64ccd18b3", default-features = false } -kona-preimage = { git = "https://github.com/ethereum-optimism/optimism", rev = "96ffbb2a94f19886fe7e27c45f3310e64ccd18b3", features = [ +kona-derive = { git = "https://github.com/ethereum-optimism/optimism", rev = "da6d3252491754837a778061db0cc47236ec13c6", default-features = false } +kona-driver = { git = "https://github.com/ethereum-optimism/optimism", rev = "da6d3252491754837a778061db0cc47236ec13c6" } +kona-executor = { git = "https://github.com/ethereum-optimism/optimism", rev = "da6d3252491754837a778061db0cc47236ec13c6" } +kona-genesis = { git = "https://github.com/ethereum-optimism/optimism", rev = "da6d3252491754837a778061db0cc47236ec13c6", default-features = false } +kona-preimage = { git = "https://github.com/ethereum-optimism/optimism", rev = "da6d3252491754837a778061db0cc47236ec13c6", features = [ "rkyv", "serde", ] } -kona-host = { git = "https://github.com/ethereum-optimism/optimism", rev = "96ffbb2a94f19886fe7e27c45f3310e64ccd18b3", default-features = false } -kona-proof = { git = "https://github.com/ethereum-optimism/optimism", rev = "96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" } -kona-protocol = { git = "https://github.com/ethereum-optimism/optimism", rev = "96ffbb2a94f19886fe7e27c45f3310e64ccd18b3", default-features = false } +kona-host = { git = "https://github.com/ethereum-optimism/optimism", rev = "da6d3252491754837a778061db0cc47236ec13c6", default-features = false } +kona-proof = { git = "https://github.com/ethereum-optimism/optimism", rev = "da6d3252491754837a778061db0cc47236ec13c6" } +kona-protocol = { git = "https://github.com/ethereum-optimism/optimism", rev = "da6d3252491754837a778061db0cc47236ec13c6", default-features = false } +kona-sp1-host-utils = { git = "https://github.com/ethereum-optimism/optimism", rev = "da6d3252491754837a778061db0cc47236ec13c6", default-features = false } # rpc jsonrpsee = { version = "0.26.0", features = ["server", "client", "macros"] } @@ -311,8 +321,8 @@ thiserror = "2" strum = { version = "0.28", features = ["derive"] } cfg-if = "1" bytemuck = "1" -semaphore-rs = { version = "0.5", features = ["depth_30"] } -semaphore-rs-proof = "0.5" +semaphore-rs = { version = "0.6", features = ["depth_30"] } +semaphore-rs-proof = "0.6" clap = { version = "4", features = ["derive", "env"] } eyre = { version = "0.6", package = "color-eyre" } serde = { version = "1", features = ["derive"] } @@ -368,6 +378,7 @@ pin-project = "1.1.13" uuid = { version = "1", features = ["serde", "v4"] } vergen = "10.0.1" vergen-git2 = "10.0.1" +backoff = { version = "0.4", features = ["tokio"] } # Test testcontainers = "0.27" @@ -381,8 +392,8 @@ proptest = "1.9.0" # in the StreamingFast forks (streamingfast/reth, streamingfast/optimism), so they are # pulled straight from git rather than via [patch]. firehose-tracer = "5.5.0" -reth-firehose = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-optimism-firehose = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.4.3-fh3.1-3" } +reth-firehose = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-optimism-firehose = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.6.0-fh3.1" } # The reth-chain-state ExEx debug_assert floods debug-build logs during live engine-API # execution; compiled out in release. Mirrors the same override in the SF reth/optimism forks. @@ -391,172 +402,173 @@ debug-assertions = false [patch.crates-io] # SF fork of alloy-evm that routes system calls (EIP-4788, EIP-2935, etc.) through the -# Inspector, so Firehose tracing observes them. Matches the patch in streamingfast/reth -# op-rs-aef8d3e-fh. See https://github.com/alloy-rs/evm/pull/323 for the upstream PR (still open). -alloy-evm = { git = "https://github.com/streamingfast/evm.git", tag = "v0.37.0-sf" } +# Inspector, so Firehose tracing observes them. Matches the patch in streamingfast/reth and +# streamingfast/optimism. See https://github.com/alloy-rs/evm/pull/323 for the upstream PR. +alloy-evm = { git = "https://github.com/streamingfast/evm.git", tag = "v0.38.0-sf" } # Redirect the whole reth dependency graph to the StreamingFast Firehose-instrumented fork. -# Upstream world-chain pins reth from op-rs/reth (the External OP Labs shallow fork, -# rev aef8d3ef = reth v2.4.1-ish + paradigmxyz/reth#26431), not paradigmxyz/reth, so the -# patch key is the op-rs URL. Our tag world-chain-v2.4.3-fh3.1-2 is built on that same rev. -[patch."https://github.com/op-rs/reth"] -reth-basic-payload-builder = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-chain-state = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-chainspec = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-cli = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-cli-commands = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-cli-runner = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-cli-util = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-config = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-consensus = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-consensus-common = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-consensus-debug-client = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-db = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-db-api = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-db-common = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-db-models = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-discv4 = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-discv5 = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-dns-discovery = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-downloaders = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-e2e-test-utils = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-ecies = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-engine-local = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-engine-primitives = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-engine-tree = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-engine-util = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-era = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-era-downloader = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-era-utils = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-errors = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-eth-wire = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-eth-wire-types = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-ethereum = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-ethereum-consensus = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-ethereum-engine-primitives = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-ethereum-forks = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-ethereum-payload-builder = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-ethereum-primitives = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-etl = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-evm = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-evm-ethereum = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-execution-cache = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-execution-errors = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-execution-types = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-exex = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-exex-types = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-fs-util = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-invalid-block-hooks = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-ipc = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-libmdbx = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-mdbx-sys = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-metrics = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-net-banlist = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-net-nat = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-network = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-network-api = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-network-p2p = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-network-peers = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-network-types = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-nippy-jar = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-node-api = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-node-builder = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-node-core = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-node-ethereum = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-node-ethstats = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-node-events = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-node-metrics = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-node-types = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-payload-builder = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-payload-builder-primitives = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-payload-primitives = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-payload-util = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-payload-validator = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-provider = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-prune = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-prune-types = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-revm = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-rpc = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-rpc-api = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-rpc-builder = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-rpc-convert = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-rpc-engine-api = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-rpc-eth-api = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-rpc-eth-types = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-rpc-layer = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-rpc-server-types = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-stages = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-stages-api = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-stages-types = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-static-file = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-static-file-types = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-storage-api = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-storage-errors = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-tasks = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-testing-utils = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-tokio-util = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-tracing = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-tracing-otlp = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-transaction-pool = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-trie = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-trie-common = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-trie-db = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-trie-parallel = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-trie-sparse = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.4.3-fh3.1-3" } +# Upstream world-chain pins reth from ethereum-optimism/reth (rev 0fbe4285 = reth v2.5.2 plus +# two commits), so the patch key is that URL. Our tag world-chain-v2.6.0-fh3.1 is built on that +# same rev. +[patch."https://github.com/ethereum-optimism/reth"] +reth-basic-payload-builder = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-chain-state = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-chainspec = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-cli = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-cli-commands = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-cli-runner = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-cli-util = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-config = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-consensus = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-consensus-common = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-consensus-debug-client = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-db = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-db-api = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-db-common = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-db-models = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-discv4 = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-discv5 = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-dns-discovery = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-downloaders = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-e2e-test-utils = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-ecies = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-engine-local = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-engine-primitives = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-engine-tree = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-engine-util = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-era = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-era-downloader = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-era-utils = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-errors = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-eth-wire = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-eth-wire-types = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-ethereum = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-ethereum-consensus = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-ethereum-engine-primitives = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-ethereum-forks = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-ethereum-payload-builder = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-ethereum-primitives = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-etl = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-evm = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-evm-ethereum = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-execution-cache = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-execution-errors = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-execution-types = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-exex = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-exex-types = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-fs-util = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-invalid-block-hooks = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-ipc = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-libmdbx = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-mdbx-sys = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-metrics = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-net-banlist = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-net-nat = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-network = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-network-api = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-network-p2p = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-network-peers = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-network-types = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-nippy-jar = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-node-api = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-node-builder = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-node-core = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-node-ethereum = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-node-ethstats = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-node-events = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-node-metrics = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-node-types = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-payload-builder = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-payload-builder-primitives = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-payload-primitives = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-payload-util = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-payload-validator = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-provider = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-prune = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-prune-types = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-revm = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-rpc = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-rpc-api = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-rpc-builder = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-rpc-convert = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-rpc-engine-api = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-rpc-eth-api = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-rpc-eth-types = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-rpc-layer = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-rpc-server-types = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-stages = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-stages-api = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-stages-types = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-static-file = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-static-file-types = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-storage-api = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-storage-errors = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-tasks = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-testing-utils = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-tokio-util = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-tracing = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-tracing-otlp = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-transaction-pool = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-trie = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-trie-common = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-trie-db = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-trie-parallel = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-trie-sparse = { git = "https://github.com/streamingfast/reth.git", tag = "world-chain-v2.6.0-fh3.1" } # Redirect the optimism-monorepo crates to the StreamingFast Firehose-instrumented fork -# (streamingfast/optimism, based on upstream optimism rev 96ffbb2a — the untagged develop -# commit world-chain pins above, which carries the superchain-registry update for the World -# Chain Karst activations). +# (streamingfast/optimism, based on upstream optimism tag op-reth/v2.6.0 = rev da6d3252, the rev +# world-chain pins above). # # Both forks follow their `release/world-chain-2.x` branch, which carries exactly the upstream # revs world-chain pins; `release/op-reth-2.x` and `release/optimism-2.x` follow op-reth releases. # -# The reth tag below must stay identical to the one this optimism tag pins in its own -# rust/Cargo.toml. They resolve to the same source id only when the tag strings match; if they +# The reth ref below must stay identical to the one this optimism ref pins in its own +# rust/Cargo.toml. They resolve to the same source id only when the ref strings match; if they # drift, cargo resolves two separate copies of every reth crate and the executor pipeline # silently links against the untraced one. [patch."https://github.com/ethereum-optimism/optimism"] -alloy-op-evm = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.4.3-fh3.1-3" } -alloy-op-hardforks = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.4.3-fh3.1-3" } -kona-cli = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.4.3-fh3.1-3" } -kona-client = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.4.3-fh3.1-3" } -kona-derive = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.4.3-fh3.1-3" } -kona-driver = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.4.3-fh3.1-3" } -kona-executor = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.4.3-fh3.1-3" } -kona-genesis = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.4.3-fh3.1-3" } -kona-hardforks = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.4.3-fh3.1-3" } -kona-host = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.4.3-fh3.1-3" } -kona-interop = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.4.3-fh3.1-3" } -kona-macros = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.4.3-fh3.1-3" } -kona-mpt = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.4.3-fh3.1-3" } -kona-preimage = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.4.3-fh3.1-3" } -kona-proof = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.4.3-fh3.1-3" } -kona-proof-interop = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.4.3-fh3.1-3" } -kona-protocol = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.4.3-fh3.1-3" } -kona-providers-alloy = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.4.3-fh3.1-3" } -kona-registry = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.4.3-fh3.1-3" } -kona-std-fpvm = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.4.3-fh3.1-3" } -kona-std-fpvm-proc = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.4.3-fh3.1-3" } -op-alloy = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.4.3-fh3.1-3" } -op-alloy-consensus = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.4.3-fh3.1-3" } -op-alloy-network = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.4.3-fh3.1-3" } -op-alloy-provider = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.4.3-fh3.1-3" } -op-alloy-rpc-jsonrpsee = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.4.3-fh3.1-3" } -op-alloy-rpc-types = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.4.3-fh3.1-3" } -op-alloy-rpc-types-engine = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.4.3-fh3.1-3" } -op-revm = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-optimism-chainspec = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-optimism-consensus = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-optimism-evm = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-optimism-exex = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-optimism-flashblocks = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-optimism-forks = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-optimism-node = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-optimism-payload-builder = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-optimism-post-exec-replay = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-optimism-primitives = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-optimism-rpc = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-optimism-storage = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-optimism-trie = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.4.3-fh3.1-3" } -reth-optimism-txpool = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.4.3-fh3.1-3" } +alloy-op-evm = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.6.0-fh3.1" } +alloy-op-hardforks = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.6.0-fh3.1" } +kona-cli = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.6.0-fh3.1" } +kona-client = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.6.0-fh3.1" } +kona-derive = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.6.0-fh3.1" } +kona-driver = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.6.0-fh3.1" } +kona-executor = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.6.0-fh3.1" } +kona-genesis = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.6.0-fh3.1" } +kona-hardforks = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.6.0-fh3.1" } +kona-host = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.6.0-fh3.1" } +kona-interop = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.6.0-fh3.1" } +kona-macros = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.6.0-fh3.1" } +kona-mpt = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.6.0-fh3.1" } +kona-preimage = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.6.0-fh3.1" } +kona-proof = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.6.0-fh3.1" } +kona-proof-interop = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.6.0-fh3.1" } +kona-protocol = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.6.0-fh3.1" } +kona-providers-alloy = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.6.0-fh3.1" } +kona-registry = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.6.0-fh3.1" } +kona-sp1-client-utils = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.6.0-fh3.1" } +kona-sp1-host-utils = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.6.0-fh3.1" } +kona-std-fpvm = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.6.0-fh3.1" } +kona-std-fpvm-proc = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.6.0-fh3.1" } +op-alloy = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.6.0-fh3.1" } +op-alloy-consensus = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.6.0-fh3.1" } +op-alloy-network = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.6.0-fh3.1" } +op-alloy-provider = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.6.0-fh3.1" } +op-alloy-rpc-jsonrpsee = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.6.0-fh3.1" } +op-alloy-rpc-types = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.6.0-fh3.1" } +op-alloy-rpc-types-engine = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.6.0-fh3.1" } +op-revm = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-optimism-chainspec = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-optimism-consensus = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-optimism-evm = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-optimism-exex = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-optimism-flashblocks = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-optimism-forks = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-optimism-node = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-optimism-payload-builder = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-optimism-post-exec-replay = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-optimism-primitives = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-optimism-rpc = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-optimism-storage = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-optimism-trie = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.6.0-fh3.1" } +reth-optimism-txpool = { git = "https://github.com/streamingfast/optimism.git", tag = "world-chain-v2.6.0-fh3.1" } diff --git a/Dockerfile b/Dockerfile index 588c51805..b405cf303 100644 --- a/Dockerfile +++ b/Dockerfile @@ -67,10 +67,10 @@ RUN --mount=type=cache,target=/usr/local/cargo/registry \ cargo build --locked --profile ${PROFILE} --features ${FEATURES} --bin ${WORLD_CHAIN_BUILDER_BIN} # Deployments depend on sh wget and awscli v2 -FROM public.ecr.aws/docker/library/debian:bookworm-slim +FROM public.ecr.aws/docker/library/debian:bookworm-slim AS runtime WORKDIR /app -# Install wget in the final image +# Install runtime tools and require Debian's eMudhra distrust update. RUN apt-get update && \ apt-get install -y --no-install-recommends \ ca-certificates \ @@ -81,6 +81,7 @@ RUN apt-get update && \ jq \ netcat-traditional \ tzdata && \ + dpkg --compare-versions "$(dpkg-query -W -f='${Version}' ca-certificates)" ge '20250419~deb12u2' && \ apt-get clean && \ rm -rf /var/lib/apt/lists/* diff --git a/Dockerfile.e2e-withdrawal b/Dockerfile.e2e-withdrawal new file mode 100644 index 000000000..6f160d7c4 --- /dev/null +++ b/Dockerfile.e2e-withdrawal @@ -0,0 +1,52 @@ +# syntax=docker/dockerfile:1.10 +# Build from the repo root: +# docker build -f Dockerfile.e2e-withdrawal -t e2e-withdrawal . +FROM public.ecr.aws/docker/library/rust:1.98.1-bookworm AS base + +# cmake is required to build aws-lc-sys (TLS via rustls / AWS SDK). +RUN apt-get update \ + && apt-get install -y --no-install-recommends cmake \ + && rm -rf /var/lib/apt/lists/* + +RUN --mount=type=cache,target=/usr/local/cargo/registry \ + --mount=type=cache,target=/usr/local/cargo/git \ + cargo install --locked cargo-chef --version ^0.1 + +FROM base AS planner +WORKDIR /app + +COPY . . + +RUN cargo chef prepare --recipe-path recipe.json + +FROM base AS builder +WORKDIR /app + +COPY --from=planner /app/recipe.json recipe.json + +# Measured crates are excluded from the root workspace; cook needs their sources +# to resolve workspace path dependencies referenced by the chef recipe. +COPY proofs/measured proofs/measured + +RUN --mount=type=cache,target=/usr/local/cargo/registry \ + --mount=type=cache,target=/usr/local/cargo/git \ + cargo chef cook --locked --release -p e2e-withdrawal --bin e2e-withdrawal --recipe-path recipe.json + +COPY . . + +RUN --mount=type=cache,target=/usr/local/cargo/registry \ + --mount=type=cache,target=/usr/local/cargo/git \ + cargo build --locked --release -p e2e-withdrawal --bin e2e-withdrawal + +FROM public.ecr.aws/docker/library/debian:bookworm-slim + +# Require Debian's eMudhra distrust update for the system CA bundle. +RUN apt-get update && \ + apt-get install -y --no-install-recommends ca-certificates && \ + dpkg --compare-versions "$(dpkg-query -W -f='${Version}' ca-certificates)" ge '20250419~deb12u2' && \ + apt-get clean && \ + rm -rf /var/lib/apt/lists/* + +COPY --from=builder /app/target/release/e2e-withdrawal /usr/local/bin/e2e-withdrawal + +ENTRYPOINT ["/usr/local/bin/e2e-withdrawal"] diff --git a/Dockerfile.prover b/Dockerfile.prover index 40cb80000..7c8c1955f 100644 --- a/Dockerfile.prover +++ b/Dockerfile.prover @@ -29,7 +29,7 @@ ENV CARGO_HOME=/usr/local/cargo \ # Canonical SP1 guest builder. This is the same linux/amd64 image and `/root/program` # workspace layout used by sp1-build's reproducible Docker mode. The digest is the # governance boundary: changing it intentionally rotates the ELF hashes and vkeys. -FROM --platform=${SP1_GUEST_PLATFORM} ghcr.io/succinctlabs/sp1:v6.3.1@sha256:7c1c8201de6f63e3f1fb9075bd9a67a4c5fc8c2d546d11a5ff71587bb51e6eb3 AS sp1-guests +FROM --platform=${SP1_GUEST_PLATFORM} ghcr.io/succinctlabs/sp1:v6.8.1@sha256:e672d7160039916f40a6a4c2ea4cb0c8cd3dab120fdb24d08560d386ad8f59c2 AS sp1-guests WORKDIR /root/program COPY . . @@ -173,10 +173,12 @@ RUN /app/bin/${PROVER_BIN} vkeys \ FROM public.ecr.aws/docker/library/debian:bookworm-slim AS runtime WORKDIR /app +# Require Debian's eMudhra distrust update for the system CA bundle. RUN apt-get update && \ apt-get install -y --no-install-recommends \ ca-certificates \ tzdata && \ + dpkg --compare-versions "$(dpkg-query -W -f='${Version}' ca-certificates)" ge '20250419~deb12u2' && \ apt-get clean && \ rm -rf /var/lib/apt/lists/* diff --git a/Dockerfile.sf b/Dockerfile.sf index d92277446..4e09215bb 100644 --- a/Dockerfile.sf +++ b/Dockerfile.sf @@ -3,7 +3,7 @@ # (fireeth) image, mirroring streamingfast/base's Dockerfile.sf. ARG FIREHOSE_ETHEREUM="latest" # Selects the base image only. Since upstream v2.4.2 the workspace ships a -# rust-toolchain.toml pinning nightly-2026-07-01 (crates/evm needs +# rust-toolchain.toml pinning nightly-2026-10-10 (crates/evm needs # #![feature(min_specialization)]), which rustup installs on the first cargo # invocation below — that nightly, not this version, is what compiles the node. ARG RUST_VERSION=1.95.0 diff --git a/bin/world-chain/Cargo.toml b/bin/world-chain/Cargo.toml index 4fdc2ff5d..d60f62f19 100644 --- a/bin/world-chain/Cargo.toml +++ b/bin/world-chain/Cargo.toml @@ -18,7 +18,6 @@ firehose-tracer.workspace = true # world-chain world-chain-cli.workspace = true world-chain-chainspec.workspace = true -reth-chainspec.workspace = true world-chain-evm.workspace = true world-chain-node.workspace = true world-chain-rpc.workspace = true diff --git a/bin/world-chain/src/main.rs b/bin/world-chain/src/main.rs index 063154517..ef41d565d 100644 --- a/bin/world-chain/src/main.rs +++ b/bin/world-chain/src/main.rs @@ -1,6 +1,5 @@ use clap::Parser; use eyre::config::HookBuilder; -use reth_chainspec::EthChainSpec; use reth_optimism_consensus::OpBeaconConsensus; use reth_tracing::tracing::info; use std::sync::Arc; @@ -50,10 +49,6 @@ fn main() { info!(target: "reth::cli", "Launching node"); let config: WorldChainNodeConfig = args.into_config(builder.config_mut())?; - // Record the chain config on the Firehose tracer (emits `FIRE INIT`) before the - // node launches, so it happens ahead of the first engine-API payload. - reth_optimism_firehose::init_blockchain(builder.config().chain.chain_id()); - info!(target: "reth::cli", "Starting in Flashblocks mode"); proof_history::launch_node(builder, config).await }, diff --git a/crates/builder/src/payload_builder.rs b/crates/builder/src/payload_builder.rs index 52ac78317..069376b02 100644 --- a/crates/builder/src/payload_builder.rs +++ b/crates/builder/src/payload_builder.rs @@ -634,7 +634,6 @@ where execution_output: Arc::new(execution_outcome.clone()), hashed_state: Arc::new(hashed_state), trie_updates: Arc::new(trie_updates), - changed_paths: None, }; let payload = OpBuiltPayload::new( diff --git a/crates/chainspec/src/spec.rs b/crates/chainspec/src/spec.rs index 5fb91c1fd..bb5371425 100644 --- a/crates/chainspec/src/spec.rs +++ b/crates/chainspec/src/spec.rs @@ -6,7 +6,7 @@ use alloy_eips::eip7840::BlobParams; use alloy_genesis::Genesis; use alloy_hardforks::Hardfork; use alloy_primitives::{B256, U256}; -use derive_more::{Constructor, Deref, Into}; +use derive_more::{Deref, Into}; use reth_chainspec::{ BaseFeeParams, BaseFeeParamsKind, ChainHardforks, ChainSpec, DepositContract, DisplayHardforks, EthChainSpec, EthereumHardfork, EthereumHardforks, ForkCondition, ForkFilter, ForkId, @@ -38,13 +38,19 @@ pub const KARST_UPGRADE_TIMESTAMP_MAINNET: u64 = 1_789_992_000; /// /// This wraps reth's generic [`ChainSpec`] the same way the OP stack spec does, while using World /// Chain hardfork names as the canonical post-Karst schedule. -#[derive(Debug, Clone, Deref, Into, Constructor, PartialEq, Eq)] +#[derive(Debug, Clone, Deref, Into, PartialEq, Eq)] pub struct WorldChainSpec { /// Inner reth chain spec. pub inner: ChainSpec, } impl WorldChainSpec { + /// Wraps the given reth chain spec. + #[inline] + pub const fn new(inner: ChainSpec) -> Self { + Self { inner } + } + /// Converts the given [`Genesis`] into a [`WorldChainSpec`]. pub fn from_genesis(genesis: Genesis) -> Self { genesis.into() diff --git a/crates/devnet/Cargo.toml b/crates/devnet/Cargo.toml index ddba2132d..0400449c9 100644 --- a/crates/devnet/Cargo.toml +++ b/crates/devnet/Cargo.toml @@ -27,6 +27,7 @@ world-chain-defender.workspace = true world-chain-rpc.workspace = true world-chain-test-utils.workspace = true +alloy-contract.workspace = true alloy-provider.workspace = true alloy-eips.workspace = true alloy-genesis.workspace = true diff --git a/crates/devnet/src/full_stack.rs b/crates/devnet/src/full_stack.rs index 828601d64..06869e981 100644 --- a/crates/devnet/src/full_stack.rs +++ b/crates/devnet/src/full_stack.rs @@ -11,10 +11,10 @@ use std::{ use alloy_eips::{BlockNumberOrTag, eip1559::BaseFeeParams}; use alloy_genesis::Genesis; use alloy_network::EthereumWallet; -use alloy_primitives::{Address, B64, B256, hex}; +use alloy_primitives::{Address, B64, B256, U256, hex}; use alloy_provider::{Provider, ProviderBuilder}; use alloy_signer_local::PrivateKeySigner; -use alloy_sol_types::SolValue; +use alloy_sol_types::{SolValue, sol}; use async_trait::async_trait; use base64::prelude::{BASE64_STANDARD, Engine}; use eyre::eyre::{Context, Result, bail, eyre}; @@ -57,7 +57,8 @@ use world_chain_proof_core::{ }; use world_chain_proof_kona_host::online::OnlineHostConfig; use world_chain_proof_protocol::{ - AlloyProofGameProvider, OptimismConsensusClient, PROOF_SYSTEM_VERSION, PROOF_THRESHOLD, + AlloyProofGameProvider, IERC20StakingVault, OptimismConsensusClient, PROOF_SYSTEM_VERSION, + PROOF_THRESHOLD, }; use world_chain_proof_sp1_host::{ Sp1ProverKind, WorldSuccinctProver, @@ -75,7 +76,7 @@ use world_chain_proposer::{ }; use world_chain_prover_service::{ ProofBackend, ProofData, ProverService, ProverServiceConfig, RpcProverServiceClient, - start_rpc_server, + run_status_poller, start_rpc_server, }; use world_chain_test_utils::DEV_CHAIN_ID; @@ -121,12 +122,13 @@ const WORLD_PROPOSER_POLL_INTERVAL: Duration = Duration::from_secs(2); const WORLD_CHALLENGER_POLL_INTERVAL: Duration = Duration::from_secs(2); /// Delay between World Chain proof-system defender scans. const WORLD_DEFENDER_POLL_INTERVAL: Duration = Duration::from_secs(2); -/// Balance, in wei, allocated to the World Chain challenger account in the L1 -/// genesis so it can cover the challenger bond plus gas. (100 ether) +/// Balance, in wei, allocated to the World Chain challenger account in the L1 genesis for gas. const WORLD_CHALLENGER_GENESIS_BALANCE_WEI: &str = "0x56bc75e2d63100000"; /// Balance, in wei, allocated to the World Chain defender account in the L1 /// genesis so it can submit proof-lane transactions. (100 ether) const WORLD_DEFENDER_GENESIS_BALANCE_WEI: &str = "0x56bc75e2d63100000"; +/// Mock bond tokens deposited for each bond-paying proof-system service (100 tokens). +const WORLD_PROOF_SERVICE_BOND_TOKEN_BALANCE: u128 = 100_000_000_000_000_000_000; const DEVNET_PRIVATE_KEY: &str = "0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d"; @@ -275,16 +277,17 @@ struct ContainerService { _container: ContainerAsync, } -/// Addresses of the proof-lane test doubles written by `DeployProofMocks.s.sol`. +/// Addresses of the proof-system test doubles written by `DeployProofMocks.s.sol`. /// /// `DeployProofSystem.s.sol` deliberately refuses to deploy verifiers of its own, so the -/// devnet deploys these explicitly and passes them in. They accept every proof — devnet only. +/// devnet deploys these explicitly and passes them in. The verifier mocks accept every proof. #[derive(Clone, Debug, Deserialize)] #[serde(rename_all = "camelCase")] struct WorldProofMocksDeployment { validity_proof_verifier: String, tee_verifier: String, security_council: String, + bond_token: String, } #[derive(Clone, Debug, Deserialize)] @@ -299,6 +302,18 @@ struct WorldProofSystemDeployment { l2_chain_id: u64, proof_system_version: u64, block_interval: u64, + game_implementation: String, + bond_token: String, + erc20_staking_vault: String, +} + +sol! { + #[sol(rpc)] + interface IMockBondToken { + function mint(address recipient, uint256 amount) external; + function approve(address spender, uint256 amount) external returns (bool); + function allowance(address owner, address spender) external view returns (uint256); + } } /// In-process World Chain proof-system proposer task. Aborted on devnet drop. @@ -341,6 +356,7 @@ impl Drop for DefenderTask { #[derive(Debug)] struct ProverServiceTask { handle: ServerHandle, + status_poller: JoinHandle<()>, _postgres: Option>, _postgres_data_dir: Option, } @@ -348,6 +364,7 @@ struct ProverServiceTask { impl Drop for ProverServiceTask { fn drop(&mut self) { let _ = self.handle.stop(); + self.status_poller.abort(); } } @@ -490,15 +507,15 @@ impl FullStackWorldDevnet { ); let proof_system = if config.world_contracts.proof_system { - Some( - deploy_world_proof_system( - &l1_public_rpc, - &artifacts.rollup_path, - &artifacts.l1_addresses, - &workdir_path, - ) - .await?, + let deployment = deploy_world_proof_system( + &l1_public_rpc, + &artifacts.rollup_path, + &artifacts.l1_addresses, + &workdir_path, ) + .await?; + fund_world_proof_bond_accounts(&l1_public_rpc, &deployment).await?; + Some(deployment) } else { None }; @@ -678,7 +695,7 @@ impl FullStackWorldDevnet { // Proof workers and the defender share one prover-service. let (prover_service, prover_service_url) = if proof_services.is_some() { - let (service, url) = start_prover_service().await?; + let (service, url) = start_prover_service(&l1_public_rpc).await?; (Some(service), Some(url)) } else { (None, None) @@ -854,12 +871,77 @@ impl FullStackWorldDevnet { &self.sequencers[0].rpc_url } + pub fn l2_op_node_rpc_url(&self) -> &str { + &self._op_nodes[0].rpc_url + } + /// JSON-RPC URL of the in-process defender prover-service, when enabled. #[allow(dead_code)] pub fn prover_service_url(&self) -> Option<&str> { self.prover_service_url.as_deref() } + /// Aborts the in-process defender and its TEE/SP1 workers so no proof lanes can land. + /// + /// Idempotent. Leaves the prover-service RPC up (harmless without requesters) so tests that + /// assert an unproven game's timeout outcome can keep the rest of the stack running. + pub fn stop_defender(&mut self) { + self._world_defender.take(); + self._nitro_worker.take(); + self._sp1_worker.take(); + } + + /// Re-spawns the in-process defender and its TEE worker after [`Self::stop_defender`]. + /// + /// Idempotent when the defender is already running. Reuses the still-live prover-service and + /// the deployed proof-system addresses. Also restarts the SP1 worker when + /// `DEVNET_SP1_WORKER_PROVER` is set, using the rollup config under the stack tempdir. + pub async fn start_defender(&mut self) -> Result<()> { + if self._world_defender.is_some() { + return Ok(()); + } + + let deployment = self + ._proof_system + .clone() + .ok_or_else(|| eyre!("cannot start defender: proof system was not deployed"))?; + let prover_service_url = self + .prover_service_url + .clone() + .ok_or_else(|| eyre!("cannot start defender: prover-service is not running"))?; + let l1_rpc = self.l1_rpc_url().to_string(); + let output_root_rpc = self.l2_op_node_rpc_url().to_string(); + let l2_rpc = self.l2_rpc_url().to_string(); + let rollup_path = self._tempdir.path().join("rollup.json"); + let restart_nitro = self._nitro_worker.is_none(); + let restart_sp1 = self._sp1_worker.is_none(); + + if restart_nitro { + self._nitro_worker = Some(start_devnet_nitro_worker(&prover_service_url)?); + } + + self._world_defender = Some( + start_world_chain_defender(&l1_rpc, &output_root_rpc, &prover_service_url, &deployment) + .await?, + ); + + if restart_sp1 && let Some(kind) = sp1_worker_prover_kind()? { + self._sp1_worker = Some( + start_sp1_worker( + &l1_rpc, + &l2_rpc, + &prover_service_url, + &rollup_path, + &deployment, + kind, + ) + .await?, + ); + } + + Ok(()) + } + pub fn sequencer_rpc_url(&self) -> &str { &self.sequencers[0].rpc_url } @@ -1067,7 +1149,7 @@ l2ContractsLocator = "{}" ) } -/// Deploys the proof-lane test doubles (`DeployProofMocks.s.sol`) for the local devnet and +/// Deploys the proof-system test doubles (`DeployProofMocks.s.sol`) for the local devnet and /// returns their addresses for `DeployProofSystem` to consume. /// /// The devnet has no SP1 gateway, no Nitro enclave and no council multisig, so the lanes are @@ -1096,6 +1178,7 @@ async fn deploy_world_proof_mocks( .arg("script") .arg("scripts/devnet/DeployProofMocks.s.sol:DeployProofMocks") .arg("--broadcast") + .arg("--skip-simulation") .arg("--rpc-url") .arg(l1_rpc_url) .arg("--private-key") @@ -1146,7 +1229,8 @@ async fn deploy_world_proof_mocks( validity = %mocks.validity_proof_verifier, tee = %mocks.tee_verifier, council = %mocks.security_council, - "World Chain proof-lane test doubles deployed (accept any proof — devnet only)" + bond_token = %mocks.bond_token, + "World Chain proof-system test doubles deployed (devnet only)" ); Ok(mocks) @@ -1214,6 +1298,7 @@ async fn deploy_world_proof_system( .arg("script") .arg("scripts/devnet/DeployProofSystem.s.sol:DeployProofSystem") .arg("--broadcast") + .arg("--skip-simulation") .arg("--rpc-url") .arg(l1_rpc_url) .arg("--private-key") @@ -1238,6 +1323,7 @@ async fn deploy_world_proof_system( .env("VALIDITY_PROOF_VERIFIER", &mocks.validity_proof_verifier) .env("TEE_VERIFIER", &mocks.tee_verifier) .env("SECURITY_COUNCIL_VERIFIER", &mocks.security_council) + .env("BOND_TOKEN", &mocks.bond_token) .env("WORLD_CHAIN_L2_CHAIN_ID", DEV_CHAIN_ID.to_string()) .env("ROLLUP_CONFIG_HASH", &rollup_config_hash_hex) .env("AGGREGATION_VKEY", DEVNET_AGGREGATION_VKEY.to_string()) @@ -1302,6 +1388,8 @@ async fn deploy_world_proof_system( validity = %deployment.validity_proof_verifier, tee = %deployment.tee_verifier, council = %deployment.security_council, + bond_token = %deployment.bond_token, + vault = %deployment.erc20_staking_vault, "World Chain proof-system contracts deployed" ); @@ -1315,6 +1403,9 @@ async fn deploy_world_proof_system( &dispute_game_factory, &anchor_state_registry, &system_config, + &op_chain_proxy_admin, + &deployment.bond_token, + &deployment.game_implementation, ) .await?; @@ -1331,12 +1422,16 @@ async fn activate_world_proof_system( dispute_game_factory: &str, anchor_state_registry: &str, system_config: &str, + op_chain_proxy_admin: &str, + bond_token: &str, + game_implementation: &str, ) -> Result<()> { let output = Command::new("forge") .current_dir(contracts_dir) .arg("script") .arg("scripts/devnet/ActivateProofSystem.s.sol:ActivateProofSystem") .arg("--broadcast") + .arg("--skip-simulation") .arg("--rpc-url") .arg(l1_rpc_url) .arg("--private-key") @@ -1345,9 +1440,13 @@ async fn activate_world_proof_system( .arg("--evm-version") .arg("cancun") .env("GUARDIAN_KEY", SUPERCHAIN_GUARDIAN_PRIVATE_KEY) + .env("DGF_OWNER_KEY", L1_PROXY_ADMIN_OWNER_PRIVATE_KEY) .env("DISPUTE_GAME_FACTORY", dispute_game_factory) .env("ANCHOR_STATE_REGISTRY", anchor_state_registry) .env("SYSTEM_CONFIG", system_config) + .env("OP_CHAIN_PROXY_ADMIN", op_chain_proxy_admin) + .env("BOND_TOKEN", bond_token) + .env("GAME_IMPLEMENTATION", game_implementation) .output() .await .wrap_err("failed to spawn forge proof-system activation")?; @@ -1385,6 +1484,88 @@ async fn activate_world_proof_system( Ok(()) } +async fn fund_world_proof_bond_accounts( + l1_rpc_url: &str, + deployment: &WorldProofSystemDeployment, +) -> Result<()> { + tokio::try_join!( + fund_world_proof_bond_account(l1_rpc_url, deployment, DEVNET_PRIVATE_KEY, "proposer"), + fund_world_proof_bond_account( + l1_rpc_url, + deployment, + WORLD_CHALLENGER_PRIVATE_KEY, + "challenger", + ), + )?; + Ok(()) +} + +async fn fund_world_proof_bond_account( + l1_rpc_url: &str, + deployment: &WorldProofSystemDeployment, + private_key: &str, + role: &str, +) -> Result<()> { + let bond_token_address: Address = deployment + .bond_token + .parse() + .wrap_err("invalid devnet bond-token address")?; + let vault_address: Address = deployment + .erc20_staking_vault + .parse() + .wrap_err("invalid devnet ERC-20 staking-vault address")?; + let signer: PrivateKeySigner = private_key + .parse() + .wrap_err_with(|| format!("invalid World Chain {role} signing key"))?; + let account = signer.address(); + let provider = ProviderBuilder::new() + .wallet(EthereumWallet::from(signer)) + .connect_http(Url::parse(l1_rpc_url)?); + let mock_bond_token = IMockBondToken::new(bond_token_address, provider.clone()); + let vault = IERC20StakingVault::IERC20StakingVaultInstance::new(vault_address, provider); + let amount = U256::from(WORLD_PROOF_SERVICE_BOND_TOKEN_BALANCE); + + let mint_receipt = mock_bond_token + .mint(account, amount) + .send() + .await? + .get_receipt() + .await?; + if !mint_receipt.status() { + bail!("minting mock bond tokens for the World Chain {role} reverted"); + } + let approval_receipt = mock_bond_token + .approve(vault_address, amount) + .send() + .await? + .get_receipt() + .await?; + if !approval_receipt.status() { + bail!("approving mock bond tokens for the World Chain {role} reverted"); + } + let deposit_receipt = vault + .deposit(account, amount) + .send() + .await? + .get_receipt() + .await?; + if !deposit_receipt.status() { + bail!("depositing mock bond tokens for the World Chain {role} reverted"); + } + let remaining_allowance = mock_bond_token + .allowance(account, vault_address) + .call() + .await?; + if !remaining_allowance.is_zero() { + bail!( + "deposit left a bond-token allowance for the World Chain {role}: {remaining_allowance}" + ); + } + + info!(%role, %account, %vault_address, %amount, "funded World Chain proof-system bond account"); + Ok(()) +} + fn write_l1_genesis(state_path: &Path, output_path: &Path) -> Result<()> { let state = read_json(state_path)?; let encoded = state @@ -1479,8 +1660,7 @@ fn world_defender_address() -> Result
{ Ok(signer.address()) } -/// Funds the World Chain challenger account in the L1 genesis `alloc` so it can -/// pay the challenger bond (plus gas) when submitting challenges. The account is +/// Funds the World Chain challenger account in the L1 genesis `alloc` for gas. The account is /// dedicated to the challenger, so it is never present in the op-deployer dump. fn fund_world_challenger(alloc: &mut Value) -> Result<()> { let address = world_challenger_address()?; @@ -2799,7 +2979,7 @@ async fn start_challenger( /// /// The proposer signs with the dev proposer key (Anvil account #1), funded via /// `fundDevAccounts`. Output roots are read from the op-node rollup RPC and -/// proposals are created through `DisputeGameFactory.create` on L1. +/// proposals are created through the factory, which locks tokens from the proposer's vault balance. async fn start_world_chain_proposer( l1_rpc_url: &str, output_root_rpc_url: &str, @@ -2836,6 +3016,7 @@ async fn start_world_chain_proposer( let output_roots = OptimismConsensusClient::new(output_root_rpc_url.to_string()); let registered = contracts.registered_lineage_config(); let config = ProposerConfig { + recovery_parent: None, poll_interval: WORLD_PROPOSER_POLL_INTERVAL, max_resolutions_per_tick: ProposerConfig::default().max_resolutions_per_tick, }; @@ -2879,8 +3060,7 @@ async fn start_world_chain_proposer( /// Spawns the in-process World Chain proof-system challenger. /// /// The challenger signs with [`WORLD_CHALLENGER_PRIVATE_KEY`], a dedicated dev -/// account that is funded through the L1 genesis (see [`fund_world_challenger`]). It scans -/// indexed factory games, recomputes the expected +/// account funded with L1 gas and a bond-token vault balance. It scans indexed factory games, recomputes the expected /// output root from the op-node rollup RPC, and challenges any game whose /// `rootClaim` disagrees by calling `MultiProofGame.challenge` on L1. async fn start_world_chain_challenger( @@ -2905,7 +3085,9 @@ async fn start_world_chain_challenger( factory_address, DEFAULT_L1_TX_CONFIRMATIONS, Duration::from_secs(world_chain_proof_protocol::DEFAULT_L1_TX_RECEIPT_TIMEOUT_SECONDS), - ); + ) + .await + .wrap_err("failed to bind the World Chain proof system")?; let output_roots = OptimismConsensusClient::new(output_root_rpc_url.to_string()); let config = ChallengerConfig { poll_interval: WORLD_CHALLENGER_POLL_INTERVAL, @@ -3047,22 +3229,33 @@ fn sp1_worker_prover_kind() -> Result> { } /// Starts the in-process defender prover-service and returns its task handle and JSON-RPC URL. -async fn start_prover_service() -> Result<(ProverServiceTask, String)> { +async fn start_prover_service(l1_rpc: &str) -> Result<(ProverServiceTask, String)> { let (database_url, postgres, postgres_data_dir) = prover_service_database_url().await?; let service = Arc::new( ProverService::connect(&database_url, ProverServiceConfig::default()) .await .wrap_err("failed to initialize postgres-backed prover-service")?, ); - let (addr, handle) = - start_rpc_server("127.0.0.1:0".parse().expect("valid loopback addr"), service) - .await - .wrap_err("failed to start prover-service RPC server")?; + let (addr, handle) = start_rpc_server( + "127.0.0.1:0".parse().expect("valid loopback addr"), + Arc::clone(&service), + ) + .await + .wrap_err("failed to start prover-service RPC server")?; + let provider = ProviderBuilder::new() + .disable_recommended_fillers() + .connect_http(Url::parse(l1_rpc)?); + let status_poller = tokio::spawn(run_status_poller( + service, + provider, + ProverServiceConfig::default().status_poller_interval, + )); let url = format!("http://{addr}"); info!(prover_service = %url, "started native defender prover-service"); Ok(( ProverServiceTask { handle, + status_poller, _postgres: postgres, _postgres_data_dir: postgres_data_dir, }, @@ -3644,6 +3837,11 @@ fn build_components( ) .with_endpoint("tee-verifier", deployment.tee_verifier.clone()) .with_endpoint("security-council", deployment.security_council.clone()) + .with_endpoint("bond-token", deployment.bond_token.clone()) + .with_endpoint( + "erc20-staking-vault", + deployment.erc20_staking_vault.clone(), + ) .with_note(format!( "WIP-1006 threshold {PROOF_THRESHOLD}/3, proof_system_version={}", deployment.proof_system_version @@ -3666,7 +3864,7 @@ fn build_components( .with_endpoint("dispute-game-factory", deployment.proof_system_factory.clone()) .with_endpoint("anchor", deployment.anchor_state_registry.clone()) .with_note(format!( - "native in-process proposer creating WIP-1006 games every {} L2 blocks via DisputeGameFactory.create", + "native in-process proposer locking ERC-20 bonds and creating WIP-1006 games every {} L2 blocks", deployment.block_interval )), ); diff --git a/crates/devnet/src/lib.rs b/crates/devnet/src/lib.rs index 62814d8d7..c259c8fa8 100644 --- a/crates/devnet/src/lib.rs +++ b/crates/devnet/src/lib.rs @@ -410,6 +410,32 @@ impl WorldDevnet { .or_else(|| self.l1.as_ref().map(L1DevChain::rpc_url)) } + /// L2 op-node RPC URL. + pub fn l2_op_node_rpc_url(&self) -> Option<&str> { + self.full_stack + .as_ref() + .map(FullStackWorldDevnet::l2_op_node_rpc_url) + } + + /// Aborts the in-process defender and its TEE/SP1 workers, when the full stack is running. + /// + /// See [`FullStackWorldDevnet::stop_defender`]. + pub fn stop_defender(&mut self) { + if let Some(full_stack) = self.full_stack.as_mut() { + full_stack.stop_defender(); + } + } + + /// Re-spawns the in-process defender and its TEE/SP1 workers after [`Self::stop_defender`]. + /// + /// See [`FullStackWorldDevnet::start_defender`]. + pub async fn start_defender(&mut self) -> Result<()> { + if let Some(full_stack) = self.full_stack.as_mut() { + full_stack.start_defender().await?; + } + Ok(()) + } + /// L1 OptimismPortal proxy address, when the preset started a full OP Stack. pub fn optimism_portal(&self) -> Option<&str> { self.full_stack diff --git a/crates/devnet/src/op_stack.rs b/crates/devnet/src/op_stack.rs index db2d9d991..ea01e8847 100644 --- a/crates/devnet/src/op_stack.rs +++ b/crates/devnet/src/op_stack.rs @@ -112,7 +112,8 @@ impl WorldContractsDeploymentConfig { if self.proof_system { contracts.extend([ "MultiProofGame(WIP_1006)", - "DelayedWETH(WIP_1006)", + "ERC20StakingVault(WIP_1006)", + "MockBondToken(devnet)", "MockRootIdVerifier(VALIDITY_PROOF)", "MockRootIdVerifier(TEE_ATTESTATION)", "MockRootIdVerifier(SECURITY_COUNCIL)", diff --git a/crates/evm/src/collector.rs b/crates/evm/src/collector.rs index 40d61a3a3..c236aa00d 100644 --- a/crates/evm/src/collector.rs +++ b/crates/evm/src/collector.rs @@ -4,8 +4,9 @@ use alloy_consensus::BlockHeader; use crossbeam_channel::{Receiver, TryRecvError}; use futures::StreamExt; use reth_provider::CanonStateSubscriptions; -use reth_revm::witness::ExecutionWitnessRecord; +use reth_revm::{State, witness::ExecutionWitnessRecord}; use reth_tasks::TaskExecutor; +use revm_database::EmptyDB; use crate::{BlockExecutionWitness, ExecutionWitnessHandle, ProviderBounds}; @@ -22,7 +23,7 @@ pub fn spawn_witness_collector

( tasks.spawn_critical_task("world-chain-witness-collector", async move { // Captured records awaiting their block becoming canonical, keyed by block number. - let mut queued: BTreeMap = BTreeMap::new(); + let mut queued: BTreeMap> = BTreeMap::new(); while let Some(notification) = canon.next().await { // Drain the channel without blocking. @@ -58,7 +59,7 @@ pub fn spawn_witness_collector

( for (block_number, record) in ready { let parent = block_number.saturating_sub(1); let result = provider.history_by_block_number(parent).and_then(|state| { - record.into_execution_witness( + ExecutionWitnessRecord::new(&record).into_execution_witness( &state, &provider, block_number, diff --git a/crates/evm/src/execution/bal.rs b/crates/evm/src/execution/bal.rs index baf06fada..ce39bd2c7 100644 --- a/crates/evm/src/execution/bal.rs +++ b/crates/evm/src/execution/bal.rs @@ -93,6 +93,11 @@ pub fn pre_refund_gas_used<'a>( #[derive(thiserror::Error, Debug, serde::Serialize)] pub enum BalValidationError { + #[error("Received BAL hash mismatch: expected {expected:?}, got {got:?}")] + ReceivedBalHashMismatch { + expected: FixedBytes<32>, + got: FixedBytes<32>, + }, #[error("BAL hash mismatch: expected {expected:?}, got {got:?}")] BalHashMismatch { expected: FixedBytes<32>, @@ -336,7 +341,9 @@ where // calculate the state root let state_root_started = Instant::now(); - let hashed_state = state.hashed_post_state(&bundle); + let hashed_state = state + .hashed_post_state(&bundle) + .map_err(BlockExecutionError::other)?; let (state_root, trie_updates) = state .state_root_with_updates(hashed_state.clone()) .map_err(BlockExecutionError::other)?; diff --git a/crates/evm/src/execution/basic.rs b/crates/evm/src/execution/basic.rs index ed571184b..074136717 100644 --- a/crates/evm/src/execution/basic.rs +++ b/crates/evm/src/execution/basic.rs @@ -184,7 +184,9 @@ where // calculate the state root let state_root_started = Instant::now(); - let hashed_state = state.hashed_post_state(&bundle); + let hashed_state = state + .hashed_post_state(&bundle) + .map_err(BlockExecutionError::other)?; let (state_root, trie_updates) = state .state_root_with_updates(hashed_state.clone()) .map_err(BlockExecutionError::other)?; diff --git a/crates/evm/src/execution/executor.rs b/crates/evm/src/execution/executor.rs index 26aab6655..30a425889 100644 --- a/crates/evm/src/execution/executor.rs +++ b/crates/evm/src/execution/executor.rs @@ -6,8 +6,9 @@ use reth_evm::{ GasOutput, }, }; -use reth_revm::{State, witness::ExecutionWitnessRecord}; +use reth_revm::State; use revm::context::Block; +use revm_database::{EmptyDB, states::bundle_state::BundleRetention}; use tracing::error; use crate::BlockExecutionWitness; @@ -21,24 +22,28 @@ pub struct WorldChainBlockExecutor { pub(crate) sender: Option>, } -/// Records an [`ExecutionWitnessRecord`] from a database when it is a [`State`] cache. +/// Snapshots execution state from a database when it is a [`State`] cache. trait MaybeWitness { - /// Returns the recorded witness if `self` is backed by a [`State`] cache. - fn witness(&self) -> Option; + /// Returns a state snapshot if `self` is backed by a [`State`] cache. + fn witness(&self) -> Option>; } impl MaybeWitness for T { - default fn witness(&self) -> Option { + default fn witness(&self) -> Option> { None } } impl MaybeWitness for &mut State { - fn witness(&self) -> Option { - Some(ExecutionWitnessRecord::from_executed_state( - self, - Default::default(), - )) + fn witness(&self) -> Option> { + let mut snapshot = State::builder() + .with_cached_prestate(self.cache.clone()) + .with_block_hashes(self.block_hashes.clone()) + .build(); + snapshot.bundle_state = self.bundle_state.clone(); + snapshot.transition_state = self.transition_state.clone(); + snapshot.merge_transitions(BundleRetention::PlainState); + Some(snapshot) } } @@ -88,10 +93,11 @@ where fn finish( self, ) -> Result<(Self::Evm, BlockExecutionResult), BlockExecutionError> { + let (evm, result) = self.inner.finish()?; if let Some(sender) = self.sender - && let Some(record) = self.inner.evm().db().witness() + && let Some(record) = evm.db().witness() { - let block_number = self.inner.evm().block().number(); + let block_number = evm.block().number(); let captured = BlockExecutionWitness { block_number: block_number.to(), @@ -103,7 +109,7 @@ where }); } - self.inner.finish() + Ok((evm, result)) } fn evm_mut(&mut self) -> &mut Self::Evm { @@ -118,3 +124,46 @@ where self.inner.receipts() } } + +#[cfg(test)] +mod tests { + use super::MaybeWitness; + use alloy_primitives::{Address, B256, U256}; + use reth_revm::State; + use revm::{ + DatabaseCommit, + state::{Account, AccountInfo}, + }; + + #[test] + fn witness_snapshot_preserves_pending_destruction_and_block_hash_reads() { + let address = Address::with_last_byte(1); + let mut state = State::builder().with_bundle_update().build(); + state.insert_account( + address, + AccountInfo { + balance: U256::from(1), + ..Default::default() + }, + ); + let mut destroyed = Account::default(); + destroyed.mark_touch(); + destroyed.mark_selfdestruct(); + state.commit([(address, destroyed)].into_iter().collect()); + state.block_hashes.insert(42, B256::with_last_byte(2)); + + let state_ref = &mut state; + let snapshot = state_ref + .witness() + .expect("state cache produces a witness snapshot"); + assert!(snapshot.bundle_state.state[&address].was_destroyed()); + assert_eq!(snapshot.block_hashes.get(42), Some(B256::with_last_byte(2))); + assert!(state.bundle_state.state.is_empty()); + assert!( + state + .transition_state + .as_ref() + .is_some_and(|transitions| !transitions.transitions.is_empty()) + ); + } +} diff --git a/crates/evm/src/lib.rs b/crates/evm/src/lib.rs index 64d574677..8bf16f118 100644 --- a/crates/evm/src/lib.rs +++ b/crates/evm/src/lib.rs @@ -46,7 +46,8 @@ use reth_evm::{ use reth_optimism_evm::{ConfigurePostExecEvm, PostExecExecutorExt, PostExecMode}; use reth_optimism_payload_builder::OpExecData; use reth_primitives_traits::{Block, BlockBody, NodePrimitives, SealedBlock, SealedHeader}; -use reth_revm::{State, witness::ExecutionWitnessRecord}; +use reth_revm::State; +use revm_database::EmptyDB; use crate::factory::WorldChainBlockExecutorFactory; @@ -77,12 +78,12 @@ impl ProviderBounds for T where } /// A captured execution witness for a single block. -#[derive(Debug, Clone)] +#[derive(Debug)] pub struct BlockExecutionWitness { /// Number of the block this witness was captured for. pub block_number: u64, - /// The recorded execution witness. - pub record: ExecutionWitnessRecord, + /// Finalized execution state retained until the block becomes canonical. + pub record: State, } /// The underlying OP EVM configuration that [`WorldChainEvmConfig`] defaults to, fixed to World diff --git a/crates/evm/src/utils.rs b/crates/evm/src/utils.rs index f4f0a0a11..bd52472b0 100644 --- a/crates/evm/src/utils.rs +++ b/crates/evm/src/utils.rs @@ -2,8 +2,11 @@ use alloy_eips::Encodable2718; use op_revm::estimate_tx_compressed_size; use reth_optimism_payload_builder::config::OpBuilderConfig; use revm_database::{ - BundleState, CacheState, - states::reverts::{AccountInfoRevert, Reverts}, + AccountStatus, BundleState, CacheState, + states::{ + CacheAccount, + reverts::{AccountInfoRevert, Reverts}, + }, }; use std::collections::{HashMap, hash_map::Entry}; @@ -60,7 +63,17 @@ pub fn cache_prestate_from_bundle(bundle: &BundleState) -> CacheState { accounts: bundle .state .iter() - .map(|(address, account)| (*address, account.into())) + .map(|(address, account)| { + let mut cached = CacheAccount::from(account); + // Destruction is already recorded in the committed bundle. Carrying it into a + // fresh fragment makes `extend` replace storage with that fragment's sparse writes. + // InMemoryChange still treats missing slots as zero; a new destruction is tracked + // normally by revm. + if cached.status == AccountStatus::DestroyedChanged { + cached.status = AccountStatus::InMemoryChange; + } + (*address, cached) + }) .collect(), contracts: bundle.contracts.clone(), } @@ -98,17 +111,114 @@ pub fn estimated_da_size_bytes(tx: &impl Encodable2718) -> u64 { #[cfg(test)] mod tests { use alloy_primitives::{Address, U256}; + use reth_trie_common::{HashedPostState, KeccakKeyHasher}; use revm::{ + Database, DatabaseCommit, database::{ - AccountRevert, AccountStatus, RevertToSlot, - states::reverts::{AccountInfoRevert, Reverts}, + AccountRevert, AccountStatus, RevertToSlot, State, + states::{ + bundle_state::BundleRetention, + reverts::{AccountInfoRevert, Reverts}, + }, }, - state::AccountInfo, + state::{Account, AccountInfo, EvmStorageSlot}, }; - use crate::utils::{effective_gas_limit, flatten_reverts}; + use crate::utils::{ + cache_prestate_from_bundle, effective_gas_limit, extend_flashblock_bundle, flatten_reverts, + }; use reth_optimism_payload_builder::config::OpBuilderConfig; + /// Fragment composition must preserve recreated storage and still honor a new destruction. + #[test] + fn recreated_account_across_flashblocks_matches_serial_state() { + let address = Address::with_last_byte(1); + let mut state = State::builder().with_bundle_update().build(); + // Prefunding prevents revm from eliding the first creation and destruction as a no-op. + state.insert_account( + address, + AccountInfo { + balance: U256::from(1), + ..Default::default() + }, + ); + + // EVM outputs for create-and-destroy, then recreation in another transaction. + let mut destroyed = Account::default(); + destroyed.mark_touch(); + destroyed.mark_selfdestruct(); + state.commit([(address, destroyed.clone())].into_iter().collect()); + + let info = AccountInfo { + nonce: 1, + ..Default::default() + }; + let mut recreated = Account::from(info.clone()); + recreated.mark_touch(); + recreated.mark_created(); + recreated.storage.insert( + U256::ZERO, + EvmStorageSlot::new_changed(U256::ZERO, U256::from(1), Default::default()), + ); + state.commit([(address, recreated)].into_iter().collect()); + state.merge_transitions(BundleRetention::Reverts); + let committed = state.take_bundle(); + assert_eq!( + committed.state[&address].status, + AccountStatus::DestroyedChanged + ); + + // Neither update includes slot 0, so merging must preserve its committed value. + let mut sparse_write = Account::from(info.clone()); + sparse_write.mark_touch(); + sparse_write.storage.insert( + U256::from(1), + EvmStorageSlot::new_changed(U256::ZERO, U256::from(7), Default::default()), + ); + let mut balance_only = Account::from(info); + balance_only.mark_touch(); + balance_only.info.balance = U256::from(2); + + for update in [sparse_write, balance_only, destroyed] { + // A fresh destruction is the control case: it must still clear slot 0. + let is_destroyed = update.is_selfdestructed(); + // Serial processing carries the whole bundle; a flashblock starts from its cache. + let mut serial = State::builder() + .with_bundle_prestate(committed.clone()) + .with_bundle_update() + .build(); + let mut fragment = State::builder() + .with_cached_prestate(cache_prestate_from_bundle(&committed)) + .with_bundle_update() + .build(); + for state in [&mut serial, &mut fragment] { + state.basic(address).unwrap(); + // Missing storage must not fall through to the parent database. + assert_eq!(state.storage(address, U256::from(2)).unwrap(), U256::ZERO); + state.commit([(address, update.clone())].into_iter().collect()); + state.merge_transitions(BundleRetention::Reverts); + } + + let composed = extend_flashblock_bundle(&committed, fragment.take_bundle()); + let mut expected = serial.take_bundle(); + expected.reverts = flatten_reverts(&expected.reverts); + // Compare the retained slot, trie inputs, and rollback data with serial processing. + assert_eq!( + composed.storage(&address, U256::ZERO), + Some(if is_destroyed { + U256::ZERO + } else { + U256::from(1) + }), + ); + assert_eq!( + HashedPostState::from_bundle_state::(composed.state.iter()), + HashedPostState::from_bundle_state::(expected.state.iter()), + ); + assert_eq!(composed.reverts, expected.reverts); + } + } + #[bon::builder] fn revert( #[builder(start_fn)] status: AccountStatus, diff --git a/crates/node/src/proof_history.rs b/crates/node/src/proof_history.rs index bce87f087..ddcf7b8d2 100644 --- a/crates/node/src/proof_history.rs +++ b/crates/node/src/proof_history.rs @@ -32,15 +32,7 @@ pub async fn launch_node( if !config.args.rollup.proofs_history { let handle = builder .node(WorldChainNode::::new(config)) - // Genesis emission must wait until the DB is initialized (the genesis block is - // written during launch), hence `on_node_started` rather than alongside - // `init_blockchain` in `main`. - .on_node_started(|node| { - reth_optimism_firehose::emit_genesis_block_if_empty( - &node.provider, - node.chain_spec().as_ref(), - ) - }) + .on_component_initialized(|node| reth_optimism_firehose::init_blockchain(&node.provider)) .launch() .await?; return handle.node_exit_future.await; @@ -91,11 +83,8 @@ where let handle = builder .node(WorldChainNode::::new(config)) + .on_component_initialized(|node| reth_optimism_firehose::init_blockchain(&node.provider)) .on_node_started(move |node| { - reth_optimism_firehose::emit_genesis_block_if_empty( - &node.provider, - node.chain_spec().as_ref(), - )?; spawn_proofs_db_metrics( node.task_executor, storage, diff --git a/crates/p2p/src/protocol/event.rs b/crates/p2p/src/protocol/event.rs index a03c33a65..bea451621 100644 --- a/crates/p2p/src/protocol/event.rs +++ b/crates/p2p/src/protocol/event.rs @@ -54,7 +54,6 @@ pub type WorldChainEventsStream = Pin( flashblocks: Pin + Send>>, canon: Pin + Send>>, diff --git a/crates/payload/src/generator.rs b/crates/payload/src/generator.rs index 24d147ab3..3de515128 100644 --- a/crates/payload/src/generator.rs +++ b/crates/payload/src/generator.rs @@ -148,7 +148,7 @@ where fn new_payload_job( &self, - input: BuildNewPayload, + mut input: BuildNewPayload, id: PayloadId, ) -> Result { let id = force_op_payload_id_v3(id); @@ -292,8 +292,9 @@ where p2p_handler: self.p2p_handler.clone(), flashblocks_state: self.flashblocks_state.clone(), block_index: index, - execution_cache: input.cache, - state_root_handle: input.state_root_handle, + execution_cache: input.resources.take_execution_cache(), + state_root_handle: input.resources.take_state_root_handle(), + leases: input.resources.take_leases(), }; // start the first job right away diff --git a/crates/payload/src/job.rs b/crates/payload/src/job.rs index c65811fd3..2d728fa62 100644 --- a/crates/payload/src/job.rs +++ b/crates/payload/src/job.rs @@ -15,7 +15,7 @@ use reth_basic_payload_builder::{ use reth_execution_cache::SavedCache; use reth_optimism_payload_builder::{OpBuiltPayload, OpPayloadAttrs}; use reth_optimism_primitives::OpPrimitives; -use reth_payload_builder::{KeepPayloadJobAlive, PayloadJob}; +use reth_payload_builder::{KeepPayloadJobAlive, PayloadBuilderLease, PayloadJob}; use reth_payload_primitives::{BuiltPayload, PayloadBuilderError, PayloadKind}; use reth_primitives_traits::BlockBody; use reth_revm::{cached::CachedReads, cancelled::CancelOnDrop}; @@ -240,6 +240,8 @@ pub struct FlashblocksPayloadJob { pub(crate) execution_cache: Option, /// Optional state root task handle, shared with the engine. pub(crate) state_root_handle: Option, + /// Resource leases retained while this job or its detached build tasks run. + pub(crate) leases: Vec, /// The type responsible for building payloads. /// /// See [`PayloadBuilder`] @@ -290,6 +292,7 @@ where let cached_reads = self.cached_reads.take().unwrap_or_default(); let execution_cache = self.execution_cache.clone(); let state_root_handle = self.state_root_handle.take(); + let leases = self.leases.clone(); let builder = self.builder.clone(); self.executor.spawn_blocking_task(Box::pin(async move { @@ -321,6 +324,7 @@ where } Err(err) => Err(err), }; + drop(leases); let _ = tx.send(outcome); })); @@ -700,8 +704,10 @@ where let (tx, rx) = oneshot::channel(); let config = self.config.clone(); let builder = self.builder.clone(); + let leases = self.leases.clone(); self.executor.spawn_blocking_task(Box::pin(async move { let res = builder.build_empty_payload(config); + drop(leases); let _ = tx.send(res); })); @@ -711,8 +717,11 @@ where debug!(target: "flashblocks::payload_builder", id=%self.config.payload_id(), "racing fallback payload"); // race the in progress job with this job let (tx, rx) = oneshot::channel(); + let leases = self.leases.clone(); self.executor.spawn_blocking_task(Box::pin(async move { - let _ = tx.send(job()); + let result = job(); + drop(leases); + let _ = tx.send(result); })); empty_payload = Some(rx); } diff --git a/crates/pool/src/tx.rs b/crates/pool/src/tx.rs index 4dccccb9b..f04b58925 100644 --- a/crates/pool/src/tx.rs +++ b/crates/pool/src/tx.rs @@ -66,6 +66,10 @@ where } impl OpPooledTx for WorldChainPooledTransaction { + fn set_op_fee_reservation(&mut self, fee: U256) { + self.inner.set_op_fee_reservation(fee); + } + fn encoded_2718(&self) -> std::borrow::Cow<'_, Bytes> { Cow::Borrowed(self.inner.encoded_2718()) } diff --git a/crates/primitives/src/flashblocks.rs b/crates/primitives/src/flashblocks.rs index e6157193b..88077d4b0 100644 --- a/crates/primitives/src/flashblocks.rs +++ b/crates/primitives/src/flashblocks.rs @@ -9,14 +9,14 @@ use alloy_consensus::{ proofs::ordered_trie_root_with_encoder, }; use alloy_eips::{ - Decodable2718, Encodable2718, eip7685::EMPTY_REQUESTS_HASH, - eip7928::EMPTY_BLOCK_ACCESS_LIST_HASH, merge::BEACON_NONCE, + Encodable2718, eip7685::EMPTY_REQUESTS_HASH, eip7928::EMPTY_BLOCK_ACCESS_LIST_HASH, + merge::BEACON_NONCE, }; use alloy_primitives::U256; use alloy_rpc_types_engine::PayloadId; use chrono::Utc; use eyre::eyre::{bail, eyre}; -use op_alloy_consensus::OpTxEnvelope; +use op_alloy_consensus::{OpTxEnvelope, decode_2718_canonical}; use reth_chainspec::EthereumHardforks; use reth_primitives_traits::{Block as _, BlockBody as _, RecoveredBlock, TxTy}; @@ -250,7 +250,7 @@ pub fn recovered_block_from_flashblocks( let transactions_encoded = diff .transactions .iter() - .map(|t| TxTy::::decode_2718(&mut t.as_ref())) + .map(|t| decode_2718_canonical::>(t)) .collect::, _>>() .map_err(|e| eyre!("Failed to decode transaction: {:?}", e))?; diff --git a/crates/rpc/Cargo.toml b/crates/rpc/Cargo.toml index 413c32337..577c104e5 100644 --- a/crates/rpc/Cargo.toml +++ b/crates/rpc/Cargo.toml @@ -39,7 +39,6 @@ reth-optimism-rpc.workspace = true reth-optimism-node.workspace = true reth-optimism-forks.workspace = true reth-optimism-primitives.workspace = true -reth-optimism-evm.workspace = true reth-revm.workspace = true # alloy diff --git a/crates/rpc/src/eth/receipt.rs b/crates/rpc/src/eth/receipt.rs index d67920c22..7f43f9716 100644 --- a/crates/rpc/src/eth/receipt.rs +++ b/crates/rpc/src/eth/receipt.rs @@ -1,20 +1,12 @@ -use std::sync::Arc; - -use alloy_consensus::TxReceipt; use op_alloy_rpc_types::OpTransactionReceipt; use reth_chainspec::ChainSpecProvider; use reth_optimism_forks::OpHardforks; use reth_optimism_primitives::OpPrimitives; -use reth_optimism_rpc::{OpEthApi, OpEthApiError, OpReceiptBuilder}; -use reth_primitives_traits::{Recovered, TransactionMeta}; -use reth_provider::{ProviderReceipt, ProviderTx}; +use reth_optimism_rpc::{OpEthApi, OpEthApiError}; use reth_rpc_eth_api::{ - EthApiTypes, RpcConvert, RpcNodeCore, RpcNodeCoreExt, RpcReceipt, RpcTypes, + EthApiTypes, RpcConvert, RpcNodeCore, RpcTypes, helpers::{LoadPendingBlock, LoadReceipt}, - transaction::ConvertReceiptInput, }; -use reth_rpc_eth_types::{EthApiError, block::BlockAndReceipts}; -use tracing::trace; use crate::eth::FlashblocksEthApi; @@ -34,93 +26,4 @@ where Error = OpEthApiError, > + RpcNodeCore>, { - /// Helper method for `eth_getBlockReceipts` and `eth_getTransactionReceipt`. - async fn build_transaction_receipt( - &self, - tx: Recovered>, - meta: TransactionMeta, - receipt: ProviderReceipt, - all_receipts: Option>>>, - ) -> Result, Self::Error> { - let hash = meta.block_hash; - - // get all receipts for the block - let all_receipts = match all_receipts { - Some(all_receipts) => Some((all_receipts, None)), - None => { - if let Ok(Some(receipts)) = self.cache().get_receipts(hash).await { - Some((receipts, None)) - } else { - // try the pending block - let pending_block = self.local_pending_block().await?; - if let Some(BlockAndReceipts { block, receipts }) = pending_block { - if block.hash_slow() == hash { - Some((receipts, Some(block))) - } else { - None - } - } else { - None - } - } - } - }; - - let all_receipts = all_receipts.ok_or(EthApiError::HeaderNotFound(hash.into()))?; - let (all_receipts, block) = all_receipts; - - let mut gas_used = 0; - let mut next_log_index = 0; - - if meta.index > 0 { - for receipt in all_receipts.iter().take(meta.index as usize) { - gas_used = receipt.cumulative_gas_used(); - next_log_index += receipt.logs().len(); - } - } - let hash = tx.hash(); - trace!( - target: "flashblocks", - tx_hash = ?hash, - tx_index = meta.index, - gas_used = ?gas_used, - receipt_gas_used = ?receipt.cumulative_gas_used(), - "Building receipt for tx", - ); - - let input = ConvertReceiptInput { - tx: tx.as_recovered_ref(), - gas_used: receipt.cumulative_gas_used().saturating_sub(gas_used), - receipt, - next_log_index, - meta, - }; - - match block { - None => Ok(self - .converter() - .convert_receipts(vec![input])? - .pop() - .unwrap()), - Some(block) => { - let mut l1_block_info = match reth_optimism_evm::extract_l1_info(block.body()) { - Ok(l1_block_info) => l1_block_info, - Err(err) => Err(err)?, - }; - - // We must clear this cache as different L2 transactions can have different - // L1 costs. A potential improvement here is to only clear the cache if the - // new transaction input has changed, since otherwise the L1 cost wouldn't. - l1_block_info.clear_tx_l1_cost(); - - Ok(OpReceiptBuilder::new( - &self.provider().chain_spec(), - input, - &mut l1_block_info, - None, - )? - .build()) - } - } - } } diff --git a/crates/rpc/src/eth/transaction.rs b/crates/rpc/src/eth/transaction.rs index aca82c479..d40f0a21c 100644 --- a/crates/rpc/src/eth/transaction.rs +++ b/crates/rpc/src/eth/transaction.rs @@ -6,8 +6,10 @@ use alloy_primitives::{B256, Bytes, TxHash}; use reth_node_api::BlockBody; use reth_optimism_primitives::OpPrimitives; use reth_optimism_rpc::{OpEthApi, OpEthApiError}; -use reth_primitives_traits::{Recovered, SignerRecoverable, TransactionMeta}; -use reth_provider::{ProviderReceipt, ProviderTx, ReceiptProvider, TransactionsProvider}; +use reth_primitives_traits::{Recovered, RecoveredBlock, SignerRecoverable, TransactionMeta}; +use reth_provider::{ + ProviderBlock, ProviderReceipt, ProviderTx, ReceiptProvider, TransactionsProvider, +}; use reth_rpc_eth_api::{ EthApiTypes, FromEthApiError, FromEvmError, RpcConvert, RpcNodeCore, RpcNodeCoreExt, helpers::{ @@ -73,6 +75,7 @@ where TransactionMeta, ProviderReceipt, Option>>>, + Option>>>, )>, Self::Error, > @@ -88,7 +91,13 @@ where if let Some(all_receipts) = cached.receipts.clone() && let Some(receipt) = all_receipts.get(cached.tx_index).cloned() { - return Ok(Some((tx, meta, receipt, Some(all_receipts)))); + return Ok(Some(( + tx, + meta, + receipt, + Some(all_receipts), + Some(cached.block), + ))); } // Block still cached but receipts evicted — fetch via cache since @@ -101,7 +110,13 @@ where .map_err(Self::Error::from_eth_err)? && let Some(receipt) = receipts.get(cached.tx_index).cloned() { - return Ok(Some((tx, meta, receipt, Some(receipts)))); + return Ok(Some(( + tx, + meta, + receipt, + Some(receipts), + Some(cached.block), + ))); } } @@ -113,7 +128,7 @@ where .transactions_iter() .position(|t| *t.tx_hash() == hash) { - let receipt = &receipts[pos]; + let receipt = receipts[pos].clone(); let tx = block .clone() .body() @@ -135,7 +150,13 @@ where .try_into_recovered_unchecked() .map_err(Self::Error::from_eth_err)?; - return Ok(Some((tx, meta, receipt.clone(), None))); + return Ok(Some(( + tx, + meta, + receipt, + Some(receipts), + Some(block.clone()), + ))); } let provider = this.provider(); @@ -159,7 +180,7 @@ where None => return Ok(None), }; - Ok(Some((tx, meta, receipt, None))) + Ok(Some((tx, meta, receipt, None, None))) }) .await } diff --git a/crates/test-utils/Cargo.toml b/crates/test-utils/Cargo.toml index b2f62ea5a..fae64035e 100644 --- a/crates/test-utils/Cargo.toml +++ b/crates/test-utils/Cargo.toml @@ -28,6 +28,7 @@ reth-optimism-primitives.workspace = true reth-optimism-payload-builder.workspace = true reth-primitives-traits.workspace = true reth-provider.workspace = true +reth-storage-errors.workspace = true reth-chainspec.workspace = true reth-transaction-pool.workspace = true reth-node-ethereum.workspace = true diff --git a/crates/test-utils/src/builder.rs b/crates/test-utils/src/builder.rs index 0c1c1c851..040318636 100644 --- a/crates/test-utils/src/builder.rs +++ b/crates/test-utils/src/builder.rs @@ -780,6 +780,14 @@ where ); executor.gas_used = prev_outcome.as_ref().map_or(0, |o| o.0.block.gas_used()); + executor.evm_gas_used = prev_outcome.as_ref().map_or(0, |o| { + let transactions: Vec<_> = o.0.block.clone_transactions_recovered().collect(); + pre_refund_gas_used(o.0.block.gas_used(), transactions.iter()) + }); + executor.da_footprint_used = prev_outcome + .as_ref() + .and_then(|o| o.0.block.blob_gas_used()) + .unwrap_or_default(); executor.receipts = prev_outcome .as_ref() .map_or(Vec::new(), |o| o.0.execution_result.receipts.clone()); @@ -822,9 +830,9 @@ where // ============================================================================ // Mock State Provider with In-Memory Trie // ============================================================================ -fn create_test_db() -> InMemoryDB { +fn create_test_db(genesis: &Genesis) -> InMemoryDB { let mut db = InMemoryDB::default(); - for (address, account) in GENESIS.alloc.clone() { + for (address, account) in genesis.alloc.clone() { db.insert_account_info( address, AccountInfo { @@ -999,10 +1007,27 @@ impl Default for TestStateProvider { impl TestStateProvider { pub fn new() -> Self { Self { - db: create_test_db(), + db: create_test_db(&GENESIS), hashed_genesis: HashedGenesisState::from_genesis(&GENESIS), } } + + /// Creates a state provider including account storage from a custom genesis. + pub fn from_genesis(genesis: &Genesis) -> Self { + let mut db = create_test_db(genesis); + for (address, account) in &genesis.alloc { + if let Some(storage) = &account.storage { + for (slot, value) in storage { + db.insert_account_storage(*address, (*slot).into(), (*value).into()) + .expect("infallible in-memory storage insert"); + } + } + } + Self { + db, + hashed_genesis: HashedGenesisState::from_genesis(genesis), + } + } } impl BytecodeReader for TestStateProvider { @@ -1197,10 +1222,13 @@ impl reth_provider::StateProofProvider for TestStateProvider { } impl reth_provider::HashedPostStateProvider for TestStateProvider { - fn hashed_post_state(&self, bundle_state: &BundleState) -> reth_trie_common::HashedPostState { - reth_trie_common::HashedPostState::from_bundle_state::( - bundle_state.state(), - ) + fn hashed_post_state( + &self, + bundle_state: &BundleState, + ) -> ProviderResult { + Ok(reth_trie_common::HashedPostState::from_bundle_state::< + reth_trie_common::KeccakKeyHasher, + >(bundle_state.state())) } } @@ -1453,7 +1481,7 @@ impl reth_provider::StateProofProvider for BenchProvider { } impl reth_provider::HashedPostStateProvider for BenchProvider { - fn hashed_post_state(&self, bundle_state: &BundleState) -> HashedPostState { + fn hashed_post_state(&self, bundle_state: &BundleState) -> ProviderResult { self.inner.hashed_post_state(bundle_state) } } diff --git a/crates/test-utils/src/e2e_harness/context.rs b/crates/test-utils/src/e2e_harness/context.rs index d771ca4fe..ff8d71d59 100644 --- a/crates/test-utils/src/e2e_harness/context.rs +++ b/crates/test-utils/src/e2e_harness/context.rs @@ -144,6 +144,7 @@ where pub struct WorldRpcTypes; impl RpcTypes for WorldRpcTypes { + type Log = alloy_rpc_types_eth::Log; type Header = alloy_rpc_types_eth::Header

; type Receipt = OpTransactionReceipt; type TransactionRequest = OpTransactionRequest; diff --git a/crates/test-utils/src/mock.rs b/crates/test-utils/src/mock.rs index 0a30c722a..515bb9ccd 100644 --- a/crates/test-utils/src/mock.rs +++ b/crates/test-utils/src/mock.rs @@ -32,10 +32,11 @@ use reth_provider::{ HashedPostStateProvider, HeaderProvider, ProviderError, ProviderResult, ReceiptProvider, ReceiptProviderIdExt, StageCheckpointReader, StateProofProvider, StateProvider, StateProviderBox, StateProviderFactory, StateReader, StateRootProvider, StorageRootProvider, - TransactionVariant, TransactionsProvider, providers::ConsistentViewError, + TransactionVariant, TransactionsProvider, }; use reth_revm::revm; use reth_stages_types::{StageCheckpoint, StageId}; +use reth_storage_errors::provider::ConsistentViewError; use reth_trie::{ AccountProof, HashedPostState, HashedStorage, MultiProof, MultiProofTargets, StorageMultiProof, StorageProof, TrieInput, updates::TrieUpdates, @@ -698,8 +699,11 @@ impl StateProofProvider for MockEthProvider { } impl HashedPostStateProvider for MockEthProvider { - fn hashed_post_state(&self, _state: &revm::database::BundleState) -> HashedPostState { - HashedPostState::default() + fn hashed_post_state( + &self, + _state: &revm::database::BundleState, + ) -> ProviderResult { + Ok(HashedPostState::default()) } } diff --git a/crates/test-utils/src/node.rs b/crates/test-utils/src/node.rs index dc64a14e6..82a26f5a4 100644 --- a/crates/test-utils/src/node.rs +++ b/crates/test-utils/src/node.rs @@ -633,8 +633,11 @@ impl StateProvider for WorldChainNoopProvider { } impl HashedPostStateProvider for WorldChainNoopProvider { - fn hashed_post_state(&self, _bundle_state: &reth_revm::db::BundleState) -> HashedPostState { - HashedPostState::default() + fn hashed_post_state( + &self, + _bundle_state: &reth_revm::db::BundleState, + ) -> ProviderResult { + Ok(HashedPostState::default()) } } diff --git a/crates/validator/Cargo.toml b/crates/validator/Cargo.toml index d3b0bfdbe..0c76fe089 100644 --- a/crates/validator/Cargo.toml +++ b/crates/validator/Cargo.toml @@ -31,9 +31,9 @@ reth-optimism-evm.workspace = true alloy-consensus.workspace = true alloy-eip7928.workspace = true alloy-primitives.workspace = true -alloy-eips.workspace = true alloy-op-evm.workspace = true alloy-rpc-types-engine.workspace = true +op-alloy-consensus.workspace = true # revm revm.workspace = true @@ -54,6 +54,8 @@ metrics.workspace = true metrics-derive.workspace = true [dev-dependencies] +alloy-eips.workspace = true +op-revm.workspace = true world-chain-test-utils.workspace = true world-chain-p2p = { workspace = true, features = ["test-utils"] } world-chain-node.workspace = true diff --git a/crates/validator/src/execution_strategy.rs b/crates/validator/src/execution_strategy.rs index fe8825767..ccd9c9416 100644 --- a/crates/validator/src/execution_strategy.rs +++ b/crates/validator/src/execution_strategy.rs @@ -4,13 +4,14 @@ use alloy_consensus::{Header, Transaction}; use alloy_eip7928::BlockAccessIndex; use alloy_op_evm::{ OpBlockExecutionCtx, OpBlockExecutor, OpBlockExecutorFactory, OpEvmFactory, OpTx, + block::OpBlockExecutionError, }; use alloy_primitives::{B256, U256}; use alloy_rpc_types_engine::PayloadId; use rayon::prelude::*; use reth_evm::{ ConfigureEvm, Evm, EvmEnvFor, EvmFactory, - block::{BlockExecutionError, CommitChanges}, + block::{BlockExecutionError, BlockValidationError, CommitChanges}, execute::{BlockAssemblerInput, BlockBuilder, BlockExecutor, BlockExecutorFactory}, }; use reth_node_api::BuiltPayloadExecutedBlock; @@ -34,7 +35,7 @@ use crate::{ state_root_strategy::{StateRootHandle, StateRootStrategy}, validator::decode_transactions_with_indices, }; -use world_chain_chainspec::WorldChainSpec; +use world_chain_chainspec::{WorldChainHardforks, WorldChainSpec}; use world_chain_evm::{ PayloadBuildStage, WorldChainEvmConfig, execution::{ @@ -262,6 +263,17 @@ impl<'a, S: StateRootStrategy> BalBlockValidator<'a, S> { .ok_or(BalValidationError::MissingAccessListData.boxed()) .map_err(BalExecutorError::from)?; + // Bind the claimed state changes to the hash that re-execution verifies below. + let received_access_list_hash = access_list_hash(&access_list); + if received_access_list_hash != expected_access_list_hash { + return Err(BalValidationError::ReceivedBalHashMismatch { + expected: expected_access_list_hash, + got: received_access_list_hash, + } + .boxed() + .into()); + } + let min_tx_index = access_list.min_tx_index; let max_tx_index = access_list.max_tx_index; let transactions_offset = committed_state.transactions.len() as u64 + 1; @@ -341,8 +353,42 @@ impl<'a, S: StateRootStrategy> BalBlockValidator<'a, S> { )?; let basefee = self.ctx.evm_env.block_env.basefee; + let block_gas_limit = self.ctx.evm_env.block_env.gas_limit; + let is_jovian = self + .ctx + .chain_spec + .is_jovian_active_at_timestamp(self.ctx.evm_env.block_env.timestamp.saturating_to()); let mut fees = U256::ZERO; for output in worker_outputs { + // Mirror OP admission checks because workers start with zero cumulative block usage. + let block_available_gas = + block_gas_limit.saturating_sub(canonical_executor.evm_gas_used); + let transaction_gas_limit = output.transaction.gas_limit(); + if (canonical_executor.is_regolith || !output.result.is_deposit) + && transaction_gas_limit > block_available_gas + { + return Err(BlockExecutionError::Validation( + BlockValidationError::TransactionGasLimitMoreThanAvailableBlockGas { + transaction_gas_limit, + block_available_gas, + }, + ) + .into()); + } + if is_jovian && !output.result.is_deposit && !output.result.is_post_exec { + let transaction_da_footprint = output.result.inner.blob_gas_used; + let available_block_da_footprint = + block_gas_limit.saturating_sub(canonical_executor.da_footprint_used); + if transaction_da_footprint > available_block_da_footprint { + return Err(BlockExecutionError::Validation(BlockValidationError::Other( + Box::new(OpBlockExecutionError::TransactionDaFootprintAboveGasLimit { + transaction_da_footprint, + available_block_da_footprint, + }), + )) + .into()); + } + } canonical_executor .evm_mut() .db_mut() @@ -515,7 +561,6 @@ impl<'a, S: StateRootStrategy> BalBlockValidator<'a, S> { execution_output: Arc::new(execution_output), hashed_state: Arc::new(hashed_state), trie_updates: Arc::new(trie_updates), - changed_paths: None, }; Ok(OpBuiltPayload::new( @@ -690,7 +735,6 @@ impl ExecutionStrategy execution_output: Arc::new(execution_output), hashed_state: Arc::new(hashed_state), trie_updates: Arc::new(trie_updates), - changed_paths: None, }; Ok(OpBuiltPayload::new( diff --git a/crates/validator/src/validator.rs b/crates/validator/src/validator.rs index ec653ebc2..dd9bf57f1 100644 --- a/crates/validator/src/validator.rs +++ b/crates/validator/src/validator.rs @@ -2,7 +2,7 @@ use alloy_consensus::{ Header, transaction::{Recovered, SignerRecoverable}, }; -use alloy_eips::Decodable2718; +use op_alloy_consensus::decode_2718_canonical; use reth_primitives_traits::SealedHeader; use std::{marker::PhantomData, sync::Arc, time::Instant}; @@ -52,11 +52,7 @@ pub fn into_executed_payload( }, ) }; - let trie_data = ComputedTrieData::new_with_changed_paths( - Arc::new(hashed_state), - Arc::new(trie_updates), - payload.changed_paths, - ); + let trie_data = ComputedTrieData::new(Arc::new(hashed_state), Arc::new(trie_updates)); ExecutedBlock::new(payload.recovered_block, payload.execution_output, trie_data) } @@ -200,8 +196,8 @@ pub fn decode_transactions_with_indices( .iter() .enumerate() .map(|(i, tx)| { - let tx_envelope = OpTransactionSigned::decode_2718(&mut tx.as_ref()) - .map_err(BalExecutorError::other)?; + let tx_envelope: OpTransactionSigned = + decode_2718_canonical(tx).map_err(BalExecutorError::other)?; let signer = tx_envelope .recover_signer() diff --git a/crates/validator/tests/access_list_validation.rs b/crates/validator/tests/access_list_validation.rs new file mode 100644 index 000000000..2cd9cb525 --- /dev/null +++ b/crates/validator/tests/access_list_validation.rs @@ -0,0 +1,199 @@ +use std::sync::Arc; + +use alloy_eip7928::{AccountChanges, BalanceChange, BlockAccessIndex}; +use alloy_primitives::{Address, U256}; +use reth_chain_state::ExecutedBlock; +use reth_optimism_primitives::OpPrimitives; +use reth_provider::StateRootProvider; +use reth_trie_common::HashedPostState; +use world_chain_evm::execution::bal::{BalExecutorError, BalValidationError}; +use world_chain_p2p::protocol::handler::FlashblocksHandle; +use world_chain_primitives::{ + access_list::access_list_hash, ed25519_dalek::SigningKey, primitives::FlashblocksPayloadV1, +}; +use world_chain_test_utils::builder::{ + BenchProvider, CHAIN_SPEC, EVM_CONFIG, build_flashblock_fixture_eth_transfers, + build_flashblock_sequence_fixture_eth_transfers, +}; +use world_chain_validator::{ + coordinator::{FlashblocksExecutionCoordinator, process_flashblock}, + flashblock_validation_metrics::FlashblockValidationMetrics, +}; + +fn test_coordinator() -> ( + FlashblocksExecutionCoordinator, + tokio::sync::watch::Sender>>, + tokio::sync::watch::Receiver>>, +) { + let sk = SigningKey::from_bytes(&[1u8; 32]); + let handle = FlashblocksHandle::new(sk.verifying_key(), Some(sk)); + let (pending_tx, pending_rx) = tokio::sync::watch::channel(None); + let coordinator = FlashblocksExecutionCoordinator::new(handle, pending_tx.clone()); + (coordinator, pending_tx, pending_rx) +} + +fn flashblock_with_injected_balance() -> FlashblocksPayloadV1 { + let provider = BenchProvider::new(); + let mut flashblock = build_flashblock_fixture_eth_transfers(1, true); + let (coordinator, pending_tx, _) = test_coordinator(); + process_flashblock( + provider.clone(), + &EVM_CONFIG, + &coordinator, + CHAIN_SPEC.clone(), + flashblock.clone(), + pending_tx, + Arc::new(FlashblockValidationMetrics::default()), + ) + .expect("honest flashblock is valid"); + let mut header = coordinator + .latest_payload() + .expect("built payload") + .block() + .header() + .clone(); + + let data = flashblock + .diff + .access_list_data + .as_mut() + .expect("BAL sidecar"); + let untouched = Address::repeat_byte(0xff); + assert!( + data.access_list + .changes + .iter() + .all(|account| account.address != untouched) + ); + data.access_list + .changes + .push( + AccountChanges::new(untouched).with_balance_change(BalanceChange::new( + BlockAccessIndex::new(data.access_list.max_tx_index), + U256::from(10u64.pow(18)), + )), + ); + data.access_list + .changes + .sort_unstable_by_key(|account| account.address); + assert_ne!(access_list_hash(&data.access_list), data.access_list_hash); + + // Match the forged state root and block hash while keeping the honest execution's BAL hash. + let hashed_state = data + .access_list + .clone() + .into_hashed_post_state(&provider, HashedPostState::default()) + .expect("claimed post-state"); + flashblock.diff.state_root = provider + .state_root(hashed_state) + .expect("claimed state root"); + assert_ne!(flashblock.diff.state_root, header.state_root); + header.state_root = flashblock.diff.state_root; + flashblock.diff.block_hash = header.hash_slow(); + flashblock +} + +#[tokio::test] +async fn accepts_valid_flashblock_sequences_with_and_without_access_lists() { + for bal_enabled in [false, true] { + let (coordinator, pending_tx, pending_rx) = test_coordinator(); + let sequence = build_flashblock_sequence_fixture_eth_transfers(2, 1, bal_enabled); + for flashblock in sequence { + let expected_hash = flashblock.diff.block_hash; + process_flashblock( + BenchProvider::new(), + &EVM_CONFIG, + &coordinator, + CHAIN_SPEC.clone(), + flashblock, + pending_tx.clone(), + Arc::new(FlashblockValidationMetrics::default()), + ) + .expect("valid flashblock"); + assert_eq!( + coordinator + .latest_payload() + .expect("built payload") + .block() + .hash(), + expected_hash + ); + assert!(pending_rx.borrow().is_some()); + } + } +} + +#[tokio::test] +async fn rejects_unexecuted_balance_change_with_honest_access_list_hash() { + let flashblock = flashblock_with_injected_balance(); + let data = flashblock + .diff + .access_list_data + .as_ref() + .expect("BAL sidecar"); + let expected_hash = data.access_list_hash; + let received_hash = access_list_hash(&data.access_list); + let (coordinator, pending_tx, pending_rx) = test_coordinator(); + let initial_flashblocks = coordinator.flashblocks(); + let (events_tx, mut events_rx) = tokio::sync::broadcast::channel(16); + coordinator.register_payload_events(events_tx); + + let error = process_flashblock( + BenchProvider::new(), + &EVM_CONFIG, + &coordinator, + CHAIN_SPEC.clone(), + flashblock, + pending_tx, + Arc::new(FlashblockValidationMetrics::default()), + ) + .expect_err("unexecuted balance change must be rejected"); + + let BalExecutorError::BalValidationError(error) = error.downcast().expect("BAL error") else { + panic!("expected BAL validation error"); + }; + assert!( + matches!(error.as_ref(), BalValidationError::ReceivedBalHashMismatch { expected, got } + if *expected == expected_hash && *got == received_hash) + ); + assert!(coordinator.latest_payload().is_none()); + assert!(pending_rx.borrow().is_none()); + assert_eq!(coordinator.flashblocks(), initial_flashblocks); + assert!(matches!( + events_rx.try_recv(), + Err(tokio::sync::broadcast::error::TryRecvError::Empty) + )); +} + +#[tokio::test] +async fn rejects_unexecuted_balance_change_with_matching_received_hash() { + let mut flashblock = flashblock_with_injected_balance(); + let data = flashblock + .diff + .access_list_data + .as_mut() + .expect("BAL sidecar"); + data.access_list_hash = access_list_hash(&data.access_list); + let (coordinator, pending_tx, pending_rx) = test_coordinator(); + + let error = process_flashblock( + BenchProvider::new(), + &EVM_CONFIG, + &coordinator, + CHAIN_SPEC.clone(), + flashblock, + pending_tx, + Arc::new(FlashblockValidationMetrics::default()), + ) + .expect_err("claimed changes must also match re-execution"); + + let BalExecutorError::BalValidationError(error) = error.downcast().expect("BAL error") else { + panic!("expected BAL validation error"); + }; + assert!(matches!( + error.as_ref(), + BalValidationError::BalHashMismatch { .. } + )); + assert!(coordinator.latest_payload().is_none()); + assert!(pending_rx.borrow().is_none()); +} diff --git a/crates/validator/tests/canonical_transactions.rs b/crates/validator/tests/canonical_transactions.rs new file mode 100644 index 000000000..4e1028772 --- /dev/null +++ b/crates/validator/tests/canonical_transactions.rs @@ -0,0 +1,87 @@ +use alloy_consensus::{SignableTransaction, TxEip1559, TxEip2930, TxEip7702, TxLegacy}; +use alloy_eips::Encodable2718; +use alloy_primitives::{Bytes, Signature}; +use op_alloy_consensus::{OpTxEnvelope, TxDeposit, build_post_exec_tx}; +use world_chain_chainspec::WorldChainSpec; +use world_chain_primitives::{ + flashblocks::{Flashblock, recovered_block_from_flashblocks}, + primitives::{ExecutionPayloadBaseV1, ExecutionPayloadFlashblockDeltaV1, FlashblocksPayloadV1}, +}; +use world_chain_validator::validator::decode_transactions_with_indices; + +fn transactions() -> Vec { + let signature = Signature::test_signature(); + let transactions: Vec = vec![ + TxLegacy::default().into_signed(signature).into(), + TxEip2930::default().into_signed(signature).into(), + TxEip1559::default().into_signed(signature).into(), + TxEip7702::default().into_signed(signature).into(), + TxDeposit::default().into(), + build_post_exec_tx(1, vec![]).into(), + ]; + transactions + .into_iter() + .map(|tx| tx.encoded_2718().into()) + .collect() +} + +fn flashblock(transactions: Vec) -> Flashblock { + Flashblock { + flashblock: FlashblocksPayloadV1 { + base: Some(ExecutionPayloadBaseV1::default()), + diff: ExecutionPayloadFlashblockDeltaV1 { + transactions, + ..Default::default() + }, + ..Default::default() + }, + } +} + +#[test] +fn accepts_canonical_transactions() { + let transactions = transactions(); + let decoded = decode_transactions_with_indices(&transactions, 7).expect("valid transactions"); + assert_eq!(decoded.len(), transactions.len()); + for (i, (index, tx)) in decoded.iter().enumerate() { + assert_eq!(*index, 7 + i as u64); + assert_eq!(tx.encoded_2718(), transactions[i]); + } + let block = recovered_block_from_flashblocks( + WorldChainSpec::mainnet(), + flashblock(transactions.clone()), + ) + .expect("valid flashblock"); + assert_eq!(block.body().transactions.len(), transactions.len()); + for (tx, encoded) in block.body().transactions.iter().zip(transactions) { + assert_eq!(tx.encoded_2718(), encoded); + } +} + +#[test] +fn rejects_non_canonical_transactions() { + let transactions = transactions(); + let mut malformed = vec![Bytes::new(), Bytes::from_static(&[0xff])]; + let mut tagged_legacy = vec![0x00]; + tagged_legacy.extend_from_slice(&transactions[0]); + malformed.push(tagged_legacy.into()); + for (i, tx) in transactions.iter().enumerate() { + let mut trailing = tx.to_vec(); + trailing.push(0x00); + malformed.push(trailing.into()); + if i > 0 { + malformed.push(tx.slice(1..)); + } + } + for tx in malformed { + let input = vec![transactions[0].clone(), tx.clone()]; + assert!( + decode_transactions_with_indices(&input, 7).is_err(), + "accepted {tx}" + ); + assert!( + recovered_block_from_flashblocks(WorldChainSpec::mainnet(), flashblock(input)).is_err(), + "accepted {tx}" + ); + } +} diff --git a/crates/validator/tests/cumulative_admission.rs b/crates/validator/tests/cumulative_admission.rs new file mode 100644 index 000000000..47f93ae17 --- /dev/null +++ b/crates/validator/tests/cumulative_admission.rs @@ -0,0 +1,377 @@ +use alloy_consensus::BlockHeader; +use alloy_eips::Encodable2718; +use alloy_op_evm::block::OpBlockExecutionError; +use alloy_primitives::{Address, B256, U256}; +use alloy_rpc_types_engine::PayloadId; +use op_revm::constants::{ + DA_FOOTPRINT_GAS_SCALAR_OFFSET, DA_FOOTPRINT_GAS_SCALAR_SLOT, L1_BLOCK_CONTRACT, +}; +use reth_evm::{ + block::{BlockExecutionError, BlockValidationError}, + execute::BlockBuilderOutcome, +}; +use reth_optimism_node::OpBuiltPayload; +use reth_optimism_primitives::{OpPrimitives, OpTransactionSigned}; +use reth_primitives_traits::Recovered; +use revm_database::BundleState; +use world_chain_evm::execution::bal::{BalExecutorError, CommittedState}; +use world_chain_primitives::{ + access_list::FlashblockAccessListData, primitives::ExecutionPayloadFlashblockDeltaV1, +}; +use world_chain_test_utils::builder::{ + ALICE, BLOCK_EXECUTION_CTX, CHAIN_SPEC, EVM_ENV, GENESIS, SEALED_HEADER, TestStateProvider, + TxOp, execute_serial_with_provider, +}; +use world_chain_validator::{ + execution_strategy::{ + ExecutionStrategy, FlashblocksBalExecutionStrategy, FlashblocksLegacyExecutionStrategy, + ValidationCtx, + }, + flashblock_validation_metrics::FlashblockValidationAttemptMetrics, + state_root_strategy::SyncStateRootStrategy, +}; + +use ValidationPath::{Parallel, Sequential}; + +const TX_GAS_LIMIT: u64 = 100_000; +const TRANSFER_GAS_USED: u64 = 21_000; +// The second transfer can declare 100,000 gas after the first has consumed 21,000. +const EXACT_GAS_BLOCK_LIMIT: u64 = TRANSFER_GAS_USED + TX_GAS_LIMIT; + +#[test] +fn rejects_insufficient_gas_within_one_flashblock() { + let provider = TestStateProvider::new(); + let transactions = two_transfers(); + let flashblock = build_flashblock(&provider, &transactions, None); + assert_eq!(flashblock.outcome.block.gas_used(), 2 * TRANSFER_GAS_USED); + let block_gas_limit = EXACT_GAS_BLOCK_LIMIT - 1; + + for path in [Sequential, Parallel] { + let error = validate( + &provider, + &flashblock, + block_gas_limit, + path, + initial_state(), + ) + .expect_err("the second transaction declares more gas than remains"); + assert_gas_limit_error(error, TX_GAS_LIMIT, TX_GAS_LIMIT - 1); + } +} + +#[test] +fn accepts_exact_gas_limit_within_one_flashblock() { + let provider = TestStateProvider::new(); + let transactions = two_transfers(); + let flashblock = build_flashblock(&provider, &transactions, None); + + for path in [Sequential, Parallel] { + validate( + &provider, + &flashblock, + EXACT_GAS_BLOCK_LIMIT, + path, + initial_state(), + ) + .expect("the second transaction's declared gas exactly fits the remaining budget"); + } +} + +#[test] +fn rejects_insufficient_gas_after_previous_flashblock() { + let provider = TestStateProvider::new(); + let transactions = two_transfers(); + let first = build_flashblock(&provider, &transactions[..1], None); + let second = build_flashblock(&provider, &transactions[1..], Some(&first)); + let block_gas_limit = EXACT_GAS_BLOCK_LIMIT - 1; + + for path in [Sequential, Parallel] { + let committed = commit_first_flashblock(&provider, &first, block_gas_limit, path); + let error = validate(&provider, &second, block_gas_limit, path, committed) + .expect_err("the previous flashblock leaves only 99,999 gas available"); + assert_gas_limit_error(error, TX_GAS_LIMIT, TX_GAS_LIMIT - 1); + } +} + +#[test] +fn accepts_exact_gas_limit_after_previous_flashblock() { + let provider = TestStateProvider::new(); + let transactions = two_transfers(); + let first = build_flashblock(&provider, &transactions[..1], None); + let second = build_flashblock(&provider, &transactions[1..], Some(&first)); + + for path in [Sequential, Parallel] { + let committed = commit_first_flashblock(&provider, &first, EXACT_GAS_BLOCK_LIMIT, path); + validate(&provider, &second, EXACT_GAS_BLOCK_LIMIT, path, committed) + .expect("the previous flashblock leaves exactly 100,000 gas available"); + } +} + +#[test] +fn rejects_insufficient_da_within_one_flashblock() { + let provider = provider_with_da_scalar(2000); + let transactions = two_transfers(); + let flashblock = build_flashblock(&provider, &transactions, None); + let total_da_footprint = flashblock + .outcome + .block + .blob_gas_used() + .expect("Jovian block"); + let block_gas_limit = total_da_footprint - 1; + assert!( + block_gas_limit >= EXACT_GAS_BLOCK_LIMIT, + "compute gas must fit" + ); + + for path in [Sequential, Parallel] { + let error = validate( + &provider, + &flashblock, + block_gas_limit, + path, + initial_state(), + ) + .expect_err("the two transactions exceed the DA budget by one"); + assert_da_limit_exceeded_by_one(error); + } +} + +#[test] +fn accepts_exact_da_limit_within_one_flashblock() { + let provider = provider_with_da_scalar(2000); + let transactions = two_transfers(); + let flashblock = build_flashblock(&provider, &transactions, None); + let block_gas_limit = flashblock + .outcome + .block + .blob_gas_used() + .expect("Jovian block"); + + for path in [Sequential, Parallel] { + validate( + &provider, + &flashblock, + block_gas_limit, + path, + initial_state(), + ) + .expect("the two transactions' total DA footprint exactly fits the block"); + } +} + +#[test] +fn rejects_insufficient_da_after_previous_flashblock() { + let provider = provider_with_da_scalar(2000); + let transactions = two_transfers(); + let first = build_flashblock(&provider, &transactions[..1], None); + let second = build_flashblock(&provider, &transactions[1..], Some(&first)); + let total_da_footprint = second.outcome.block.blob_gas_used().expect("Jovian block"); + let block_gas_limit = total_da_footprint - 1; + assert!( + block_gas_limit >= EXACT_GAS_BLOCK_LIMIT, + "compute gas must fit" + ); + + for path in [Sequential, Parallel] { + let committed = commit_first_flashblock(&provider, &first, block_gas_limit, path); + let error = validate(&provider, &second, block_gas_limit, path, committed) + .expect_err("the previous flashblock's DA usage must count toward the block budget"); + assert_da_limit_exceeded_by_one(error); + } +} + +#[test] +fn accepts_exact_da_limit_after_previous_flashblock() { + let provider = provider_with_da_scalar(2000); + let transactions = two_transfers(); + let first = build_flashblock(&provider, &transactions[..1], None); + let second = build_flashblock(&provider, &transactions[1..], Some(&first)); + let block_gas_limit = second.outcome.block.blob_gas_used().expect("Jovian block"); + + for path in [Sequential, Parallel] { + let committed = commit_first_flashblock(&provider, &first, block_gas_limit, path); + validate(&provider, &second, block_gas_limit, path, committed) + .expect("both flashblocks' total DA footprint exactly fits the block"); + } +} + +#[test] +fn uses_committed_pre_refund_gas_for_admission() { + let provider = TestStateProvider::new(); + let transactions = two_transfers(); + let first = build_flashblock(&provider, &transactions[..1], None); + let second = build_flashblock(&provider, &transactions[1..], Some(&first)); + + for path in [Sequential, Parallel] { + let mut committed = commit_first_flashblock(&provider, &first, EXACT_GAS_BLOCK_LIMIT, path); + // Model one gas of prior post-exec refund: receipt gas is 21,000, real compute is 21,001. + committed.evm_gas_used += 1; + assert_eq!(committed.gas_used, TRANSFER_GAS_USED); + assert_eq!(committed.evm_gas_used, TRANSFER_GAS_USED + 1); + + let error = validate(&provider, &second, EXACT_GAS_BLOCK_LIMIT, path, committed) + .expect_err("the pre-refund compute budget leaves only 99,999 gas available"); + assert_gas_limit_error(error, TX_GAS_LIMIT, TX_GAS_LIMIT - 1); + } +} + +#[derive(Clone, Copy, Debug)] +enum ValidationPath { + Sequential, + Parallel, +} + +struct FlashblockFixture { + outcome: BlockBuilderOutcome, + access_list_data: FlashblockAccessListData, + bundle: BundleState, + transactions: Vec>, +} + +fn two_transfers() -> [Recovered; 2] { + let transfer = TxOp::Transfer { + from: ALICE.clone(), + to: Address::repeat_byte(0x11), + value: U256::from(100), + }; + [ + transfer.to_signed_tx_with_gas_limit(0, TX_GAS_LIMIT), + transfer.to_signed_tx_with_gas_limit(1, TX_GAS_LIMIT), + ] +} + +fn build_flashblock( + provider: &TestStateProvider, + transactions: &[Recovered], + previous: Option<&FlashblockFixture>, +) -> FlashblockFixture { + let previous_outcome = + previous.map(|fixture| (fixture.outcome.clone(), fixture.bundle.clone())); + let (outcome, access_list_data, bundle) = + execute_serial_with_provider(provider, previous_outcome, transactions) + .expect("build reference flashblock with the fixture's generous gas limit"); + FlashblockFixture { + outcome, + access_list_data, + bundle, + transactions: transactions.to_vec(), + } +} + +fn initial_state() -> CommittedState { + CommittedState::try_from(None).expect("no previous flashblock") +} + +fn commit_first_flashblock( + provider: &TestStateProvider, + first: &FlashblockFixture, + block_gas_limit: u64, + path: ValidationPath, +) -> CommittedState { + let payload = validate(provider, first, block_gas_limit, path, initial_state()) + .expect("the first flashblock fits within the block budget"); + CommittedState::try_from(Some(&payload)).expect("state committed by the first flashblock") +} + +fn validate( + provider: &TestStateProvider, + fixture: &FlashblockFixture, + block_gas_limit: u64, + path: ValidationPath, + committed: CommittedState, +) -> Result { + // Change only the gas limit and matching block hash, preserve the reference execution's roots. + let mut header = fixture.outcome.block.header().clone(); + header.gas_limit = block_gas_limit; + let diff = ExecutionPayloadFlashblockDeltaV1 { + state_root: header.state_root, + receipts_root: header.receipts_root, + logs_bloom: header.logs_bloom, + gas_used: header.gas_used, + block_hash: header.hash_slow(), + transactions: fixture + .transactions + .iter() + .map(|tx| tx.encoded_2718().into()) + .collect(), + withdrawals: vec![], + withdrawals_root: header.withdrawals_root.unwrap_or_default(), + access_list_data: Some(fixture.access_list_data.clone()), + }; + let mut metrics = FlashblockValidationAttemptMetrics::default(); + let mut evm_env = EVM_ENV.clone(); + evm_env.block_env.gas_limit = block_gas_limit; + let ctx = ValidationCtx { + parent: &SEALED_HEADER, + attempt_metrics: &mut metrics, + chain_spec: CHAIN_SPEC.clone(), + evm_env, + execution_context: BLOCK_EXECUTION_CTX.clone(), + state_root_strategy: SyncStateRootStrategy, + }; + match path { + Sequential => FlashblocksLegacyExecutionStrategy.execute( + ctx, + provider.clone(), + diff, + committed, + PayloadId::default(), + ), + Parallel => FlashblocksBalExecutionStrategy.execute( + ctx, + provider.clone(), + diff, + committed, + PayloadId::default(), + ), + } +} + +fn provider_with_da_scalar(da_scalar: u16) -> TestStateProvider { + let mut genesis = GENESIS.clone(); + let account = genesis.alloc.entry(L1_BLOCK_CONTRACT).or_default(); + account.nonce = Some(1); + let mut scalar_slot = [0u8; 32]; + scalar_slot[DA_FOOTPRINT_GAS_SCALAR_OFFSET..DA_FOOTPRINT_GAS_SCALAR_OFFSET + 2] + .copy_from_slice(&da_scalar.to_be_bytes()); + account.storage.get_or_insert_with(Default::default).insert( + B256::from(DA_FOOTPRINT_GAS_SCALAR_SLOT), + B256::from(scalar_slot), + ); + TestStateProvider::from_genesis(&genesis) +} + +fn assert_gas_limit_error( + error: BalExecutorError, + expected_tx_gas: u64, + expected_remaining_gas: u64, +) { + let BalExecutorError::BlockExecutionError(BlockExecutionError::Validation( + BlockValidationError::TransactionGasLimitMoreThanAvailableBlockGas { + transaction_gas_limit, + block_available_gas, + }, + )) = error + else { + panic!("expected cumulative gas admission error: {error:?}"); + }; + assert_eq!(transaction_gas_limit, expected_tx_gas); + assert_eq!(block_available_gas, expected_remaining_gas); +} + +fn assert_da_limit_exceeded_by_one(error: BalExecutorError) { + let BalExecutorError::BlockExecutionError(BlockExecutionError::Validation( + BlockValidationError::Other(error), + )) = error + else { + panic!("expected cumulative DA admission error: {error:?}"); + }; + let Some(OpBlockExecutionError::TransactionDaFootprintAboveGasLimit { + transaction_da_footprint, + available_block_da_footprint, + }) = error.downcast_ref::() + else { + panic!("expected DA footprint error: {error:?}"); + }; + assert_eq!(*transaction_da_footprint, *available_block_da_footprint + 1); +} diff --git a/docs/proof/elf-management.md b/docs/proof/elf-management.md index 313a0d2fa..3f049568d 100644 --- a/docs/proof/elf-management.md +++ b/docs/proof/elf-management.md @@ -35,7 +35,7 @@ embedded bytes (`just proof-vkeys`), which is pinned in the `MultiProofGame` imp ## Reproducibility -`sp1_build::build_program_with_args` uses Docker by default with the SP1 v6.3.1 linux/amd64 +`sp1_build::build_program_with_args` uses Docker by default with the SP1 v6.8.1 linux/amd64 image pinned by digest. A `cargo build -p world-chain-prover-sp1` from a clean checkout therefore produces bit-for-bit identical ELFs and vkeys regardless of host toolchain. @@ -62,15 +62,15 @@ cargo build -p world-chain-proof-sp1-worker # likewise just proof-vkeys # prints the on-chain vkey commitments ``` -The first build runs each guest build inside the digest-pinned SP1 v6.3.1 image (a few minutes). +The first build runs each guest build inside the digest-pinned SP1 v6.8.1 image (a few minutes). Subsequent builds reuse the cached ELFs unless the guest source or SP1 image reference changes — `sp1-build` calls `cargo:rerun-if-changed` on every dependency of the program crate, so any meaningful source edit invalidates the cache. Requirements: -- Docker (default reproducibility mode pulls the digest-pinned `succinctlabs/sp1:v6.3.1`), or -- The SP1 toolchain on `PATH` (`curl -L https://sp1.succinct.xyz | bash && sp1up --version v6.3.1`) +- Docker (default reproducibility mode pulls the digest-pinned `ghcr.io/succinctlabs/sp1:v6.8.1`), or +- The SP1 toolchain on `PATH` (`curl -L https://sp1.succinct.xyz | bash && sp1up --version v6.8.1`) with `SP1_BUILD_DOCKER=false` for non-production iteration only. Build the production worker with its dedicated target: diff --git a/docs/review-policy.md b/docs/review-policy.md new file mode 100644 index 000000000..7276a48ad --- /dev/null +++ b/docs/review-policy.md @@ -0,0 +1,322 @@ +# Pull request review policy + +This policy reduces review work for code owners while retaining independent owner +review for other contributors. Risk and ownership are computed by GitHub Actions +from the target branch, not from labels or instructions in a PR. + +## Merge requirements + +By default, every PR to `main` needs all four checks and resolved review conversations: + +| Check | Requirement | +| --- | --- | +| `codex-review-gate` | Codex reviewed the current head, or posted a fresh thumbs-up. | +| `bugbot-review-gate` | Cursor Bugbot completed a review of the current head. | +| `human-review-gate` | The risk tier and file ownership requirements below are satisfied. | +| `required-ci-gate` | Every applicable CI workflow and required job succeeded. | + +Global code owners can explicitly bypass the AI review and build/test checks for +an emergency merge, as described below. Human confirmations and resolved review +threads remain required. + +All review threads must be resolved, including outdated threads and findings from +either bot. Fix the problem or explain why it is a false positive before resolving +the thread. A completed AI review can have findings: the separate native thread +resolution requirement keeps the PR blocked until they are addressed. + +## Risk tiers + +The ordered rules in `.github/review-policy.json` classify every changed path. Last +matching rule wins; unmatched paths are **important**. A PR takes the highest risk +of its paths. Renames include both names; deleted paths count too. + +| Tier | Areas | +| --- | --- | +| Critical | Dispute contracts; builder, chainspec, EVM, node, payload, primitives, validator; measured code; proof protocol, challenger, defender; measured build inputs, SP1 ELF building, release/governance scripts, workflows and review controls. | +| Important | CLI, commands, P2P, pool, RPC, node entrypoint; host backends, kona-host, workers and other proof services; other contracts; `proofs/measurements.json`; ordinary build/dependency configuration; protocol specifications and proof operating documentation. | +| Low | `crates/pbh/**`; descriptive documentation; explicitly listed test, benchmark, fixture and development directories. | + +Whole components include manifests and build scripts. Dedicated test/benchmark +directories can be low risk, but everything under `proofs/measured/**` stays +critical. Inline tests inherit their source file's tier. The root workspace +manifest is critical; the root lockfile is important. Measured lockfiles are +critical. The check summary identifies the paths setting the PR's risk. + +## Human confirmations + +Only a human author with repository write access who owns **every** changed path +can take the owner fast path. `CODEOWNERS` is read from the current target branch, +using GitHub's `.github/`, root, then `docs/` precedence and last matching pattern. +The global owner is `@worldcoin/protocol`; current team members own all files. + +| Risk | Author owns every path | Other authors | +| --- | --- | --- | +| Low | No human confirmation needed. | Owner approval covering the paths the author does not own. | +| Important | Author `/approve` or approval by a relevant owner. | Owner approval covering the paths the author does not own. | +| Critical | Two distinct humans: author `/approve` plus another owner, or two relevant owners. | Two distinct humans, with the necessary owner approvals; author `/approve` may count as one. | + +Post `/approve` as the entire body of a PR comment to confirm as the author. Post +`/unapprove` to revoke. Only the author, as a human collaborator with write access, +can use these commands. Other reviewers use GitHub's ordinary **Approve** review. +Quotes, code blocks, bot comments and embedded commands do not count. The latest +surviving author command wins; editing/deleting a command re-evaluates the state. + +Each human counts once. A relevant owner owns at least one changed path, including +the global fallback for unowned paths. Approvals must cover every path not owned +by the author. Files without owners fall back to the global `*` owners, and never +give the author a fast path. Without a global fallback they remain blocked. + +Approvals and author confirmation survive later pushes. A higher risk tier can require +an additional confirmation. Dismissed approvals do not count, and an active +**Request changes** review from an authorized human blocks the gate. An ordinary +comment review does not revoke an earlier approval. + +Owner usernames are case-insensitive. Protocol-team membership is fetched live on +each evidence read, including final verification after AI review. New PRs therefore +use the current roster without changing this repository or rerunning activation. +Open PRs pick up membership changes on their next gate evaluation; dispatch +**Review policy** with the PR number to refresh one immediately. A previous owner +approval stops counting if that reviewer is no longer an owner at reevaluation. +Unreadable membership fails closed with an explicit message. Unsupported +CODEOWNERS syntax is rejected instead of being guessed. + +### Team membership credential + +Provide the Actions secret `REVIEW_POLICY_TEAM_TOKEN` with read access to Worldcoin +organization **Members**. A fine-grained personal access token needs only this +organization permission; repository write or administration permission is not +needed. An organization secret must be explicitly available to `world-chain`. +The built-in `GITHUB_TOKEN` does not grant organization membership access. + +The controller uses a separate API client for team membership. Repository reads +and check publication continue to use the job's built-in token. Missing, expired +or unauthorized membership credentials block the gates rather than treating +contributors as owners. Team membership includes active members of child teams. + +When rotating this credential, update `REVIEW_POLICY_TEAM_TOKEN` at its existing +repository or organization scope, preserving any organization-secret repository +access policy. Rerun **Review policy** for an open PR and confirm its gate summary +evaluates team ownership without a membership configuration error. For an +organization secret, also verify its other consumers before revoking the previous +token. + +To request that re-evaluation without pushing a commit, run: + +```bash +gh workflow run review-policy.yml --repo worldcoin/world-chain --ref main -f pr=NUMBER +``` + +Replace `NUMBER` with the open PR number. The controller runs from trusted `main`. + +## AI completion and CI + +The author enables **Automatic review / All PRs** and the every-push trigger in +Codex settings. Bugbot must also run on every push; personal once-per-PR or manual +overrides cannot satisfy the gate for a later head. + +Codex's formal review must reference the current SHA. If there are no findings, +Codex can instead react to the PR with a thumbs-up. Reactions have no commit SHA, +so the gate accepts only a Codex thumbs-up created at or after its first observation +of this head. A neutral `review-policy-observed` check persists that timestamp +across retries. The known heuristic limitation is a delayed thumbs-up for an old +head arriving after a new push; this tradeoff is intentional for v1. + +Bugbot must publish `Cursor Bugbot` from the Cursor app on the current SHA. A +successful check counts. A neutral check counts with Bugbot's matching formal +completion review posted after that run began, or when Cursor explicitly reports +`Bugbot skipped this commit because its changes match the last review.` in the +check's result text. This attestation on the current SHA lets Bugbot reuse a review +after a rebase with an unchanged patch; the controller trusts Cursor's comparison +rather than treating a review on an older SHA alone as sufficient. Only the latest +Cursor check counts. An absent, running, cancelled, failed or ambiguous result does +not pass. Resolving a finding does not need to turn the original check green if a +completed review was established. Review threads still require resolution when +Bugbot reuses a review. + +The controller polls for AI completion every 60 seconds for up to 30 minutes of +active evaluation, excluding waits imposed by GitHub API rate limits. +Timeout fails the AI gate; rerun **Review policy**, or dispatch it with the PR +number. A later formal review or Cursor check event also re-evaluates the gate. +Reactions have no dedicated Actions trigger: a thumbs-up arriving after polling +ends requires a manual rerun. While polling is active, a thumbs-up can wait up to +one polling interval plus API latency to be detected. Human commands, formal reviews +and CI completion trigger evaluations without waiting for that interval. + +CI requirements are also selected from the trusted configuration. The gate checks +the expected workflow ID, current head, PR association and the latest attempt's +individual job results. A skipped job, cancelled workflow or missing required run +cannot pass. Non-applicable workflows are excluded explicitly, not accepted merely +because a job was skipped. Measured changes also require the existing dependency +audit; all PRs require policy tests and the large-file check. + +## Execution and recovery + +The privileged controller checks out only an immutable commit of `main`. It never +executes PR code or reads artifacts from untrusted workflows. A separate unprivileged +review-event notifier wakes the controller; the controller reads live API state. +Its token has checks and commit-status write access and read access to repository +metadata, PRs, issues and Actions. The separate membership client uses `REVIEW_POLICY_TEAM_TOKEN` only for +read-only team lookups. No OpenAI API key is needed. + +PR events run only the short `request-review-policy` job, which dispatches the +controller on trusted `main` without checking out PR code. The cancellable +`evaluate` job belongs to that background run; its four published commit statuses +determine the review-policy outcome on the PR. New events still supersede older +evaluations immediately. Superseded runs remain cancelled in Actions history, +while the PR's launcher job completes successfully; actual gate failures remain +visible and keep their normal merge requirements. + +Each gate publishes a commit status with its existing required context and a link +to its diagnostic check. GitHub excludes checks from some background workflow +events from required-check evaluation; commit statuses report the same verified +outcomes independently of that workflow-job restriction. The required source +remains GitHub Actions. Diagnostic checks retain the full evidence and also stay +in sync, since GitHub requires both to pass when a status and check share a name. +See [GitHub's required-check troubleshooting](https://docs.github.com/en/pull-requests/how-tos/merge-and-close-pull-requests/troubleshooting-required-status-checks#checks-from-some-workflow-jobs-are-not-evaluated). + +CI completion wakes the controller. Initial CI start events do not restart an +evaluation already launched by the PR event; a rerun's start still wakes it so a +previous successful CI result can be invalidated immediately. Review-event notifier +completion, author commands and Cursor events retain their existing behavior. + +An ordinary merge to `main` does not re-evaluate other open PRs. The push handler +compares Git object identities for the three supported CODEOWNERS locations, +`.github/review-policy.json`, `scripts/review-policy/`, `.github/workflows/` and +`.github/actions/`. Only changes to these controls refresh all open PRs, retaining +normal AI polling so an ongoing review can still complete after a policy update. +Git trees are read without recursion, including additions and deletions, and +incomplete reads fail closed. + +An evaluation already running can continue across ordinary merges to `main` when +these controls are unchanged. It still stops on a changed PR head, target branch, +or review policy. Immutable Git trees and policy fingerprints are cached within +the run, so repeated identity checks do not repeat those API reads. A normal main +push therefore runs only the short target-discovery job, with no evaluator matrix. + +API requests are serialized and use conditional GETs when GitHub supplies an ETag. +Cached data is reused only after GitHub confirms it is unchanged with HTTP 304; +these authenticated responses do not consume the primary API quota. Human approval, +permission and team membership reads still contact GitHub each time. The second +human verification reads only human evidence, without duplicating AI/CI queries. +Completed CI jobs are reused within an evaluation only while the run ID, attempt, +update timestamp and conclusion match; the workflow run itself is always rechecked. +See [GitHub's API recommendations](https://docs.github.com/en/rest/using-the-rest-api/best-practices-for-using-the-rest-api). + +On a rate-limit response, the controller stops requests, logs when it will resume, +and waits for `Retry-After` or the quota reset (with bounded exponential backoff for +secondary limits). It then restarts from current PR, policy and review evidence; +it never retries a previously computed successful result after the wait. Recovery +allows three retries and at most 65 minutes of quota waiting, without resetting +the 30-minute AI budget. The evaluator job allows 105 minutes including recovery. +If the recovery budget is exhausted, the workflow fails with a rerun instruction. +GitHub may still reject check updates while its quota is exhausted, leaving a gate +pending until a later evaluation. Missing permissions and invalid credentials do +not receive quota retries. + +PRs that modify, delete or rename `.github/workflows/review-policy-events.yml` +fail the gates because review events use the PR's version of that workflow. +Updating the notifier requires a controlled migration with native review protection +enabled, so pending PRs cannot disable approval revocations. + +Checks are posted on the PR head explicitly. Each PR is serialized, and the head, +target branch and policy identity are rechecked before publishing. Every poll +rereads AI results, human confirmations, permissions and CI results. Human clearance +requires two consecutive snapshots with the same fingerprint of human review decisions, the +author's approval command state, permissions, ownership, risk and commit identity. +The verified human fingerprint is recorded in the check summary. AI/CI progress, +reactions, review body edits and ordinary discussion do not invalidate it. A revoked +author confirmation, dismissed approval or failed CI rerun during the AI wait still +blocks its corresponding gate. Repeatedly changing human evidence fails closed +and requires a rerun. GitHub API reads and check publication are not atomic; later +events trigger a new evaluation. + +Every evaluation creates fresh pending gates and updates older duplicates to the +same outcome. Pending and failed commit statuses are written before diagnostic +check updates; success is written only after those updates and a fresh check of +the head, target policy and absence of a newer evaluation. Unchanged statuses +are not reposted during polling. Old successful checks cannot survive a revoked +author confirmation or remain green while a fresh evaluation is waiting for evidence. Historical checks are only +written when their status or conclusion changes; the newest checks carry the +current complete summary. +The target SHA is resolved from the branch API because the PR API can retain an +older base SHA after `main` advances. + +Multiple open PRs targeting `main` with the same +head SHA are blocked because commit checks could otherwise share human decisions. +Close duplicates and rerun. PRs exceeding GitHub's 3000-file API limit must be split. +Pushes to `main` re-evaluate open PRs against current ownership and policy. + +Auto-merge remains opt-in and uses the repository's existing squash-only setting. +This change does not introduce a merge queue. + +## Emergency CI override + +Global code owners can explicitly bypass build/test CI and the Codex and Bugbot +completion checks when a pipeline or reviewer is broken or unavailable. In the PR +merge box, select GitHub's bypass option and confirm the squash merge. This is a +manual merge action; failing or pending checks stay visible and no result is +changed to success. There is no automatic fallback during an outage: an AI review +without a completion signal times out after 30 minutes and can be rerun or +explicitly bypassed. The risk-based human confirmations and resolution of all +review threads remain mandatory. Socket and other independent protections still +apply. + +Human clearance is verified independently of AI completion and refreshed during +the wait, so revocations and review changes still block an emergency merge. + +The activation script installs two rulesets on `main`: + +- `world-chain-review-policy` requires `human-review-gate` and resolved threads, + with no bypass actors. +- `world-chain-ci-policy` requires `required-ci-gate`, `codex-review-gate` and + `bugbot-review-gate`. Its bypass list contains `@worldcoin/protocol` as a native + **Team** actor, using GitHub's **For pull requests only** mode. The same explicit + bypass covers all three checks; it does not grant direct pushes to `main`. + +The script derives the actor from the last global `*` rule on the trusted `main`. +It verifies that an owner team belongs to the repository's organization, is visible +and has repository write access. It stores the team ID, without copying members. +Joining or leaving the protocol team automatically updates native CI bypass +access; no activation rerun is needed for membership changes. Changing which team +is the global owner still requires activation to bind the new team ID. + +## Rollout and rollback + +1. Land the workflows through the existing review process. Do not relax protection + before the trusted controller is on `main`. +2. Configure `REVIEW_POLICY_TEAM_TOKEN`, then enable Codex automatic review for all + PRs/every push. Observe all four checks on real PRs, including protocol membership, + an author confirmation and bot findings resolved as threads. +3. Save a fresh snapshot outside the checkout: + `node scripts/review-policy/admin.cjs snapshot --backup /tmp/world-chain-review-before.json`. +4. Validate readiness without changing GitHub: + `node scripts/review-policy/admin.cjs activate --backup /tmp/world-chain-review-before.json --evidence-pr NUMBER`. +5. Run the same activation command with `--apply` only after readiness passes. It + first installs the CI and AI ruleset with owner-only PR bypass, then the human + review and thread ruleset without bypass, and verifies both before removing the + blanket approval/code-owner requirement. Existing Socket and unrelated rules + are retained. + +Activation verifies the deployed files match the local implementation and requires +a real PR whose four gate checks and matching GitHub Actions commit statuses +succeeded. Each status must link to its corresponding diagnostic check. Evidence +may refer to an older `main` commit only if its trusted policy inputs are identical to current `main`, using +the same Git-tree comparison as the evaluator. Missing or invalid evidence commit +identities, changed policy and unreadable trees block activation. The final check +that `main` stayed unchanged during activation still applies. + +The required checks accept GitHub Actions as their source. Only the CI ruleset +permits bypass, and only for the verified global owner team. Automatic +stale-review dismissal and last-push +approval stay disabled. + +For rollback, run +`node scripts/review-policy/admin.cjs restore --backup /tmp/world-chain-review-before.json` +to inspect the operation, then add `--apply`. Restoration reinstates the old native +review requirements **before** removing/restoring the review-policy and CI-policy +rulesets, including any previous bypass configuration. +Snapshots are never overwritten. Treat a partial activation as blocked, inspect the +error, and use the snapshot to restore. + +Run the local tests with `node --test scripts/review-policy/*.test.cjs`. Policy CI +also runs actionlint against the controller, notifier, tests and affected CI. diff --git a/e2e-tests/e2e-withdrawal/Cargo.toml b/e2e-tests/e2e-withdrawal/Cargo.toml new file mode 100644 index 000000000..41611fb06 --- /dev/null +++ b/e2e-tests/e2e-withdrawal/Cargo.toml @@ -0,0 +1,51 @@ +[package] +name = "e2e-withdrawal" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +homepage.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[dependencies] +# alloy +alloy-primitives.workspace = true +alloy-provider = { workspace = true, features = ["reqwest", "reqwest-rustls-tls"] } +alloy-signer-local.workspace = true +alloy-signer-aws.workspace = true +alloy-network.workspace = true +alloy-sol-types.workspace = true +alloy-contract.workspace = true +alloy-eips.workspace = true +alloy-consensus.workspace = true +alloy-rpc-types.workspace = true +alloy-json-rpc.workspace = true +alloy-rpc-client.workspace = true +alloy-transport-http = { workspace = true, features = ["reqwest"] } + +# aws +aws-config.workspace = true +aws-credential-types.workspace = true +aws-sdk-s3.workspace = true +aws-sdk-kms.workspace = true + +# misc +async-trait.workspace = true +backoff.workspace = true +reqwest = { version = "0.13", default-features = false } +clap.workspace = true +eyre.workspace = true +tokio.workspace = true +serde.workspace = true +serde_json.workspace = true +tracing.workspace = true +tracing-subscriber = { workspace = true, features = ["json"] } +thiserror.workspace = true +tower.workspace = true + +[dev-dependencies] +tempfile.workspace = true +tokio = { workspace = true, features = ["test-util"] } diff --git a/e2e-tests/e2e-withdrawal/src/args.rs b/e2e-tests/e2e-withdrawal/src/args.rs new file mode 100644 index 000000000..809c101c4 --- /dev/null +++ b/e2e-tests/e2e-withdrawal/src/args.rs @@ -0,0 +1,297 @@ +use crate::{signer, types::StepError}; +use alloy_primitives::{Address, U256, utils::parse_ether}; +use clap::Args; +use std::path::{Component, Path, PathBuf}; + +/// Arguments for the L1. +#[derive(Debug, Args, Clone)] +#[command(group(clap::ArgGroup::new("l1_signer").required(true).multiple(false).args(["l1_private_key", "l1_aws_kms_key_id"])))] +pub struct L1Args { + /// L1 rpc endpoint url. + #[arg(long, env = "L1_RPC_ENDPOINT")] + pub l1_rpc_endpoint: String, + /// L1 private key. + #[arg(long, env = "L1_PRIVATE_KEY")] + pub l1_private_key: Option, + /// L1 AWS KMS Ethereum signing key ID, ARN or alias. + #[arg(long, env = "L1_AWS_KMS_KEY_ID")] + pub l1_aws_kms_key_id: Option, +} + +/// Arguments for the `init` command. +#[derive(Debug, Args)] +#[command(group(clap::ArgGroup::new("l2_signer").required(true).multiple(false).args(["l2_private_key", "l2_aws_kms_key_id"])))] +pub struct InitArgs { + /// L2 rpc endpoint url. + #[arg(long, env = "L2_RPC_ENDPOINT")] + pub l2_rpc_endpoint: String, + /// L2 private key. + #[arg(long, env = "L2_PRIVATE_KEY")] + pub l2_private_key: Option, + /// L2 AWS KMS Ethereum signing key ID, ARN or alias. + #[arg(long, env = "L2_AWS_KMS_KEY_ID")] + pub l2_aws_kms_key_id: Option, + /// The amount of ETH you want to withdraw. + #[arg(long, env = "ETH_VALUE", value_parser = parse_ether, default_value_t = U256::ZERO)] + pub value: U256, + /// Location for the initiated withdrawal JSON (local path or `s3://bucket/key`). + #[arg( + long, + env = "WITHDRAWAL_INITIATED", + default_value = "initiated_withdrawal.json" + )] + pub initiated: String, +} + +/// Arguments for the `prove` command. +#[derive(Debug, Args)] +pub struct ProveArgs { + /// L1 args. + #[command(flatten)] + pub l1_args: L1Args, + /// L2 rpc endpoint url. + #[arg(long, env = "L2_RPC_ENDPOINT")] + pub l2_rpc_endpoint: String, + /// DisputeGameFactory contract address. + #[arg(long, env = "DISPUTE_GAME_FACTORY")] + pub dispute_game_factory: Address, + /// OptimismPortal contract address. + #[arg(long, env = "OPTIMISM_PORTAL")] + pub optimism_portal: Address, + /// Location for the initiated withdrawal JSON (local path or `s3://bucket/key`). + #[arg( + long, + env = "WITHDRAWAL_INITIATED", + default_value = "initiated_withdrawal.json" + )] + pub initiated: String, + /// Location for the proven withdrawal JSON (local path or `s3://bucket/key`). + #[arg( + long, + env = "WITHDRAWAL_PROVEN", + default_value = "prove_withdrawal.json" + )] + pub proven: String, +} + +/// Arguments for the `finalize` command. +#[derive(Debug, Args)] +pub struct FinalizeArgs { + /// L1 args. + #[command(flatten)] + pub l1_args: L1Args, + /// AnchorStateRegistry contract address. + #[arg(long, env = "ANCHOR_STATE_REGISTRY")] + pub anchor_state_registry: Address, + /// OptimismPortal contract address. + #[arg(long, env = "OPTIMISM_PORTAL")] + pub optimism_portal: Address, + /// Location for the proven withdrawal JSON (local path or `s3://bucket/key`). + #[arg( + long, + env = "WITHDRAWAL_PROVEN", + default_value = "prove_withdrawal.json" + )] + pub proven: String, +} + +/// Arguments for the `step` command. +#[derive(Debug, Args)] +#[command(group(clap::ArgGroup::new("l2_signer").required(true).multiple(false).args(["l2_private_key", "l2_aws_kms_key_id"])))] +pub struct StepArgs { + /// L1 args. + #[command(flatten)] + pub l1_args: L1Args, + /// L2 rpc endpoint url. + #[arg(long, env = "L2_RPC_ENDPOINT")] + pub l2_rpc_endpoint: String, + /// L2 private key. + #[arg(long, env = "L2_PRIVATE_KEY")] + pub l2_private_key: Option, + /// L2 AWS KMS Ethereum signing key ID, ARN or alias. + #[arg(long, env = "L2_AWS_KMS_KEY_ID")] + pub l2_aws_kms_key_id: Option, + /// The amount of ETH you want to withdraw. + #[arg(long, env = "ETH_VALUE", value_parser = parse_ether, default_value_t = U256::ZERO)] + pub value: U256, + /// DisputeGameFactory contract address. + #[arg(long, env = "DISPUTE_GAME_FACTORY")] + pub dispute_game_factory: Address, + /// OptimismPortal contract address. + #[arg(long, env = "OPTIMISM_PORTAL")] + pub optimism_portal: Address, + /// AnchorStateRegistry contract address. + #[arg(long, env = "ANCHOR_STATE_REGISTRY")] + pub anchor_state_registry: Address, + /// Durable location for the initiated-withdrawal JSON. + #[arg( + long, + env = "WITHDRAWAL_INITIATED", + default_value = "initiated_withdrawal.json" + )] + pub initiated: String, + /// Durable location for the proven-withdrawal JSON. + #[arg( + long, + env = "WITHDRAWAL_PROVEN", + default_value = "prove_withdrawal.json" + )] + pub proven: String, +} + +impl StepArgs { + /// Validate the complete workflow before any transaction is submitted. + pub fn validate(&self) -> Result<(), StepError> { + self.l1_args.validate()?; + signer::validate( + self.l2_private_key.as_deref(), + self.l2_aws_kms_key_id.as_deref(), + "L2_PRIVATE_KEY or L2_AWS_KMS_KEY_ID (exactly one)", + )?; + rpc_url(&self.l2_rpc_endpoint, "L2_RPC_ENDPOINT")?; + validate_handoffs(&self.initiated, &self.proven) + } + + /// Convert into `InitArgs` + pub fn to_init(&self) -> InitArgs { + InitArgs { + l2_rpc_endpoint: self.l2_rpc_endpoint.clone(), + l2_private_key: self.l2_private_key.clone(), + l2_aws_kms_key_id: self.l2_aws_kms_key_id.clone(), + value: self.value, + initiated: self.initiated.clone(), + } + } + + /// Convert into `ProveArgs` + pub fn to_prove(&self) -> ProveArgs { + ProveArgs { + l1_args: self.l1_args.clone(), + l2_rpc_endpoint: self.l2_rpc_endpoint.clone(), + dispute_game_factory: self.dispute_game_factory, + optimism_portal: self.optimism_portal, + initiated: self.initiated.clone(), + proven: self.proven.clone(), + } + } + + /// Convert into `FinalizeArgs` + pub fn to_finalize(&self) -> FinalizeArgs { + FinalizeArgs { + l1_args: self.l1_args.clone(), + anchor_state_registry: self.anchor_state_registry, + optimism_portal: self.optimism_portal, + proven: self.proven.clone(), + } + } +} + +impl L1Args { + fn validate(&self) -> Result<(), StepError> { + signer::validate( + self.l1_private_key.as_deref(), + self.l1_aws_kms_key_id.as_deref(), + "L1_PRIVATE_KEY or L1_AWS_KMS_KEY_ID (exactly one)", + )?; + rpc_url(&self.l1_rpc_endpoint, "L1_RPC_ENDPOINT")?; + Ok(()) + } +} + +impl InitArgs { + pub fn validate(&self) -> Result<(), StepError> { + signer::validate( + self.l2_private_key.as_deref(), + self.l2_aws_kms_key_id.as_deref(), + "L2_PRIVATE_KEY or L2_AWS_KMS_KEY_ID (exactly one)", + )?; + rpc_url(&self.l2_rpc_endpoint, "L2_RPC_ENDPOINT")?; + handoff_identity(&self.initiated, "WITHDRAWAL_INITIATED")?; + Ok(()) + } +} + +impl ProveArgs { + pub fn validate(&self) -> Result<(), StepError> { + self.l1_args.validate()?; + rpc_url(&self.l2_rpc_endpoint, "L2_RPC_ENDPOINT")?; + validate_handoffs(&self.initiated, &self.proven) + } +} + +impl FinalizeArgs { + pub fn validate(&self) -> Result<(), StepError> { + self.l1_args.validate()?; + handoff_identity(&self.proven, "WITHDRAWAL_PROVEN")?; + Ok(()) + } +} + +/// Parse only supported HTTP(S) endpoints without exposing credentials in errors. +pub fn rpc_url(value: &str, field: &'static str) -> Result { + let url = reqwest::Url::parse(value).map_err(|_| StepError::InvalidConfiguration { field })?; + if !matches!(url.scheme(), "http" | "https") || url.host_str().is_none() { + return Err(StepError::InvalidConfiguration { field }); + } + Ok(url) +} + +fn validate_handoffs(initiated: &str, proven: &str) -> Result<(), StepError> { + if handoff_identity(initiated, "WITHDRAWAL_INITIATED")? + == handoff_identity(proven, "WITHDRAWAL_PROVEN")? + { + return Err(StepError::InvalidConfiguration { + field: "WITHDRAWAL_INITIATED and WITHDRAWAL_PROVEN must be distinct", + }); + } + Ok(()) +} + +#[derive(PartialEq)] +enum HandoffIdentity { + S3(String), + Local(PathBuf), +} + +fn handoff_identity(value: &str, field: &'static str) -> Result { + let invalid = || StepError::InvalidConfiguration { field }; + if let Some(rest) = value.strip_prefix("s3://") { + let (bucket, key) = rest.split_once('/').ok_or_else(invalid)?; + if bucket.is_empty() || key.is_empty() { + return Err(invalid()); + } + // S3 keys are literal: do not normalize their slashes or dot segments. + return Ok(HandoffIdentity::S3(value.to_owned())); + } + if value.trim().is_empty() || value.contains("://") || value.contains('\0') { + return Err(invalid()); + } + let path = Path::new(value); + let mut resolved = if path.is_absolute() { + PathBuf::new() + } else { + std::env::current_dir().map_err(|_| invalid())? + }; + // Resolve existing ancestors as well as lexical aliases for not-yet-created + // handoffs, so ./file and symlinked parents cannot hide a collision. + for component in path.components() { + match component { + Component::CurDir => {} + Component::ParentDir => { + resolved.pop(); + } + other => { + resolved.push(other.as_os_str()); + match resolved.canonicalize() { + Ok(canonical) => resolved = canonical, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(_) => return Err(invalid()), + } + } + } + } + if resolved.file_name().is_none() || resolved.is_dir() { + return Err(invalid()); + } + Ok(HandoffIdentity::Local(resolved)) +} diff --git a/e2e-tests/e2e-withdrawal/src/bindings.rs b/e2e-tests/e2e-withdrawal/src/bindings.rs new file mode 100644 index 000000000..8d514d881 --- /dev/null +++ b/e2e-tests/e2e-withdrawal/src/bindings.rs @@ -0,0 +1,193 @@ +use alloy_primitives::{Address, B256}; +use alloy_sol_types::sol; +use serde::{Deserialize, Serialize}; + +sol! { + #[derive(Debug, Serialize, Deserialize)] + struct WithdrawalTransaction { + uint256 nonce; + address sender; + address target; + uint256 value; + uint256 gasLimit; + bytes data; + } + + struct OutputRootProof { + bytes32 version; + bytes32 stateRoot; + bytes32 messagePasserStorageRoot; + bytes32 latestBlockhash; + } + + #[sol(rpc)] + interface L2ToL1MessagePasser { + event MessagePassed( + uint256 indexed nonce, + address indexed sender, + address indexed target, + uint256 value, + uint256 gasLimit, + bytes data, + bytes32 withdrawalHash + ); + + function initiateWithdrawal(address target, uint256 gasLimit, bytes data) external payable; + } + + #[sol(rpc)] + interface OptimismPortal { + function anchorStateRegistry() external view returns (address); + function disputeGameFactory() external view returns (address); + function disputeGameFinalityDelaySeconds() external view returns (uint256); + function proofMaturityDelaySeconds() external view returns (uint256); + function version() external view returns (string); + function proveWithdrawalTransaction( + WithdrawalTransaction tx_, + uint256 disputeGameIndex, + OutputRootProof outputRootProof, + bytes[] withdrawalProof + ) external; + function finalizeWithdrawalTransaction(WithdrawalTransaction tx_) external; + function finalizedWithdrawals(bytes32 withdrawalHash) external view returns (bool); + } + + interface IDisputeGame {} + + #[sol(rpc)] + interface AnchorStateRegistry { + function isGameClaimValid(IDisputeGame _game) public view returns (bool); + function paused() external view returns (bool); + function isGameRegistered(IDisputeGame _game) external view returns (bool); + function isGameBlacklisted(IDisputeGame _game) external view returns (bool); + function isGameRetired(IDisputeGame _game) external view returns (bool); + function isGameRespected(IDisputeGame _game) external view returns (bool); + function isGameFinalized(IDisputeGame _game) external view returns (bool); + } + + #[sol(rpc)] + interface IDisputeGameFactory { + event DisputeGameCreated(address indexed disputeProxy, uint32 indexed gameType, bytes32 indexed rootClaim); + + function create(uint32 gameType, bytes32 rootClaim, bytes calldata extraData) + external + payable + returns (address proxy); + function games(uint32 gameType, bytes32 rootClaim, bytes calldata extraData) + external + view + returns (address proxy, uint64 timestamp); + function gameAtIndex(uint256 index) + external + view + returns (uint32 gameType, uint64 timestamp, address proxy); + function gameCount() external view returns (uint256 gameCount); + function gameImpls(uint32 gameType) external view returns (address impl); + function initBonds(uint32 gameType) external view returns (uint256 bond); + function getGameUUID(uint32 gameType, bytes32 rootClaim, bytes calldata extraData) + external + pure + returns (bytes32 uuid); + } + + #[sol(rpc)] + interface IMultiProofGame { + event Challenged(address indexed challenger, uint64 proofDeadline); + event Proved(uint8 indexed lane, bytes32 indexed rootId, address recipient, uint8 proofBitmap); + event GameClosed(uint8 bondDistributionMode); + event Resolved(uint8 indexed status); + + // Reverts reachable from `submitProofLane`. Declared so a failed submission can be + // classified instead of retried blindly. + error ClaimAlreadyResolved(); + error InvalidParentGame(); + error GameOver(); + error InvalidLane(uint8 lane); + error InvalidProof(uint8 lane, bytes32 rootId); + error DuplicateProofLane(uint8 lane, bytes32 rootId, uint8 proofBitmap); + + // Deployment parameters (immutables on the implementation). + function PROOF_THRESHOLD() external view returns (uint8); + function PROOF_LANE_COUNT() external view returns (uint8); + function domainHash() external view returns (bytes32); + function rollupConfigHash() external view returns (bytes32); + function aggregationVKey() external view returns (bytes32); + function rangeVKeyCommitment() external view returns (bytes32); + function teeImageId() external view returns (bytes32); + function blockInterval() external view returns (uint256); + function challengePeriod() external view returns (uint64); + function proofPeriod() external view returns (uint64); + function proposerBond() external view returns (uint256); + function challengerBond() external view returns (uint256); + function protocolFeeRecipient() external view returns (address); + function disputeGameFactory() external view returns (address); + function anchorStateRegistry() external view returns (address); + function bondVault() external view returns (address); + + // Proposal context. + function rootId() external view returns (bytes32); + function proposalDomainHash() external view returns (bytes32); + function attempt() external view returns (uint256); + function parentRef() external view returns (address); + function startingRootHash() external view returns (bytes32); + function startingBlockNumber() external view returns (uint256); + function l2SequenceNumber() external view returns (uint256); + function l1Head() external view returns (bytes32); + function l1OriginNumber() external view returns (uint256); + function rootClaim() external view returns (bytes32); + function gameCreator() external view returns (address); + function gameType() external view returns (uint32); + function extraData() external view returns (bytes memory); + function wasRespectedGameTypeWhenCreated() external view returns (bool); + + // Game progress. `claimData` follows the `ZKDisputeGame.ProposalStatus` state machine. + function createdAt() external view returns (uint64); + function resolvedAt() external view returns (uint64); + function status() external view returns (uint8); + function claimData() + external + view + returns (uint8 status, address challenger, uint64 deadline, uint8 proofBitmap, uint8 invalidationReason); + function invalidationReason() external view returns (uint8); + function proofBitmap() external view returns (uint8); + function laneRecipient(uint8 laneId) external view returns (address); + function challenger() external view returns (address); + function challengeDeadline() external view returns (uint64); + function proofDeadline() external view returns (uint64); + function gameOver() external view returns (bool); + function resolutionStatus() + external + view + returns (bool resolvable, uint8 outcome, uint8 reason); + + // Mutating entry points. + function challenge() external returns (uint8 proposalStatus); + /// `proof` is the compact payload built by `encode_compact_proof`. + function submitProofLane(bytes calldata proof) external returns (uint8 proposalStatus); + function resolve() external returns (uint8 status); + function closeGame() external; + + // Bond settlement. + function bondDistributionMode() external view returns (uint8); + function totalBonds() external view returns (uint256); + function normalModeCredit(address recipient) external view returns (uint256); + function refundModeCredit(address recipient) external view returns (uint256); + } +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct InitiatedWithdrawal { + pub transaction: WithdrawalTransaction, + pub hash: B256, + pub l2_block: u64, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct ProveWithdrawal { + pub transaction: WithdrawalTransaction, + pub hash: B256, + pub game_index: u64, + pub game_l2_block: u64, + pub game_addr: Address, + pub proven_at: u64, +} diff --git a/e2e-tests/e2e-withdrawal/src/cli.rs b/e2e-tests/e2e-withdrawal/src/cli.rs new file mode 100644 index 000000000..fe96185c6 --- /dev/null +++ b/e2e-tests/e2e-withdrawal/src/cli.rs @@ -0,0 +1,20 @@ +use crate::{ + cmd::Command, + types::{StepError, StepOutcome}, +}; +use clap::Parser; + +/// Cli struct for the alphanet-withdrawal binary. +#[derive(Debug, Parser)] +pub struct Cli { + /// The command to run. + #[command(subcommand)] + command: Command, +} + +impl Cli { + /// Run the cli binary to completion. + pub async fn run(&self) -> Result { + self.command.run().await + } +} diff --git a/e2e-tests/e2e-withdrawal/src/clients.rs b/e2e-tests/e2e-withdrawal/src/clients.rs new file mode 100644 index 000000000..1e486b771 --- /dev/null +++ b/e2e-tests/e2e-withdrawal/src/clients.rs @@ -0,0 +1,98 @@ +//! Shared L1/L2 providers for withdrawal workflow commands. + +use crate::{args::StepArgs, rpc, signer, types::StepError}; +use alloy_network::EthereumWallet; +use alloy_primitives::Address; +use alloy_provider::{DynProvider, Provider, ProviderBuilder}; + +/// Wallet-backed L1 and L2 providers reused across workflow ticks. +pub struct Clients { + /// L1 provider. + pub l1: DynProvider, + /// L2 provider. + pub l2: DynProvider, + /// Default signer address for the L2 wallet (needed by init). + pub l2_address: Address, +} + +impl Clients { + /// Build both chain providers from step/run arguments. + pub async fn from_step_args(args: &StepArgs) -> Result { + let l1 = l1_provider( + args.l1_args.l1_private_key.as_deref(), + args.l1_args.l1_aws_kms_key_id.as_deref(), + &args.l1_args.l1_rpc_endpoint, + ) + .await?; + let (l2, l2_address) = l2_provider( + args.l2_private_key.as_deref(), + args.l2_aws_kms_key_id.as_deref(), + &args.l2_rpc_endpoint, + ) + .await?; + Ok(Self { l1, l2, l2_address }) + } +} + +/// Build a wallet-backed L1 provider. +pub async fn l1_provider( + private_key: Option<&str>, + kms_key_id: Option<&str>, + endpoint: &str, +) -> Result { + signed_provider( + private_key, + kms_key_id, + endpoint, + "L1_RPC_ENDPOINT", + "L1_PRIVATE_KEY or L1_AWS_KMS_KEY_ID (exactly one)", + ) + .await + .map(|(provider, _)| provider) +} + +/// Build a wallet-backed L2 provider and its default signer address. +pub async fn l2_provider( + private_key: Option<&str>, + kms_key_id: Option<&str>, + endpoint: &str, +) -> Result<(DynProvider, Address), StepError> { + signed_provider( + private_key, + kms_key_id, + endpoint, + "L2_RPC_ENDPOINT", + "L2_PRIVATE_KEY or L2_AWS_KMS_KEY_ID (exactly one)", + ) + .await +} + +/// Build a read-only L2 provider (no signer). +pub fn l2_read_provider(endpoint: &str) -> Result { + Ok(ProviderBuilder::new() + .connect_client(rpc::client(endpoint, "L2_RPC_ENDPOINT")?) + .erased()) +} + +async fn signed_provider( + private_key: Option<&str>, + kms_key_id: Option<&str>, + endpoint: &str, + rpc_field: &'static str, + signer_field: &'static str, +) -> Result<(DynProvider, Address), StepError> { + let wallet = signer::wallet(private_key, kms_key_id, endpoint, rpc_field, signer_field).await?; + let address = wallet.default_signer().address(); + Ok((provider_with_wallet(wallet, endpoint, rpc_field)?, address)) +} + +fn provider_with_wallet( + wallet: EthereumWallet, + endpoint: &str, + rpc_field: &'static str, +) -> Result { + Ok(ProviderBuilder::new() + .wallet(wallet) + .connect_client(rpc::client(endpoint, rpc_field)?) + .erased()) +} diff --git a/e2e-tests/e2e-withdrawal/src/cmd/finalize.rs b/e2e-tests/e2e-withdrawal/src/cmd/finalize.rs new file mode 100644 index 000000000..02e6c6111 --- /dev/null +++ b/e2e-tests/e2e-withdrawal/src/cmd/finalize.rs @@ -0,0 +1,240 @@ +use crate::{ + args::FinalizeArgs, + bindings::{ + AnchorStateRegistry::AnchorStateRegistryInstance, IMultiProofGame::IMultiProofGameInstance, + OptimismPortal::OptimismPortalInstance, ProveWithdrawal, + }, + clients, storage, + types::{ + FinalizedOutcome, GameBlockedReason, StepError, StepOutcome, StepStage, WaitingOutcome, + WaitingReason, + }, +}; +use alloy_eips::BlockId; +use alloy_primitives::ruint::FromUintError; +use alloy_provider::Provider; +use eyre::eyre::{OptionExt, WrapErr, eyre}; + +/// Run the `finalize` command. +pub async fn run(args: &FinalizeArgs) -> Result { + args.validate()?; + let l1_provider = clients::l1_provider( + args.l1_args.l1_private_key.as_deref(), + args.l1_args.l1_aws_kms_key_id.as_deref(), + &args.l1_args.l1_rpc_endpoint, + ) + .await?; + run_with(args, &l1_provider).await +} + +/// Finalize a withdrawal using a pre-built L1 provider. +pub async fn run_with

(args: &FinalizeArgs, l1_provider: &P) -> Result +where + P: Provider, +{ + // read ProveWithdrawal data (local path or s3://bucket/key) + let prove_withdrawal: ProveWithdrawal = storage::read_json(&args.proven).await?; + // already finalized on-chain, treat as success so step can retry handoff cleanup. + let optimism_portal = OptimismPortalInstance::new(args.optimism_portal, l1_provider); + if optimism_portal + .finalizedWithdrawals(prove_withdrawal.hash) + .call() + .await + .map_err(|err| StepError::Generic(err.into()))? + { + return Ok(StepOutcome::Finalized(FinalizedOutcome::AlreadyFinalized { + withdrawal_hash: prove_withdrawal.hash, + })); + } + // check whether the withdrawal is finalizable: + // now - proven.timestamp > OptimismPortal::proofMaturityDelaySeconds() + let latest_block = l1_provider + .get_block(BlockId::latest()) + .await + .map_err(|err| StepError::Generic(err.into()))? + .ok_or_eyre("latest L1 block not found")?; + let now = latest_block.header.timestamp; + let block = BlockId::hash(latest_block.header.hash); + let proof_maturity_delay_seconds = optimism_portal + .proofMaturityDelaySeconds() + .block(block) + .call() + .await + .map_err(|err| StepError::Generic(err.into()))?; + let proof_maturity_delay_seconds = proof_maturity_delay_seconds + .try_into() + .map_err(|err: FromUintError| StepError::Generic(err.into()))?; + if now < prove_withdrawal.proven_at { + return Err(StepError::InvalidState { + stage: StepStage::Finalize, + message: "proven timestamp is later than the latest L1 block", + }); + } + // the portal requires elapsed time to be strictly greater than the delay. + let eligible_at = prove_withdrawal + .proven_at + .checked_add(proof_maturity_delay_seconds) + .and_then(|timestamp| timestamp.checked_add(1)) + .ok_or(StepError::InvalidState { + stage: StepStage::Finalize, + message: "proof maturity timestamp overflows u64", + })?; + // detect blocked games even while proof maturity is still pending. All game + // checks use the same block hash so a changing head cannot mix game states. + let game_waiting = check_game(l1_provider, args, &prove_withdrawal, block).await?; + if now < eligible_at { + let waiting_outcome = WaitingOutcome { + withdrawal_hash: prove_withdrawal.hash, + stage: StepStage::Finalize, + waiting_reason: WaitingReason::ProofMaturityNotElapsed { eligible_at }, + }; + return Ok(StepOutcome::Waiting(waiting_outcome)); + } + if let Some(waiting_reason) = game_waiting { + let waiting_outcome = WaitingOutcome { + withdrawal_hash: prove_withdrawal.hash, + stage: StepStage::Finalize, + waiting_reason, + }; + return Ok(StepOutcome::Waiting(waiting_outcome)); + } + // send the OptimismPortal::finalizeWithdrawal + let pending_tx = optimism_portal + .finalizeWithdrawalTransaction(prove_withdrawal.transaction) + .send() + .await + .map_err(|err| StepError::Generic(err.into()))?; + let tx_hash = *pending_tx.tx_hash(); + let receipt = + crate::rpc::receipt_with_deadline(tx_hash, StepStage::Finalize, pending_tx.get_receipt()) + .await?; + if !receipt.status() { + return Err(StepError::Generic(eyre!( + "finalizeWithdrawalTransaction tx has not succeeded. Tx hash: {}", + receipt.transaction_hash + ))); + } + let is_finalized = optimism_portal + .finalizedWithdrawals(prove_withdrawal.hash) + .call() + .await + .map_err(|err| StepError::Generic(err.into()))?; + if !is_finalized { + return Err(StepError::FinalizeNotYetVisible { + transaction_hash: receipt.transaction_hash, + withdrawal_hash: prove_withdrawal.hash, + }); + } + Ok(StepOutcome::Finalized(FinalizedOutcome::Finalized { + withdrawal_hash: prove_withdrawal.hash, + tx_hash: receipt.transaction_hash, + })) +} + +/// Distinguish expected game progress from conditions that require intervention. +async fn check_game( + provider: &P, + args: &FinalizeArgs, + withdrawal: &ProveWithdrawal, + block: BlockId, +) -> Result, StepError> { + let registry = AnchorStateRegistryInstance::new(args.anchor_state_registry, provider); + let address = withdrawal.game_addr; + let blocked = |reason| StepError::GameBlocked { + withdrawal_hash: withdrawal.hash, + game_address: address, + reason, + }; + + if registry + .isGameClaimValid(address) + .block(block) + .call() + .await + .wrap_err("L1 RPC: checking game claim validity")? + { + return Ok(None); + } + if registry + .paused() + .block(block) + .call() + .await + .wrap_err("L1 RPC: checking system pause")? + { + return Err(blocked(GameBlockedReason::SystemPaused)); + } + if !registry + .isGameRegistered(address) + .block(block) + .call() + .await + .wrap_err("L1 RPC: checking game registration")? + { + return Err(blocked(GameBlockedReason::NotRegistered)); + } + if registry + .isGameBlacklisted(address) + .block(block) + .call() + .await + .wrap_err("L1 RPC: checking game blacklist")? + { + return Err(blocked(GameBlockedReason::Blacklisted)); + } + if registry + .isGameRetired(address) + .block(block) + .call() + .await + .wrap_err("L1 RPC: checking game retirement")? + { + return Err(blocked(GameBlockedReason::Retired)); + } + if !registry + .isGameRespected(address) + .block(block) + .call() + .await + .wrap_err("L1 RPC: checking respected game type")? + { + return Err(blocked(GameBlockedReason::NotRespected)); + } + + let game = IMultiProofGameInstance::new(address, provider); + match game + .status() + .block(block) + .call() + .await + .wrap_err("L1 RPC: checking game status")? + { + // GameStatus: IN_PROGRESS = 0, CHALLENGER_WINS = 1, DEFENDER_WINS = 2. + 0 => { + return Ok(Some(WaitingReason::GameUnresolved { + game_address: address, + })); + } + 1 => return Err(blocked(GameBlockedReason::ChallengerWon)), + 2 => {} + _ => { + return Err(StepError::InvalidState { + stage: StepStage::Finalize, + message: "unrecognized dispute game status", + }); + } + } + if !registry + .isGameFinalized(address) + .block(block) + .call() + .await + .wrap_err("L1 RPC: checking game finality delay")? + { + return Ok(Some(WaitingReason::GameFinalityDelay { + game_address: address, + })); + } + // Do not turn an unexplained rejection into successful waiting. + Err(blocked(GameBlockedReason::InvalidClaim)) +} diff --git a/e2e-tests/e2e-withdrawal/src/cmd/init.rs b/e2e-tests/e2e-withdrawal/src/cmd/init.rs new file mode 100644 index 000000000..9d12b2f5d --- /dev/null +++ b/e2e-tests/e2e-withdrawal/src/cmd/init.rs @@ -0,0 +1,112 @@ +use crate::{ + args::InitArgs, + bindings::{InitiatedWithdrawal, L2ToL1MessagePasser, WithdrawalTransaction}, + clients, storage, + types::{InitiatedOutcome, StepError, StepOutcome, StepStage}, +}; +use alloy_network::ReceiptResponse; +use alloy_primitives::{Address, B256, Bytes, U256, address}; +use alloy_provider::Provider; +use alloy_rpc_types::TransactionReceipt; +use eyre::eyre::{OptionExt, ensure}; + +/// Address of the `L2ToL1MessagePasser` contract on L2. +const L2_TO_L1_MESSAGE_PASSER: Address = address!("4200000000000000000000000000000000000016"); + +/// Run the `init` command. +pub async fn run(args: &InitArgs) -> Result { + args.validate()?; + let (l2_provider, signer_addr) = clients::l2_provider( + args.l2_private_key.as_deref(), + args.l2_aws_kms_key_id.as_deref(), + &args.l2_rpc_endpoint, + ) + .await?; + run_with(args, &l2_provider, signer_addr).await +} + +/// Initialize a withdrawal using a pre-built L2 provider. +pub async fn run_with

( + args: &InitArgs, + l2_provider: &P, + signer_addr: Address, +) -> Result +where + P: Provider, +{ + // target address of the L2 -> L1 withdrawal is the same address that sends the tx on L2 + let target_addr = signer_addr; + // sends the initiate_withdrawal transaction to the L2ToL1MessagePasser contract + let (initiated_withdrawal, tx_hash) = + initiate_withdrawal(l2_provider, target_addr, args.value).await?; + // save the InitiatedWithdrawal data (local path or s3://bucket/key) + let handoff = serde_json::to_value(&initiated_withdrawal) + .map_err(|err| StepError::Generic(err.into()))?; + storage::write_json(&args.initiated, &handoff) + .await + .map_err(|err| StepError::PersistenceAfterTransaction { + transaction_hash: tx_hash, + stage: StepStage::Init, + handoff: Box::new(handoff), + source: err, + })?; + // create the StepOutcome + let initiated_outcome = InitiatedOutcome { + tx_hash, + withdrawal_hash: initiated_withdrawal.hash, + l2_block: initiated_withdrawal.l2_block, + }; + Ok(StepOutcome::Initiated(initiated_outcome)) +} + +async fn initiate_withdrawal

( + provider: P, + target_addr: Address, + value: U256, +) -> eyre::Result<(InitiatedWithdrawal, B256)> +where + P: Provider, +{ + let pending = L2ToL1MessagePasser::new(L2_TO_L1_MESSAGE_PASSER, provider) + .initiateWithdrawal(target_addr, U256::from(100_000), Bytes::new()) + .gas(250_000) + .value(value) + .send() + .await?; + let tx_hash = *pending.tx_hash(); + let receipt = + crate::rpc::receipt_with_deadline(tx_hash, StepStage::Init, pending.get_receipt()).await?; + ensure!(receipt.status(), "L2 withdrawal initiation reverted"); + let tx_hash = receipt.transaction_hash(); + let initiated_withdrawal = initiated_withdrawal_from_receipt(&receipt)?; + Ok((initiated_withdrawal, tx_hash)) +} + +fn initiated_withdrawal_from_receipt( + receipt: &TransactionReceipt, +) -> eyre::Result { + let l2_block = receipt + .block_number() + .ok_or_eyre("withdrawal receipt missing L2 block number")?; + let message = receipt + .logs() + .iter() + .find_map(|log| { + log.log_decode_validate::() + .ok() + }) + .ok_or_eyre("withdrawal receipt missing MessagePassed event")?; + let message = message.data(); + Ok(InitiatedWithdrawal { + transaction: WithdrawalTransaction { + nonce: message.nonce, + sender: message.sender, + target: message.target, + value: message.value, + gasLimit: message.gasLimit, + data: message.data.clone(), + }, + hash: message.withdrawalHash, + l2_block, + }) +} diff --git a/e2e-tests/e2e-withdrawal/src/cmd/mod.rs b/e2e-tests/e2e-withdrawal/src/cmd/mod.rs new file mode 100644 index 000000000..563877651 --- /dev/null +++ b/e2e-tests/e2e-withdrawal/src/cmd/mod.rs @@ -0,0 +1,50 @@ +use crate::{ + args::{FinalizeArgs, InitArgs, ProveArgs, StepArgs}, + types::{StepError, StepOutcome}, +}; +use clap::Subcommand; + +mod finalize; +mod init; +mod prove; +mod run; +mod step; + +/// Commands for an end-to-end L2->L1 withdrawal flow. +/// +/// The workflow is: +/// +/// 1. Initialize the withdrawal by sending an L2 transaction to the `L2ToL1MessagePasser` contract. +/// +/// 2. Once a proof-system game exists whose related L2 block number is greater than or equal to the +/// block that included that transaction, send an L1 transaction to `OptimismPortal` to prove +/// the withdrawal. +/// +/// 3. After the proof-system game is finalized and `OptimismPortal`'s `PROOF_MATURITY` delay has +/// elapsed, send an L1 transaction to `OptimismPortal` to finalize the withdrawal. +#[derive(Debug, Subcommand)] +pub enum Command { + /// Initialize the L2->L1 withdrawal. + Init(InitArgs), + /// Prove the withdrawal. + Prove(ProveArgs), + /// Finalize the withdrawal. + Finalize(FinalizeArgs), + /// Run the next stage of the withdrawal workflow based on stored state. + Step(StepArgs), + /// Run the e2e-withdrawal workflow undefinitely. + Run(StepArgs), +} + +impl Command { + /// Run the command to completion. + pub async fn run(&self) -> Result { + match self { + Self::Init(args) => init::run(args).await, + Self::Prove(args) => prove::run(args).await, + Self::Finalize(args) => finalize::run(args).await, + Self::Step(args) => step::run(args).await, + Self::Run(args) => run::run(args).await, + } + } +} diff --git a/e2e-tests/e2e-withdrawal/src/cmd/prove.rs b/e2e-tests/e2e-withdrawal/src/cmd/prove.rs new file mode 100644 index 000000000..5613fe4ba --- /dev/null +++ b/e2e-tests/e2e-withdrawal/src/cmd/prove.rs @@ -0,0 +1,228 @@ +use crate::{ + args::ProveArgs, + bindings::{ + IDisputeGameFactory::IDisputeGameFactoryInstance, IMultiProofGame::IMultiProofGameInstance, + InitiatedWithdrawal, OptimismPortal::OptimismPortalInstance, OutputRootProof, + ProveWithdrawal, + }, + clients, storage, + types::{ProvenOutcome, StepError, StepOutcome, StepStage, WaitingOutcome, WaitingReason}, +}; +use alloy_consensus::BlockHeader; +use alloy_eips::{BlockId, BlockNumberOrTag}; +use alloy_network::ReceiptResponse; +use alloy_primitives::{Address, B256, Bytes, U256, address, keccak256, ruint::FromUintError}; +use alloy_provider::Provider; +use alloy_sol_types::SolValue; +use eyre::eyre::{OptionExt, ensure, eyre}; + +/// WIP-1006 game type. +const MULTI_PROOF_GAME_TYPE: u32 = 1006; +/// Address of the `L2ToL1MessagePasser` contract on L2. +const L2_TO_L1_MESSAGE_PASSER: Address = address!("4200000000000000000000000000000000000016"); + +/// Run the `prove` command. +pub async fn run(args: &ProveArgs) -> Result { + args.validate()?; + let l1_provider = clients::l1_provider( + args.l1_args.l1_private_key.as_deref(), + args.l1_args.l1_aws_kms_key_id.as_deref(), + &args.l1_args.l1_rpc_endpoint, + ) + .await?; + let l2_provider = clients::l2_read_provider(&args.l2_rpc_endpoint)?; + run_with(args, &l1_provider, &l2_provider).await +} + +/// Prove a withdrawal using pre-built L1 and L2 providers. +pub async fn run_with( + args: &ProveArgs, + l1_provider: &L1, + l2_provider: &L2, +) -> Result +where + L1: Provider, + L2: Provider, +{ + // read InitiatedWithdrawal data (local path or s3://bucket/key) + let initiated_withdrawal: InitiatedWithdrawal = storage::read_json(&args.initiated).await?; + // wait for a covering WIP1006 game with l2SequenceNumber >= initiated_withdrawal.l2_block + let Some((game_index, game_addr, game_l2_block)) = check_multi_proof_game( + l1_provider, + args.dispute_game_factory, + initiated_withdrawal.l2_block, + ) + .await? + else { + return Ok(StepOutcome::Waiting(WaitingOutcome { + withdrawal_hash: initiated_withdrawal.hash, + stage: StepStage::Prove, + waiting_reason: WaitingReason::CoveringGameUnavailable { + withdrawal_l2_block: initiated_withdrawal.l2_block, + }, + })); + }; + // get the output root proof and the withdrawal proof + let (output_root_proof, withdrawal_proof) = + build_withdrawal_proof(l2_provider, game_l2_block, initiated_withdrawal.hash).await?; + // send the OptimismPortal::proveWithdrawalTransaction + let optimism_portal = OptimismPortalInstance::new(args.optimism_portal, l1_provider); + let pending_tx = optimism_portal + .proveWithdrawalTransaction( + initiated_withdrawal.transaction.clone(), + U256::from(game_index), + output_root_proof, + withdrawal_proof, + ) + .send() + .await + .map_err(|err| StepError::Generic(err.into()))?; + let tx_hash = *pending_tx.tx_hash(); + let receipt = + crate::rpc::receipt_with_deadline(tx_hash, StepStage::Prove, pending_tx.get_receipt()) + .await?; + if !receipt.status() { + return Err(StepError::Generic(eyre!( + "ProveWithdrawalTransaction tx has not succeeded. Tx hash: {}", + receipt.transaction_hash() + ))); + } + let proven_at = proven_at_from_receipt(l1_provider, &receipt).await?; + let withdrawal_hash = initiated_withdrawal.hash; + let withdrawal_l2_block = initiated_withdrawal.l2_block; + let prove_withdrawal = prove_withdrawal( + initiated_withdrawal, + game_index, + game_addr, + game_l2_block, + proven_at, + ); + let handoff = + serde_json::to_value(&prove_withdrawal).map_err(|err| StepError::Generic(err.into()))?; + storage::write_json(&args.proven, &handoff) + .await + .map_err(|err| StepError::PersistenceAfterTransaction { + transaction_hash: receipt.transaction_hash(), + stage: StepStage::Prove, + handoff: Box::new(handoff), + source: err, + })?; + Ok(StepOutcome::Proven(ProvenOutcome { + tx_hash: receipt.transaction_hash(), + withdrawal_hash, + withdrawal_l2_block, + })) +} + +fn prove_withdrawal( + initiated_withdrawal: InitiatedWithdrawal, + game_index: u64, + game_addr: Address, + game_l2_block: u64, + proven_at: u64, +) -> ProveWithdrawal { + ProveWithdrawal { + transaction: initiated_withdrawal.transaction, + hash: initiated_withdrawal.hash, + game_index, + game_l2_block, + game_addr, + proven_at, + } +} + +async fn proven_at_from_receipt( + provider: &P, + receipt: &impl ReceiptResponse, +) -> Result { + let block_number = receipt + .block_number() + .ok_or_eyre("prove receipt missing L1 block number") + .map_err(StepError::Generic)?; + let block = provider + .get_block(BlockId::number(block_number)) + .await + .map_err(|err| StepError::Generic(err.into()))? + .ok_or_eyre("prove L1 block not found") + .map_err(StepError::Generic)?; + Ok(block.header.timestamp()) +} + +async fn check_multi_proof_game

( + provider: P, + factory_address: Address, + min_l2_block: u64, +) -> Result, StepError> +where + P: Provider, +{ + let factory = IDisputeGameFactoryInstance::new(factory_address, &provider); + // iterate over the last 100 games + let game_count: u64 = factory + .gameCount() + .call() + .await + .map_err(|err| StepError::Generic(err.into()))? + .try_into() + .map_err(|err: FromUintError| StepError::Generic(err.into()))?; + let game_count_sub_100 = game_count.saturating_sub(100); + for index in game_count_sub_100..game_count { + let entry = factory + .gameAtIndex(U256::from(index)) + .call() + .await + .map_err(|err| StepError::Generic(err.into()))?; + if entry.gameType != MULTI_PROOF_GAME_TYPE { + continue; + } + let game = IMultiProofGameInstance::new(entry.proxy, &provider); + let l2_block: u64 = game + .l2SequenceNumber() + .call() + .await + .map_err(|err| StepError::Generic(err.into()))? + .try_into() + .map_err(|err: FromUintError| StepError::Generic(err.into()))?; + if l2_block >= min_l2_block { + return Ok(Some((index, entry.proxy, l2_block))); + } + } + Ok(None) +} + +async fn build_withdrawal_proof

( + l2_provider: P, + game_l2_block: u64, + withdrawal_hash: B256, +) -> eyre::Result<(OutputRootProof, Vec)> +where + P: Provider, +{ + let block = l2_provider + .get_block_by_number(BlockNumberOrTag::Number(game_l2_block)) + .await? + .ok_or_eyre("WIP-1006 output block missing from L2")?; + let storage_key = keccak256((withdrawal_hash, U256::ZERO).abi_encode_params()); + let account_proof = l2_provider + .get_proof(L2_TO_L1_MESSAGE_PASSER, vec![storage_key]) + .block_id(BlockId::Number(BlockNumberOrTag::Number(game_l2_block))) + .await?; + let storage_proof = account_proof + .storage_proof + .first() + .ok_or_eyre("eth_getProof returned no withdrawal storage proof")?; + ensure!( + storage_proof.value == U256::from(1), + "withdrawal is absent from the message passer" + ); + + Ok(( + OutputRootProof { + version: B256::ZERO, + stateRoot: block.header.state_root(), + messagePasserStorageRoot: account_proof.storage_hash, + latestBlockhash: block.header.hash, + }, + storage_proof.proof.clone(), + )) +} diff --git a/e2e-tests/e2e-withdrawal/src/cmd/run.rs b/e2e-tests/e2e-withdrawal/src/cmd/run.rs new file mode 100644 index 000000000..7fedeb26f --- /dev/null +++ b/e2e-tests/e2e-withdrawal/src/cmd/run.rs @@ -0,0 +1,103 @@ +use crate::{ + args::StepArgs, + clients::Clients, + cmd::step, + retry::RetryBudget, + storage, + types::{GameBlockedReason, StepError, StepOutcome, StepStage}, +}; +use std::time::Duration; + +const POLL_INTERVAL: Duration = Duration::from_secs(120); + +/// Run complete withdrawal cycles until a terminal failure occurs. +pub async fn run(args: &StepArgs) -> Result { + args.validate()?; + let clients = Clients::from_step_args(args).await?; + let mut cleanup_retry = RetryBudget::default(); + loop { + let result = step::run_with(args, &clients).await; + match &result { + Ok(outcome) => tracing::info!(?outcome, "withdrawal workflow iteration completed"), + Err(_) => tracing::info!("withdrawal workflow iteration failed, handling error"), + } + match result { + Ok(_) => cleanup_retry = RetryBudget::default(), + Err(StepError::PersistenceAfterTransaction { + transaction_hash, + stage, + handoff, + source, + }) => { + let location = match stage { + StepStage::Init => &args.initiated, + StepStage::Prove => &args.proven, + _ => { + return Err(StepError::PersistenceAfterTransaction { + transaction_hash, + stage, + handoff, + source, + }); + } + }; + // Include the initial write in the budget and retain the payload. + // Recovery needs no further RPC or storage reads. + let mut retry = RetryBudget::default(); + let mut source = source; + loop { + let Some(delay) = retry.next_delay(storage::is_permanent_error(&source)) else { + return Err(StepError::PersistenceAfterTransaction { + transaction_hash, + stage, + handoff, + source, + }); + }; + tracing::warn!(error = ?source, %transaction_hash, %stage, + attempt = retry.failures, retry_in_secs = delay.as_secs_f64(), + "handoff persistence failed, retrying"); + tokio::time::sleep(delay).await; + match storage::write_json(location, &handoff).await { + Ok(()) => break, + Err(error) => source = error, + } + } + } + Err(error @ StepError::CleanupAfterFinalized { .. }) => { + let StepError::CleanupAfterFinalized { source, .. } = &error else { + // Safe, we've just checked it's a `CleanupAfterFinalized` error + unreachable!() + }; + let Some(delay) = cleanup_retry.next_delay(storage::is_permanent_error(source)) + else { + return Err(error); + }; + tracing::warn!(error = ?error, attempt = cleanup_retry.failures, + retry_in_secs = delay.as_secs_f64(), "handoff cleanup failed, retrying"); + tokio::time::sleep(delay).await; + continue; + } + Err(StepError::GameBlocked { + withdrawal_hash, + game_address, + reason, + }) if reason != GameBlockedReason::SystemPaused => { + tracing::warn!( + %withdrawal_hash, + %game_address, + %reason, + "supporting game is invalid. Deleting proven handoff to re-prove" + ); + storage::delete(&args.proven) + .await + .map_err(StepError::Generic)?; + } + Err(error) if error.is_retryable() => { + tracing::warn!(error = ?error, "retryable withdrawal condition, waiting"); + } + Err(error) => return Err(error), + } + tokio::time::sleep(POLL_INTERVAL).await; + } +} diff --git a/e2e-tests/e2e-withdrawal/src/cmd/step.rs b/e2e-tests/e2e-withdrawal/src/cmd/step.rs new file mode 100644 index 000000000..6b6771fed --- /dev/null +++ b/e2e-tests/e2e-withdrawal/src/cmd/step.rs @@ -0,0 +1,72 @@ +use crate::{ + args::StepArgs, + clients::Clients, + cmd::{finalize, init, prove}, + storage, + types::{FinalizedOutcome, StepError, StepOutcome, StepStage}, +}; +use eyre::eyre::WrapErr; + +/// Run the `step` command. +/// +/// Dispatches to the next withdrawal stage based on durable handoff presence: +/// - no initiated -> `init` +/// - initiated, no proven -> `prove` +/// - proven -> `finalize` (idempotent if already on-chain), then delete handoffs +pub async fn run(args: &StepArgs) -> Result { + args.validate()?; + let clients = Clients::from_step_args(args).await?; + run_with(args, &clients).await +} + +/// Run the next workflow stage using pre-built providers. +pub async fn run_with(args: &StepArgs, clients: &Clients) -> Result { + let initiated_exists = storage::exists(&args.initiated).await?; + let proven_exists = storage::exists(&args.proven).await?; + + match (initiated_exists, proven_exists) { + (false, false) => init::run_with(&args.to_init(), &clients.l2, clients.l2_address).await, + (true, false) => prove::run_with(&args.to_prove(), &clients.l1, &clients.l2).await, + // Both present, or only proven left after a partial cleanup: finalize is + // idempotent, then retry handoff deletion. + (true, true) | (false, true) => { + let outcome = finalize::run_with(&args.to_finalize(), &clients.l1).await?; + match outcome { + StepOutcome::Finalized(finalized) => { + delete_handoffs(args, &finalized).await?; + Ok(StepOutcome::Finalized(finalized)) + } + StepOutcome::Waiting(waiting) => Ok(StepOutcome::Waiting(waiting)), + StepOutcome::Initiated(_) | StepOutcome::Proven(_) => { + Err(StepError::InvalidState { + stage: StepStage::Finalize, + message: "finalize returned an outcome belonging to another stage", + }) + } + } + } + } +} + +/// Delete handoffs in order: initiated first, then proven. +/// +/// If initiated delete fails, keep proven so the next tick still sees both +/// handoffs and retries finalize (idempotent) + cleanup instead of re-proving. +async fn delete_handoffs(args: &StepArgs, finalized: &FinalizedOutcome) -> Result<(), StepError> { + let withdrawal_hash = finalized.withdrawal_hash(); + storage::delete(&args.initiated) + .await + .wrap_err_with(|| format!("failed to delete initiated handoff at `{}`", args.initiated)) + .map_err(|source| StepError::CleanupAfterFinalized { + withdrawal_hash, + source, + })?; + storage::delete(&args.proven) + .await + .wrap_err_with(|| format!("failed to delete proven handoff at `{}`", args.proven)) + .map_err(|source| StepError::CleanupAfterFinalized { + withdrawal_hash, + source, + })?; + Ok(()) +} diff --git a/e2e-tests/e2e-withdrawal/src/lib.rs b/e2e-tests/e2e-withdrawal/src/lib.rs new file mode 100644 index 000000000..576d06a9a --- /dev/null +++ b/e2e-tests/e2e-withdrawal/src/lib.rs @@ -0,0 +1,10 @@ +pub mod args; +pub mod bindings; +pub mod cli; +pub mod clients; +pub mod cmd; +pub mod retry; +pub mod rpc; +pub mod signer; +pub mod storage; +pub mod types; diff --git a/e2e-tests/e2e-withdrawal/src/main.rs b/e2e-tests/e2e-withdrawal/src/main.rs new file mode 100644 index 000000000..5efe1d8dd --- /dev/null +++ b/e2e-tests/e2e-withdrawal/src/main.rs @@ -0,0 +1,24 @@ +use clap::Parser; +use e2e_withdrawal::cli::Cli; +use eyre::eyre::{WrapErr, eyre}; +use tracing_subscriber::EnvFilter; + +#[tokio::main] +async fn main() -> eyre::Result<()> { + let cli = Cli::parse(); + let filter = EnvFilter::builder() + .with_default_directive(tracing::Level::INFO.into()) + .from_env() + .wrap_err("invalid RUST_LOG filter")?; + tracing_subscriber::fmt() + .with_env_filter(filter) + .json() + .try_init() + .map_err(|err| eyre!("failed to initialize tracing: {err}"))?; + + if let Err(error) = cli.run().await { + tracing::error!(error = ?error, "withdrawal command failed"); + return Err(error.into()); + } + Ok(()) +} diff --git a/e2e-tests/e2e-withdrawal/src/retry.rs b/e2e-tests/e2e-withdrawal/src/retry.rs new file mode 100644 index 000000000..79aef2657 --- /dev/null +++ b/e2e-tests/e2e-withdrawal/src/retry.rs @@ -0,0 +1,63 @@ +use backoff::{ExponentialBackoff, backoff::Backoff}; +use std::{future::Future, time::Duration}; + +/// Default attempt budget for storage operations and post-tx persistence/cleanup. +pub const MAX_ATTEMPTS: u32 = 10; + +/// Attempt budget for retryable RPC read transport requests. +pub const RPC_MAX_ATTEMPTS: u32 = 3; + +/// Default deadline for RPC requests, receipt waits and storage attempts. +pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30); + +/// Retry `attempt_fn` with exponential backoff until success or the budget is exhausted. +pub async fn with_backoff( + max_attempts: u32, + mut attempt_fn: F, + mut should_retry: impl FnMut(&E) -> bool, + mut on_retry: impl FnMut(u32, Duration, &E), +) -> Result +where + F: FnMut() -> Fut, + Fut: Future>, +{ + let mut backoff = ExponentialBackoff::default(); + let mut attempt = 0u32; + loop { + attempt += 1; + match attempt_fn().await { + Ok(value) => return Ok(value), + Err(error) => { + if attempt >= max_attempts || !should_retry(&error) { + return Err(error); + } + let Some(delay) = backoff.next_backoff() else { + return Err(error); + }; + on_retry(attempt, delay, &error); + tokio::time::sleep(delay).await; + } + } + } +} + +/// Stateful attempt budget for callers that retry across separate invocations. +#[derive(Default)] +pub struct RetryBudget { + /// Number of failures recorded so far, including the initial failure. + pub failures: u32, + backoff: ExponentialBackoff, +} + +impl RetryBudget { + /// Return the next sleep delay, or `None` when the budget is exhausted. + /// + /// Callers decide permanence (e.g. via `storage::is_permanent_error`). + pub fn next_delay(&mut self, is_permanent: bool) -> Option { + self.failures += 1; + if self.failures >= MAX_ATTEMPTS || is_permanent { + return None; + } + self.backoff.next_backoff() + } +} diff --git a/e2e-tests/e2e-withdrawal/src/rpc.rs b/e2e-tests/e2e-withdrawal/src/rpc.rs new file mode 100644 index 000000000..f01cb7f9b --- /dev/null +++ b/e2e-tests/e2e-withdrawal/src/rpc.rs @@ -0,0 +1,176 @@ +use crate::{ + args, + retry::{self, DEFAULT_TIMEOUT, RPC_MAX_ATTEMPTS}, + types::StepStage, +}; +use alloy_json_rpc::{RequestPacket, ResponsePacket}; +use alloy_provider::transport::{TransportError, TransportErrorKind, TransportFut}; +use alloy_rpc_client::RpcClient; +use alloy_transport_http::Http; +use eyre::eyre::WrapErr; +use std::{ + task::{Context, Poll}, + time::Duration, +}; +use tower::Service; + +/// Bound the entire receipt wait, including any in-flight RPC at the deadline. +pub async fn receipt_with_deadline( + transaction_hash: alloy_primitives::B256, + stage: StepStage, + future: impl std::future::Future>, +) -> eyre::Result +where + E: std::error::Error + Send + Sync + 'static, +{ + tokio::time::timeout(DEFAULT_TIMEOUT, future) + .await + .wrap_err_with(|| { + format!("{stage} receipt timed out after 30 seconds; transaction {transaction_hash}") + })? + .wrap_err_with(|| format!("{stage} receipt failed; transaction {transaction_hash}")) +} + +/// Apply retries below the provider so receipt polling and transaction fillers +/// get the same policy as explicit reads. Submission requests are never retried. +pub fn client(endpoint: &str, field: &'static str) -> eyre::Result { + let url = args::rpc_url(endpoint, field)?; + let client = reqwest::Client::builder() + .timeout(DEFAULT_TIMEOUT) + .retry(reqwest::retry::never()) + .build()?; + let inner = Http::with_client(client, url); + let is_local = inner.guess_local(); + Ok(RpcClient::new( + ReadRetryTransport { + inner, + dependency: field, + }, + is_local, + )) +} + +#[derive(Clone, Debug)] +struct ReadRetryTransport { + inner: Http, + dependency: &'static str, +} + +impl Service for ReadRetryTransport { + type Response = ResponsePacket; + type Error = TransportError; + type Future = TransportFut<'static>; + + fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll> { + self.inner.poll_ready(cx) + } + + fn call(&mut self, request: RequestPacket) -> Self::Future { + // Submissions and mixed batches bypass retry handling entirely. + if !request.method_names().all(is_read) { + return self.inner.call(request); + } + Box::pin(self.clone().retry_read(request)) + } +} + +impl ReadRetryTransport { + async fn retry_read(self, request: RequestPacket) -> Result { + let methods = request.method_names().collect::>().join(","); + let dependency = self.dependency; + retry::with_backoff( + RPC_MAX_ATTEMPTS, + || { + let mut transport = self.clone(); + let request = request.clone(); + async move { transport.inner.call(request).await.and_then(check_response) } + }, + is_transient, + |attempt, delay, error| log_retry(dependency, &methods, attempt, delay, error), + ) + .await + } +} + +/// Surface transient JSON-RPC errors to the retry loop; preserve other responses. +fn check_response(response: ResponsePacket) -> Result { + if let Some(error) = response.as_error() { + let error = TransportError::ErrorResp(error.clone()); + if is_transient(&error) { + return Err(error); + } + } + Ok(response) +} + +fn log_retry( + dependency: &str, + methods: &str, + attempt: u32, + delay: Duration, + error: &TransportError, +) { + let (failure_class, upstream_status, rpc_error_code) = match error { + TransportError::Transport(TransportErrorKind::HttpError(error)) => { + ("http", Some(error.status), None) + } + TransportError::Transport(TransportErrorKind::Custom(error)) + if error + .downcast_ref::() + .is_some_and(|error| error.is_timeout()) => + { + ("timeout", None, None) + } + TransportError::ErrorResp(error) => ("rpc", None, Some(error.code)), + _ => ("transport", None, None), + }; + tracing::warn!( + dependency, + rpc_method = methods, + attempt, + upstream_status, + failure_class, + rpc_error_code, + retry_in_secs = delay.as_secs_f64(), + "RPC read failed; retrying" + ); +} + +fn is_read(method: &str) -> bool { + matches!( + method, + "eth_call" + | "eth_estimateGas" + | "eth_chainId" + | "eth_blockNumber" + | "eth_gasPrice" + | "eth_maxPriorityFeePerGas" + | "eth_feeHistory" + | "eth_getBlockByNumber" + | "eth_getBlockByHash" + | "eth_getBlockReceipts" + | "eth_getTransactionReceipt" + | "eth_getTransactionByHash" + | "eth_getTransactionCount" + | "eth_getBalance" + | "eth_getCode" + | "eth_getStorageAt" + | "eth_getProof" + | "eth_getLogs" + | "net_version" + ) +} + +fn is_transient(error: &TransportError) -> bool { + match error { + TransportError::Transport(TransportErrorKind::HttpError(error)) => { + error.status == 408 || error.status == 429 || (500..600).contains(&error.status) + } + TransportError::Transport(TransportErrorKind::Custom(error)) => error + .downcast_ref::() + .is_some_and(|error| error.is_timeout() || error.is_connect() || error.is_body()), + TransportError::ErrorResp(error) => error.is_retry_err() || error.code == -32603, + TransportError::NullResp => true, + _ => false, + } +} diff --git a/e2e-tests/e2e-withdrawal/src/signer.rs b/e2e-tests/e2e-withdrawal/src/signer.rs new file mode 100644 index 000000000..f9df3e065 --- /dev/null +++ b/e2e-tests/e2e-withdrawal/src/signer.rs @@ -0,0 +1,112 @@ +//! Local and AWS KMS wallet construction shared by both chains. + +use crate::{retry, rpc, types::StepError}; +use alloy_network::EthereumWallet; +use alloy_provider::{Provider, ProviderBuilder}; +use alloy_signer_aws::AwsSigner; +use alloy_signer_local::PrivateKeySigner; +use aws_sdk_kms::config::{retry::RetryConfig, timeout::TimeoutConfig}; +use eyre::eyre::{WrapErr, bail}; + +pub fn validate( + private_key: Option<&str>, + kms_key_id: Option<&str>, + field: &'static str, +) -> Result<(), StepError> { + match (private_key, kms_key_id) { + (Some(key), None) if key.parse::().is_ok() => Ok(()), + (None, Some(id)) if !id.trim().is_empty() => Ok(()), + _ => Err(StepError::InvalidConfiguration { field }), + } +} + +pub async fn wallet( + private_key: Option<&str>, + kms_key_id: Option<&str>, + endpoint: &str, + rpc_field: &'static str, + signer_field: &'static str, +) -> Result { + validate(private_key, kms_key_id, signer_field)?; + if let Some(key) = private_key { + let signer = + key.parse::() + .map_err(|_| StepError::InvalidConfiguration { + field: signer_field, + })?; + return Ok(EthereumWallet::from(signer)); + } + + // Also bound credential discovery and the chain-ID lookup, not only KMS requests. + tokio::time::timeout( + retry::DEFAULT_TIMEOUT, + Box::pin(async { + let chain_id = ProviderBuilder::new() + .connect_client(rpc::client(endpoint, rpc_field)?) + .get_chain_id() + .await + .wrap_err_with(|| format!("failed to fetch chain ID via {rpc_field}"))?; + let config = aws_config::defaults(aws_config::BehaviorVersion::latest()) + .load() + .await; + if config.region().is_none() { + bail!("AWS region missing; set AWS_REGION or AWS_DEFAULT_REGION"); + } + let config = aws_sdk_kms::config::Builder::from(&config) + .timeout_config( + TimeoutConfig::builder() + .operation_timeout(retry::DEFAULT_TIMEOUT) + .operation_attempt_timeout(retry::DEFAULT_TIMEOUT) + .build(), + ) + .retry_config(RetryConfig::standard().with_max_attempts(retry::RPC_MAX_ATTEMPTS)) + .build(); + let signer = AwsSigner::new( + aws_sdk_kms::Client::from_conf(config), + kms_key_id.expect("validated KMS source").to_owned(), + Some(chain_id), + ) + .await + .wrap_err("failed to retrieve AWS KMS signing public key")?; + Ok::<_, eyre::Report>(EthereumWallet::from(signer)) + }), + ) + .await + .wrap_err_with(|| format!("{signer_field}: signer initialization timed out after 30 seconds"))? + .wrap_err_with(|| format!("{signer_field}: signer initialization failed")) + .map_err(StepError::from) +} + +#[cfg(test)] +mod tests { + use super::*; + const KEY: &str = "0000000000000000000000000000000000000000000000000000000000000001"; + + #[test] + fn validates_exactly_one_source() { + for (key, kms, valid) in [ + (Some(KEY), None, true), + (None, Some("alias/test"), true), + (None, None, false), + (Some(KEY), Some("alias/test"), false), + (Some("invalid-secret"), None, false), + (None, Some(" "), false), + (None, Some(""), false), + ] { + assert_eq!(validate(key, kms, "signer").is_ok(), valid); + } + let error = validate(Some("invalid-secret"), None, "signer").unwrap_err(); + assert!(!format!("{error:?}").contains("invalid-secret")); + } + + #[tokio::test] + async fn local_wallet_needs_no_network() { + let wallet = wallet(Some(KEY), None, "invalid-url", "RPC", "signer") + .await + .unwrap(); + assert_eq!( + wallet.default_signer().address(), + KEY.parse::().unwrap().address() + ); + } +} diff --git a/e2e-tests/e2e-withdrawal/src/storage.rs b/e2e-tests/e2e-withdrawal/src/storage.rs new file mode 100644 index 000000000..318211e5f --- /dev/null +++ b/e2e-tests/e2e-withdrawal/src/storage.rs @@ -0,0 +1,294 @@ +use crate::retry::{self, DEFAULT_TIMEOUT, MAX_ATTEMPTS}; +use async_trait::async_trait; +use aws_credential_types::provider::ProvideCredentials; +use aws_sdk_s3::{ + error::{ProvideErrorMetadata, SdkError}, + operation::{ + delete_object::DeleteObjectError, get_object::GetObjectError, head_object::HeadObjectError, + put_object::PutObjectError, + }, +}; +use eyre::eyre::{Context, OptionExt, bail}; +use serde::{Serialize, de::DeserializeOwned}; + +/// Byte-oriented blob store used for withdrawal handoff JSON. +#[async_trait] +pub trait BlobStore: Send + Sync { + /// Read the blob at `key`. + async fn get(&self, key: &str) -> eyre::Result>; + /// Write `bytes` to `key`. + async fn put(&self, key: &str, bytes: &[u8]) -> eyre::Result<()>; + /// Return whether `key` exists. + async fn exists(&self, key: &str) -> eyre::Result; + /// Delete `key`. Missing keys are ignored. + async fn delete(&self, key: &str) -> eyre::Result<()>; +} + +/// Filesystem-backed store. The key is treated as a filesystem path. +pub struct LocalStore; + +#[async_trait] +impl BlobStore for LocalStore { + async fn get(&self, key: &str) -> eyre::Result> { + Ok(tokio::fs::read(key).await?) + } + + async fn put(&self, key: &str, bytes: &[u8]) -> eyre::Result<()> { + Ok(tokio::fs::write(key, bytes).await?) + } + + async fn exists(&self, key: &str) -> eyre::Result { + Ok(tokio::fs::try_exists(key).await?) + } + + async fn delete(&self, key: &str) -> eyre::Result<()> { + match tokio::fs::remove_file(key).await { + Ok(()) => Ok(()), + Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(()), + Err(err) => Err(err.into()), + } + } +} + +/// S3-backed store for a single bucket. +pub struct S3Store { + client: aws_sdk_s3::Client, + bucket: String, +} + +#[async_trait] +impl BlobStore for S3Store { + async fn get(&self, key: &str) -> eyre::Result> { + let object = self + .client + .get_object() + .bucket(&self.bucket) + .key(key) + .send() + .await + .wrap_err_with(|| format!("failed to get s3://{}/{}", self.bucket, key))?; + let bytes = object + .body + .collect() + .await + .wrap_err_with(|| format!("failed to read s3://{}/{} body", self.bucket, key))? + .into_bytes() + .to_vec(); + Ok(bytes) + } + + async fn put(&self, key: &str, bytes: &[u8]) -> eyre::Result<()> { + self.client + .put_object() + .bucket(&self.bucket) + .key(key) + .content_type("application/json") + .body(bytes.to_vec().into()) + .send() + .await + .wrap_err_with(|| format!("failed to put s3://{}/{}", self.bucket, key))?; + Ok(()) + } + + async fn exists(&self, key: &str) -> eyre::Result { + match self + .client + .head_object() + .bucket(&self.bucket) + .key(key) + .send() + .await + { + Ok(_) => Ok(true), + Err(err) => { + if err.as_service_error().is_some_and(|e| e.is_not_found()) { + Ok(false) + } else { + Err(err) + .wrap_err_with(|| format!("failed to head s3://{}/{}", self.bucket, key)) + } + } + } + } + + async fn delete(&self, key: &str) -> eyre::Result<()> { + self.client + .delete_object() + .bucket(&self.bucket) + .key(key) + .send() + .await + .wrap_err_with(|| format!("failed to delete s3://{}/{}", self.bucket, key))?; + Ok(()) + } +} + +/// Open a location URI and return the store plus the key within that store. +/// +/// - Local path: any string that does not start with `s3://` +/// - S3: `s3://bucket/key` +pub async fn open(location: &str) -> eyre::Result<(Box, String)> { + if let Some(rest) = location.strip_prefix("s3://") { + let (bucket, key) = rest + .split_once('/') + .ok_or_eyre("s3 location must be s3://bucket/key")?; + if bucket.is_empty() { + bail!("s3 location missing bucket: {location}"); + } + if key.is_empty() { + bail!("s3 location missing key: {location}"); + } + let config = aws_config::defaults(aws_config::BehaviorVersion::latest()) + .load() + .await; + if config.region().is_none() { + bail!( + "AWS region not configured; set AWS_REGION or AWS_DEFAULT_REGION \ + (needed for s3:// locations)" + ); + } + // Resolve credentials early so missing AWS_PROFILE / expired SSO is obvious, + // instead of a later opaque "dispatch failure" from IMDS fallback. + if let Some(provider) = config.credentials_provider() { + provider.provide_credentials().await.wrap_err( + "AWS credentials unavailable; set AWS_PROFILE to an SSO profile \ + (e.g. tfh-crypto-dev-poweruseraccess) and run \ + `aws sso login --profile `", + )?; + } + let store = S3Store { + client: aws_sdk_s3::Client::new(&config), + bucket: bucket.to_string(), + }; + return Ok((Box::new(store), key.to_string())); + } + + Ok((Box::new(LocalStore), location.to_string())) +} + +/// Read and deserialize JSON from a local path or `s3://bucket/key`. +pub async fn read_json(location: &str) -> eyre::Result { + with_retries("read", location, || async { + let (store, key) = open(location).await?; + Ok(serde_json::from_slice(&store.get(&key).await?)?) + }) + .await +} + +/// Serialize and write JSON to a local path or `s3://bucket/key`. +pub async fn write_json(location: &str, value: &T) -> eyre::Result<()> { + with_retries("write", location, || async { + let (store, key) = open(location).await?; + store.put(&key, &serde_json::to_vec_pretty(value)?).await + }) + .await +} + +/// Return whether a local path or `s3://bucket/key` exists. +pub async fn exists(location: &str) -> eyre::Result { + with_retries("exists", location, || async { + let (store, key) = open(location).await?; + store.exists(&key).await + }) + .await +} + +/// Delete a local path or `s3://bucket/key`. Missing objects are ignored. +pub async fn delete(location: &str) -> eyre::Result<()> { + with_retries("delete", location, || async { + let (store, key) = open(location).await?; + store.delete(&key).await + }) + .await +} + +async fn with_retries( + operation: &str, + location: &str, + mut attempt_fn: F, +) -> eyre::Result +where + F: FnMut() -> Fut, + Fut: std::future::Future>, +{ + retry::with_backoff( + MAX_ATTEMPTS, + || with_deadline(operation, location, attempt_fn()), + |error| !is_permanent_error(error), + |attempt, delay, error| { + tracing::warn!( + error = ?error, + operation, + location, + attempt, + retry_in_secs = delay.as_secs_f64(), + "storage operation failed, retrying" + ); + }, + ) + .await +} + +async fn with_deadline( + operation: &str, + location: &str, + future: impl std::future::Future>, +) -> eyre::Result { + tokio::time::timeout(DEFAULT_TIMEOUT, future) + .await + .wrap_err_with(|| { + format!("storage {operation} timed out after 30 seconds at `{location}`") + })? +} + +/// Recognize permanent failures without matching human-readable error strings. +pub fn is_permanent_error(error: &eyre::Report) -> bool { + if let Some(error) = error.downcast_ref::() { + return matches!( + error.kind(), + std::io::ErrorKind::PermissionDenied + | std::io::ErrorKind::InvalidInput + | std::io::ErrorKind::NotFound + ); + } + if error.downcast_ref::().is_some() { + return true; + } + // Persistence and cleanup retain typed SDK errors through context. + matches!( + s3_service_code(error), + Some( + "AccessDenied" + | "InvalidAccessKeyId" + | "SignatureDoesNotMatch" + | "NoSuchBucket" + | "InvalidArgument" + | "NoSuchKey" + ) + ) +} + +fn s3_service_code(error: &eyre::Report) -> Option<&str> { + error + .downcast_ref::>() + .and_then(|error| error.as_service_error()) + .and_then(|error| error.code()) + .or_else(|| { + error + .downcast_ref::>() + .and_then(|error| error.as_service_error()) + .and_then(|error| error.code()) + }) + .or_else(|| { + error + .downcast_ref::>() + .and_then(|error| error.as_service_error()) + .and_then(|error| error.code()) + }) + .or_else(|| { + error + .downcast_ref::>() + .and_then(|error| error.as_service_error()) + .and_then(|error| error.code()) + }) +} diff --git a/e2e-tests/e2e-withdrawal/src/types.rs b/e2e-tests/e2e-withdrawal/src/types.rs new file mode 100644 index 000000000..cc7b49053 --- /dev/null +++ b/e2e-tests/e2e-withdrawal/src/types.rs @@ -0,0 +1,237 @@ +use alloy_primitives::{Address, B256, BlockNumber, TxHash}; + +/// Successful progress or expected waiting during the withdrawal workflow. +#[derive(Debug)] +pub enum StepOutcome { + /// Initiation succeeded and its handoff was persisted. + Initiated(InitiatedOutcome), + /// Proving succeeded and its handoff was persisted. + Proven(ProvenOutcome), + /// A prerequisite is pending; no transaction was submitted by this invocation. + Waiting(WaitingOutcome), + /// Finalization was confirmed; `step` also completed handoff cleanup. + Finalized(FinalizedOutcome), +} + +/// Details of a successfully initiated withdrawal. +#[derive(Debug)] +pub struct InitiatedOutcome { + /// L2 initiation transaction hash. + pub tx_hash: B256, + /// Withdrawal identifier emitted by the message passer. + pub withdrawal_hash: B256, + /// L2 block containing the initiation transaction. + pub l2_block: BlockNumber, +} + +/// Details of a successfully proven withdrawal. +#[derive(Debug)] +pub struct ProvenOutcome { + /// L1 proving transaction hash. + pub tx_hash: B256, + /// Identifier of the proven withdrawal. + pub withdrawal_hash: B256, + /// L2 initiation block, not the covering game's block. + pub withdrawal_l2_block: BlockNumber, +} + +/// Whether finalization was already recorded or performed by this invocation. +#[derive(Debug)] +pub enum FinalizedOutcome { + /// The portal already recorded the withdrawal as finalized. + AlreadyFinalized { + /// Identifier of the finalized withdrawal. + withdrawal_hash: B256, + }, + /// This invocation submitted and confirmed finalization. + Finalized { + /// Identifier of the finalized withdrawal. + withdrawal_hash: B256, + /// L1 finalization transaction hash. + tx_hash: TxHash, + }, +} + +impl FinalizedOutcome { + /// Withdrawal hash associated with this finalize outcome. + pub fn withdrawal_hash(&self) -> B256 { + match self { + Self::AlreadyFinalized { withdrawal_hash } => *withdrawal_hash, + Self::Finalized { + withdrawal_hash, .. + } => *withdrawal_hash, + } + } +} + +/// A withdrawal awaiting a normal on-chain prerequisite. +#[derive(Debug)] +pub struct WaitingOutcome { + /// Identifier of the withdrawal awaiting progress. + pub withdrawal_hash: B256, + /// Stage that cannot proceed yet. + pub stage: StepStage, + /// Prerequisite that must be satisfied before retrying. + pub waiting_reason: WaitingReason, +} + +/// Stage of the withdrawal workflow associated with an outcome or failure. +#[derive(Debug)] +pub enum StepStage { + /// Submit the withdrawal on L2 and persist its handoff. + Init, + /// Prove the withdrawal on L1 and persist its handoff. + Prove, + /// Confirm or perform finalization on L1. + Finalize, + /// Remove handoffs after confirmed finalization. + Cleanup, +} + +impl std::fmt::Display for StepStage { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let s = match self { + StepStage::Init => "init", + StepStage::Prove => "prove", + StepStage::Finalize => "finalize", + StepStage::Cleanup => "cleanup", + }; + write!(f, "{s}") + } +} + +/// Expected conditions that can become satisfied as the chain progresses. +#[derive(Debug)] +pub enum WaitingReason { + /// No suitable game was found covering the withdrawal's L2 block. + CoveringGameUnavailable { + /// L2 block that a covering game must include. + withdrawal_l2_block: BlockNumber, + }, + /// The portal's proof maturity delay has not elapsed. + ProofMaturityNotElapsed { + /// First eligible L1 block timestamp, in Unix seconds. + eligible_at: u64, + }, + /// The covering game is still in progress. + GameUnresolved { + /// Address of the unresolved game. + game_address: Address, + }, + /// The resolved game is still within the finality delay. + GameFinalityDelay { + /// Address of the game awaiting finality. + game_address: Address, + }, +} + +/// Conditions that block finalization rather than represent normal progress. +#[derive(Debug, thiserror::Error, PartialEq)] +pub enum GameBlockedReason { + /// The system must be unpaused before finalization can proceed. + #[error("system is paused")] + SystemPaused, + /// The game is absent from the registry's dispute game factory. + #[error("game is not registered")] + NotRegistered, + /// The registry explicitly blacklisted the game. + #[error("game is blacklisted")] + Blacklisted, + /// The game predates the registry's retirement cutoff. + #[error("game is retired")] + Retired, + /// The game's type was not respected when it was created. + #[error("game type was not respected when the game was created")] + NotRespected, + /// The game resolved against the withdrawal's supporting claim. + #[error("game resolved in favor of the challenger")] + ChallengerWon, + /// The registry rejected the claim despite all known prerequisites passing. + #[error("game claim is invalid despite satisfying known finalization prerequisites")] + InvalidClaim, +} + +/// A workflow failure; the variant alone does not make arbitrary retries safe. +#[derive(Debug, thiserror::Error)] +pub enum StepError { + /// Unclassified failure. + #[error("Generic error: {0}")] + Generic(#[from] eyre::Report), + /// A required configuration value is invalid. + #[error("Invalid configuration: {field}")] + InvalidConfiguration { + /// Configuration field name; never its secret value. + field: &'static str, + }, + /// Stored or observed state violates a workflow invariant. + #[error("Invalid state during {stage}: {message}")] + InvalidState { + /// Stage that detected the invalid state. + stage: StepStage, + /// Description of the violated invariant. + message: &'static str, + }, + /// The supporting game cannot currently be used for finalization. + #[error("Withdrawal {withdrawal_hash} is blocked by game {game_address}: {reason}")] + GameBlocked { + /// Identifier of the blocked withdrawal. + withdrawal_hash: B256, + /// Address of the supporting game. + game_address: Address, + /// Condition preventing finalization. + reason: GameBlockedReason, + }, + /// Persistence error after transaction has already been sent onchain. + #[error( + "Persistence error after transaction has already been sent onchain. Tx hash: {transaction_hash}, stage: {stage}, source: {source}" + )] + PersistenceAfterTransaction { + /// Hash of the confirmed transaction whose handoff could not be saved. + transaction_hash: B256, + /// Stage that executed the transaction. + stage: StepStage, + /// Complete handoff retained so persistence retries need no remote reads. + handoff: Box, + /// Underlying persistence failure. + source: eyre::Report, + }, + /// Handoff cleanup failed after the withdrawal was already finalized onchain. + /// + /// The next `step` tick should retry finalize (idempotent) and cleanup. + #[error( + "Cleanup error after withdrawal was finalized onchain. Withdrawal hash: {withdrawal_hash}, source: {source}" + )] + CleanupAfterFinalized { + /// Identifier of the withdrawal already finalized on-chain. + withdrawal_hash: B256, + /// Underlying handoff deletion failure. + source: eyre::Report, + }, + /// Finalize tx succeeded but the portal read has not yet observed it. + /// + /// Usually caused by an RPC provider routing the confirmation read to a + /// lagging node. The next tick should retry finalize (idempotent). + #[error( + "Portal did not yet show finalized withdrawal {withdrawal_hash} after tx {transaction_hash}" + )] + FinalizeNotYetVisible { + /// Hash of the successful finalize transaction. + transaction_hash: B256, + /// Identifier of the withdrawal that should now be finalized. + withdrawal_hash: B256, + }, +} + +impl StepError { + /// Return whether the error is retryable. + pub fn is_retryable(&self) -> bool { + matches!( + self, + Self::FinalizeNotYetVisible { .. } + | Self::GameBlocked { + reason: GameBlockedReason::SystemPaused, + .. + } + ) + } +} diff --git a/e2e-tests/src/it/acceptance_tests/config.rs b/e2e-tests/src/it/acceptance_tests/config.rs index 96e65b95e..6e7bde64c 100644 --- a/e2e-tests/src/it/acceptance_tests/config.rs +++ b/e2e-tests/src/it/acceptance_tests/config.rs @@ -181,7 +181,9 @@ fn cloudflare_access_from_env() -> eyre::Result> { client_secret, })), (None, None) => Ok(None), - _ => bail!("CF_ACCESS_CLIENT_ID and CF_ACCESS_CLIENT_SECRET must be set together"), + _ => { + bail!("CF_ACCESS_CLIENT_ID and CF_ACCESS_CLIENT_SECRET must be set together"); + } } } @@ -335,9 +337,11 @@ fn bundler_cloudflare_access_from_env( client_secret, })), (None, None) => Ok(chain_cloudflare_access.cloned()), - _ => bail!( - "ACCEPTANCE_BUNDLER_CF_ACCESS_CLIENT_ID and ACCEPTANCE_BUNDLER_CF_ACCESS_CLIENT_SECRET must be set together" - ), + _ => { + bail!( + "ACCEPTANCE_BUNDLER_CF_ACCESS_CLIENT_ID and ACCEPTANCE_BUNDLER_CF_ACCESS_CLIENT_SECRET must be set together" + ); + } } } @@ -365,9 +369,11 @@ fn user_operation_profile_from_env() -> eyre::Result Ok(UserOperationProfile::Heavy), "smoke" => Ok(UserOperationProfile::Smoke), - _ => bail!( - "unsupported ACCEPTANCE_4337_PROFILE {value:?}; expected one of: heavy, smoke" - ), + _ => { + bail!( + "unsupported ACCEPTANCE_4337_PROFILE {value:?}; expected one of: heavy, smoke" + ); + } }) .transpose() } @@ -385,7 +391,7 @@ fn parse_optional_address( return Ok(world_chain_devnet_default); } - bail!("{name} is required when ACCEPTANCE_BUNDLER_RPC_URL is set outside chain 69420") + bail!("{name} is required when ACCEPTANCE_BUNDLER_RPC_URL is set outside chain 69420"); } fn optional_env(name: &str) -> Option { diff --git a/e2e-tests/src/it/acceptance_tests/erc4337.rs b/e2e-tests/src/it/acceptance_tests/erc4337.rs index 9ce70f6d7..b9c464388 100644 --- a/e2e-tests/src/it/acceptance_tests/erc4337.rs +++ b/e2e-tests/src/it/acceptance_tests/erc4337.rs @@ -602,15 +602,19 @@ impl<'a> UserOperationHarness<'a> { let send = self.send_sponsored_user_operation(user_op); match timeout(self.config.user_operation_reject_timeout, send).await { - Ok(Ok(hash)) => bail!("{label} was accepted by bundler as {hash:?}"), + Ok(Ok(hash)) => { + bail!("{label} was accepted by bundler as {hash:?}"); + } Ok(Err(error)) => { info!(%label, %error, "user operation rejected as expected"); Ok(()) } - Err(_) => bail!( - "{label} did not reject within {:?}", - self.config.user_operation_reject_timeout - ), + Err(_) => { + bail!( + "{label} did not reject within {:?}", + self.config.user_operation_reject_timeout + ); + } } } diff --git a/e2e-tests/src/it/acceptance_tests/karst.rs b/e2e-tests/src/it/acceptance_tests/karst.rs index b00ecbae6..c0d3ebea4 100644 --- a/e2e-tests/src/it/acceptance_tests/karst.rs +++ b/e2e-tests/src/it/acceptance_tests/karst.rs @@ -77,34 +77,71 @@ pub(super) async fn l2_execution_checks(env: &RpcEnv) -> eyre::Result<()> { "running Karst L2 execution acceptance tests" ); - eprintln!("karst: checking EIP-7910 eth_config"); - check_eip_7910_eth_config(env).await?; + let mut failures = Vec::new(); + macro_rules! run_check { + ($label:literal, $check:expr) => { + eprintln!("karst: checking {}", $label); + if let Err(err) = $check.await { + eprintln!("karst: FAILED {}: {err:#}", $label); + failures.push(format!("{}: {err:#}", $label)); + } + }; + } + + run_check!("EIP-7910 eth_config", check_eip_7910_eth_config(env)); - let mut sender = L2TxSender::new( + match L2TxSender::new( env.chain_provider().clone(), l2_key, env.config().tx_timeout, env.config().tx_poll_interval, ) - .await?; + .await + { + Ok(mut sender) => { + run_check!( + "EIP-7823 MODEXP input bound", + check_eip_7823_modexp_upper_bound(&mut sender) + ); + run_check!( + "EIP-7883 MODEXP gas floor", + check_eip_7883_modexp_gas_floor_increase(&mut sender) + ); + run_check!( + "EIP-7951 P256VERIFY gas cost", + check_eip_7951_p256verify_gas_cost(&mut sender) + ); + run_check!( + "bn256 pairing input limit", + check_karst_bn256_pairing_input_size_reduction(&mut sender) + ); + run_check!( + "EIP-7939 CLZ opcode activation", + check_eip_7939_clz_opcode_activation(&mut sender) + ); + run_check!( + "EIP-7825 transaction gas cap", + check_eip_7825_tx_gas_limit_cap(&mut sender) + ); + } + Err(err) => { + eprintln!("karst: FAILED transaction sender initialization: {err:#}"); + failures.push(format!("transaction sender initialization: {err:#}")); + } + } - eprintln!("karst: checking EIP-7823 MODEXP input bound"); - check_eip_7823_modexp_upper_bound(&mut sender).await?; - eprintln!("karst: checking EIP-7883 MODEXP gas floor"); - check_eip_7883_modexp_gas_floor_increase(&mut sender).await?; - eprintln!("karst: checking EIP-7951 P256VERIFY gas cost"); - check_eip_7951_p256verify_gas_cost(&mut sender).await?; - eprintln!("karst: checking bn256 pairing input limit"); - check_karst_bn256_pairing_input_size_reduction(&mut sender).await?; - eprintln!("karst: checking EIP-7939 CLZ opcode activation"); - check_eip_7939_clz_opcode_activation(&mut sender).await?; - eprintln!("karst: checking EIP-7825 transaction gas cap"); - check_eip_7825_tx_gas_limit_cap(&mut sender).await?; - eprintln!("karst: checking EIP-7825 deposit bypass"); - check_eip_7825_deposit_bypasses_tx_gas_limit_cap(env).await?; + run_check!( + "EIP-7825 deposit bypass", + check_eip_7825_deposit_bypasses_tx_gas_limit_cap(env) + ); eprintln!("karst: L2 execution checks completed"); info!("Karst L2 execution acceptance tests completed"); + ensure!( + failures.is_empty(), + "Karst L2 execution checks failed:\n{}", + failures.join("\n") + ); Ok(()) } @@ -555,7 +592,7 @@ fn deposit_tx_from_receipt( bail!( "EIP-7825 deposit bypass: no TransactionDeposited event found in L1 receipt {:?}", receipt.transaction_hash - ) + ); } fn deposit_tx_from_log(log: &Log) -> eyre::Result> { @@ -582,7 +619,9 @@ fn deposit_tx_from_log(log: &Log) -> eyre::Result> { let is_creation = match opaque[72] { 0 => false, 1 => true, - value => bail!("EIP-7825 deposit bypass: invalid deposit creation flag {value}"), + value => { + bail!("EIP-7825 deposit bypass: invalid deposit creation flag {value}"); + } }; let input = Bytes::copy_from_slice(&opaque[73..]); let to = if is_creation { diff --git a/e2e-tests/src/it/acceptance_tests/rpc.rs b/e2e-tests/src/it/acceptance_tests/rpc.rs index 87d91e247..b9b13611a 100644 --- a/e2e-tests/src/it/acceptance_tests/rpc.rs +++ b/e2e-tests/src/it/acceptance_tests/rpc.rs @@ -28,6 +28,13 @@ impl RpcEnv { let Some(config) = Config::from_env()? else { return Ok(None); }; + eprintln!("acceptance: L2 sender address={}", config.l2_key.address()); + if let Some(deposit) = config.karst_deposit.as_ref() { + eprintln!( + "acceptance: L1 deposit sender address={}", + deposit.l1_key.address() + ); + } let provider = provider_for_url::(&config.rpc_url, config.cloudflare_access.as_ref())?; let optimism_provider = diff --git a/e2e-tests/src/it/acceptance_tests/utils.rs b/e2e-tests/src/it/acceptance_tests/utils.rs index d430a5b01..6e742fc85 100644 --- a/e2e-tests/src/it/acceptance_tests/utils.rs +++ b/e2e-tests/src/it/acceptance_tests/utils.rs @@ -125,7 +125,7 @@ impl L2TxSender { "{label}: expected submission rejection for tx {hash:?}, got receipt success={} in block {:?}", receipt.status(), receipt.block_number - ) + ); } Err(err) => { info!( diff --git a/e2e-tests/src/it/alphanet/already_challenged_game_is_ignored.rs b/e2e-tests/src/it/alphanet/already_challenged_game_is_ignored.rs new file mode 100644 index 000000000..51a90275b --- /dev/null +++ b/e2e-tests/src/it/alphanet/already_challenged_game_is_ignored.rs @@ -0,0 +1,83 @@ +use crate::it::utils::devnet::proof_system_client; +use alloy_network::EthereumWallet; +use alloy_primitives::Address; +use alloy_provider::ProviderBuilder; +use alloy_signer_local::PrivateKeySigner; +use revm_primitives::B256; +use std::str::FromStr; +use world_chain_proof_protocol::{IMultiProofGame::IMultiProofGameInstance, LineageProvider}; +use world_chain_proposer::{Proposal, ProposalSubmission, ProposerClient}; + +#[tokio::test] +#[ignore] +async fn submit_bad_proposal() { + // fetch env vars + let l1_private_key_str = std::env::var("L1_PRIVATE_KEY").unwrap(); + let l1_rpc_endpoint = std::env::var("L1_RPC_ENDPOINT").unwrap(); + let dispute_game_factory_str = std::env::var("DISPUTE_GAME_FACTORY").unwrap(); + let dispute_game_facatory_addr = Address::from_str(&dispute_game_factory_str).unwrap(); + // create L1 signer provider + let local_signer = PrivateKeySigner::from_str(&l1_private_key_str).unwrap(); + let l1_provider = ProviderBuilder::new() + .wallet(EthereumWallet::from(local_signer)) + .connect(&l1_rpc_endpoint) + .await + .unwrap(); + // create Alloy proof system client + let alloy_proof_system_client = proof_system_client(l1_provider, dispute_game_facatory_addr) + .await + .unwrap(); + // create a bad proposal with a bad root claim + let anchor = alloy_proof_system_client.lineage_anchor().await.unwrap(); + let registered_block_interval = alloy_proof_system_client + .registered_lineage_config() + .block_interval; + let bad_root_claim = B256::with_last_byte(2); + let bad_proposal = Proposal { + parent_ref: anchor.address, + root_claim: bad_root_claim, + l2_block_number: anchor + .l2_block_number + .saturating_add(registered_block_interval), + attempt: 0, + }; + // submit bad proposal + let proposal_submission = alloy_proof_system_client + .submit_proposal(&bad_proposal) + .await + .unwrap(); + // save ProposalSubmission to a .json file + std::fs::write( + "submit_bad_proposal.json", + serde_json::to_string_pretty(&proposal_submission).unwrap(), + ) + .unwrap() +} + +#[tokio::test] +#[ignore] +async fn challenge() { + // fetch env vars + let l1_private_key_str = std::env::var("L1_PRIVATE_KEY").unwrap(); + let l1_rpc_endpoint = std::env::var("L1_RPC_ENDPOINT").unwrap(); + // create L1 signer provider + let local_signer = PrivateKeySigner::from_str(&l1_private_key_str).unwrap(); + let local_signer_addr = local_signer.address(); + let l1_provider = ProviderBuilder::new() + .wallet(EthereumWallet::from(local_signer)) + .connect(&l1_rpc_endpoint) + .await + .unwrap(); + // read ProposalSubmission from .json file + let proposal_submission: ProposalSubmission = + serde_json::from_slice(&std::fs::read("submit_bad_proposal.json").unwrap()).unwrap(); + // challenge the game + let game_instance = + IMultiProofGameInstance::new(proposal_submission.game_address, &l1_provider); + let challenge_pending_tx = game_instance.challenge().send().await.unwrap(); + let challenge_receipt = challenge_pending_tx.get_receipt().await.unwrap(); + assert!(challenge_receipt.status()); + // ensure the challenger is actually local_signer_addr + let challenger_addr = game_instance.challenger().call().await.unwrap(); + assert_eq!(challenger_addr, local_signer_addr); +} diff --git a/e2e-tests/src/it/alphanet/bad_proposal_is_challenged_and_invalidated.rs b/e2e-tests/src/it/alphanet/bad_proposal_is_challenged_and_invalidated.rs new file mode 100644 index 000000000..f2532c04e --- /dev/null +++ b/e2e-tests/src/it/alphanet/bad_proposal_is_challenged_and_invalidated.rs @@ -0,0 +1,181 @@ +use crate::it::utils::devnet::{ + GAME_CHALLENGER_WINS, IMockBondToken, proof_system_client, wait_for_challenge_with_timeout, +}; +use alloy_eips::BlockId; +use alloy_network::EthereumWallet; +use alloy_primitives::{Address, U256}; +use alloy_provider::{Provider, ProviderBuilder}; +use alloy_signer_local::PrivateKeySigner; +use revm_primitives::B256; +use std::{str::FromStr, time::Duration}; +use world_chain_proof_protocol::{ + IDisputeGameFactory::IDisputeGameFactoryInstance, + IERC20StakingVault::IERC20StakingVaultInstance, IMultiProofGame::IMultiProofGameInstance, + LineageProvider, read_registered_bond_vault, +}; +use world_chain_proposer::{Proposal, ProposalSubmission, ProposerClient}; + +/// Mock bond tokens deposited for each throwaway proof-system participant (100 tokens). +const THROWAWAY_ACCOUNT_BOND_TOKEN_BALANCE: u128 = 100_000_000_000_000_000_000; + +#[tokio::test] +#[ignore] +async fn fund_l1_signer_mock_token() { + // fetch env vars + let l1_private_key_str = std::env::var("L1_PRIVATE_KEY").unwrap(); + let l1_rpc_endpoint = std::env::var("L1_RPC_ENDPOINT").unwrap(); + let dispute_game_factory_str = std::env::var("DISPUTE_GAME_FACTORY").unwrap(); + let dispute_game_facatory_addr = Address::from_str(&dispute_game_factory_str).unwrap(); + // create L1 signer provider + let local_signer = PrivateKeySigner::from_str(&l1_private_key_str).unwrap(); + let local_signer_addr = local_signer.address(); + let l1_provider = ProviderBuilder::new() + .wallet(EthereumWallet::from(local_signer)) + .connect(&l1_rpc_endpoint) + .await + .unwrap(); + // create dispute game factory instance + let dispute_game_factory_instance = + IDisputeGameFactoryInstance::new(dispute_game_facatory_addr, l1_provider.clone()); + // read the registered bond vault contract + let bond_vault_addr = read_registered_bond_vault(&l1_provider, &dispute_game_factory_instance) + .await + .unwrap(); + let bond_vault_instance = IERC20StakingVaultInstance::new(bond_vault_addr, &l1_provider); + // get the bond token contract + let bond_token_address = bond_vault_instance.token().call().await.unwrap(); + let mock_bond_token = IMockBondToken::new(bond_token_address, &l1_provider); + // mint tokens + let amount = U256::from(THROWAWAY_ACCOUNT_BOND_TOKEN_BALANCE); + let mint_pending_tx = mock_bond_token + .mint(local_signer_addr, amount) + .send() + .await + .unwrap(); + let mint_receipt = mint_pending_tx.get_receipt().await.unwrap(); + assert!(mint_receipt.status()); + // approve mock tokens to be used by the bond vault contract + let approve_pending_tx = mock_bond_token + .approve(bond_vault_addr, amount) + .send() + .await + .unwrap(); + let approve_receipt = approve_pending_tx.get_receipt().await.unwrap(); + assert!(approve_receipt.status()); + // deposit mock tokens into the bond vault contract + let deposit_pending_tx = bond_vault_instance + .deposit(local_signer_addr, amount) + .send() + .await + .unwrap(); + let deposit_receipt = deposit_pending_tx.get_receipt().await.unwrap(); + assert!(deposit_receipt.status()); +} + +#[tokio::test] +#[ignore] +async fn submit_bad_proposal() { + // fetch env vars + let l1_private_key_str = std::env::var("L1_PRIVATE_KEY").unwrap(); + let l1_rpc_endpoint = std::env::var("L1_RPC_ENDPOINT").unwrap(); + let dispute_game_factory_str = std::env::var("DISPUTE_GAME_FACTORY").unwrap(); + let dispute_game_facatory_addr = Address::from_str(&dispute_game_factory_str).unwrap(); + // create L1 signer provider + let local_signer = PrivateKeySigner::from_str(&l1_private_key_str).unwrap(); + let l1_provider = ProviderBuilder::new() + .wallet(EthereumWallet::from(local_signer)) + .connect(&l1_rpc_endpoint) + .await + .unwrap(); + // create Alloy proof system client + let alloy_proof_system_client = proof_system_client(l1_provider, dispute_game_facatory_addr) + .await + .unwrap(); + // create a bad proposal with a bad root claim + let anchor = alloy_proof_system_client.lineage_anchor().await.unwrap(); + let registered_block_interval = alloy_proof_system_client + .registered_lineage_config() + .block_interval; + let bad_root_claim = B256::with_last_byte(1); + let bad_proposal = Proposal { + parent_ref: anchor.address, + root_claim: bad_root_claim, + l2_block_number: anchor + .l2_block_number + .saturating_add(registered_block_interval), + attempt: 0, + }; + // submit bad proposal + let proposal_submission = alloy_proof_system_client + .submit_proposal(&bad_proposal) + .await + .unwrap(); + // save ProposalSubmission to a .json file + std::fs::write( + "submit_bad_proposal.json", + serde_json::to_string_pretty(&proposal_submission).unwrap(), + ) + .unwrap() +} + +#[tokio::test] +#[ignore] +async fn wait_for_challenger() { + // fetch env vars + let l1_private_key_str = std::env::var("L1_PRIVATE_KEY").unwrap(); + let l1_rpc_endpoint = std::env::var("L1_RPC_ENDPOINT").unwrap(); + // create L1 signer provider + let local_signer = PrivateKeySigner::from_str(&l1_private_key_str).unwrap(); + let l1_provider = ProviderBuilder::new() + .wallet(EthereumWallet::from(local_signer)) + .connect(&l1_rpc_endpoint) + .await + .unwrap(); + // read ProposalSubmission from .json file + let proposal_submission: ProposalSubmission = + serde_json::from_slice(&std::fs::read("submit_bad_proposal.json").unwrap()).unwrap(); + // wait for the game to be challenged + let timeout = Duration::from_secs(10); + let game_instance = IMultiProofGameInstance::new(proposal_submission.game_address, l1_provider); + let challenger_addr = wait_for_challenge_with_timeout(&game_instance, timeout) + .await + .unwrap(); + println!("challenger address: {challenger_addr}"); + // assert defender is not defending this game + let proof_bitmap = game_instance.proofBitmap().call().await.unwrap(); + assert_eq!(proof_bitmap, 0); +} + +#[tokio::test] +#[ignore] +async fn wait_for_challenger_wins() { + // fetch env vars + let l1_private_key_str = std::env::var("L1_PRIVATE_KEY").unwrap(); + let l1_rpc_endpoint = std::env::var("L1_RPC_ENDPOINT").unwrap(); + // create L1 signer provider + let local_signer = PrivateKeySigner::from_str(&l1_private_key_str).unwrap(); + let l1_provider = ProviderBuilder::new() + .wallet(EthereumWallet::from(local_signer)) + .connect(&l1_rpc_endpoint) + .await + .unwrap(); + let proposal_submission: ProposalSubmission = + serde_json::from_slice(&std::fs::read("submit_bad_proposal.json").unwrap()).unwrap(); + // assert proof deadline is elapsed + let game_instance = + IMultiProofGameInstance::new(proposal_submission.game_address, &l1_provider); + let proof_deadline = game_instance.proofDeadline().call().await.unwrap(); + let latest_block = l1_provider + .get_block(BlockId::latest()) + .await + .unwrap() + .unwrap(); + let latest_block_timestamp = latest_block.header.timestamp; + assert!( + latest_block_timestamp > proof_deadline, + "proof deadline has not elapsed yet - latest block timestamp: {latest_block_timestamp}, proof deadline: {proof_deadline}" + ); + // assert that the game has resolved `CHALLENGER_WINS` + let status = game_instance.status().call().await.unwrap(); + assert_eq!(status, GAME_CHALLENGER_WINS); +} diff --git a/e2e-tests/src/it/alphanet/challenge_valid_game.rs b/e2e-tests/src/it/alphanet/challenge_valid_game.rs new file mode 100644 index 000000000..ed52cd09c --- /dev/null +++ b/e2e-tests/src/it/alphanet/challenge_valid_game.rs @@ -0,0 +1,98 @@ +//! A valid game that gets challenged should still be able to end up `DEFENDER_WINS`. + +use crate::it::utils::devnet::{GAME_DEFENDER_WINS, GAME_IN_PROGRESS}; +use alloy_network::EthereumWallet; +use alloy_primitives::Address; +use alloy_provider::ProviderBuilder; +use alloy_signer_local::PrivateKeySigner; +use revm_primitives::U256; +use std::str::FromStr; +use world_chain_proof_protocol::{ + ConsensusProvider, IDisputeGameFactory::IDisputeGameFactoryInstance, + IMultiProofGame::IMultiProofGameInstance, OptimismConsensusClient, +}; + +#[tokio::test] +#[ignore] +async fn challenge_valid_game() { + // fetch env vars + let l1_private_key_str = std::env::var("L1_PRIVATE_KEY").unwrap(); + let l1_rpc_endpoint = std::env::var("L1_RPC_ENDPOINT").unwrap(); + let l2_op_consensus_endpoint = std::env::var("L2_OP_CONSENSUS_ENDPOINT").unwrap(); + let dispute_game_factory_str = std::env::var("DISPUTE_GAME_FACTORY").unwrap(); + let dispute_game_factory_addr = Address::from_str(&dispute_game_factory_str).unwrap(); + // create L1 signer provider + let local_signer = PrivateKeySigner::from_str(&l1_private_key_str).unwrap(); + let l1_provider = ProviderBuilder::new() + .wallet(EthereumWallet::from(local_signer)) + .connect(&l1_rpc_endpoint) + .await + .unwrap(); + // create OptimismConsensusClient to fetch output roots + let op_consensus_client = OptimismConsensusClient::new(&l2_op_consensus_endpoint); + // fetch the latest valid game + let dispute_game_factory_instance = + IDisputeGameFactoryInstance::new(dispute_game_factory_addr, &l1_provider); + let game_count: u64 = dispute_game_factory_instance + .gameCount() + .call() + .await + .unwrap() + .try_into() + .unwrap(); + let mut valid_game = None; + for index in (0..game_count).rev() { + let game_at_index_return = dispute_game_factory_instance + .gameAtIndex(U256::from(index)) + .call() + .await + .unwrap(); + let game = IMultiProofGameInstance::new(game_at_index_return.proxy, &l1_provider); + let root_claim = game.rootClaim().call().await.unwrap(); + let l2_block_number = game.l2SequenceNumber().call().await.unwrap(); + let expected_root_claim = op_consensus_client + .output_root_at_block(l2_block_number.try_into().unwrap()) + .await + .unwrap(); + if root_claim == expected_root_claim { + valid_game = Some(game); + break; + } + } + let valid_game = valid_game.unwrap(); + // challenge valid game + let challenge_pending_tx = valid_game.challenge().send().await.unwrap(); + let challenge_receipt = challenge_pending_tx.get_receipt().await.unwrap(); + assert!(challenge_receipt.status()); + // save game address to a .json file + std::fs::write( + "challenged_game_addr.json", + serde_json::to_string_pretty(valid_game.address()).unwrap(), + ) + .unwrap() +} + +#[tokio::test] +#[ignore] +async fn wait_defender_wins() { + // fetch env vars + let l1_private_key_str = std::env::var("L1_PRIVATE_KEY").unwrap(); + let l1_rpc_endpoint = std::env::var("L1_RPC_ENDPOINT").unwrap(); + // create L1 signer provider + let local_signer = PrivateKeySigner::from_str(&l1_private_key_str).unwrap(); + let l1_provider = ProviderBuilder::new() + .wallet(EthereumWallet::from(local_signer)) + .connect(&l1_rpc_endpoint) + .await + .unwrap(); + // read challenged game address from .json file + let game_addr: Address = + serde_json::from_slice(&std::fs::read("challenged_game_addr.json").unwrap()).unwrap(); + let game_instance = IMultiProofGameInstance::new(game_addr, &l1_provider); + // check for defender wins + let status = game_instance.status().call().await.unwrap(); + // ensure the game is not in progress anymore + assert_ne!(status, GAME_IN_PROGRESS); + // ensure the game is DEFENDER_WINS + assert_eq!(status, GAME_DEFENDER_WINS); +} diff --git a/e2e-tests/src/it/alphanet/invalid_game_with_invalid_parent.rs b/e2e-tests/src/it/alphanet/invalid_game_with_invalid_parent.rs new file mode 100644 index 000000000..d9d74e674 --- /dev/null +++ b/e2e-tests/src/it/alphanet/invalid_game_with_invalid_parent.rs @@ -0,0 +1,155 @@ +use crate::it::utils::devnet::{ + GAME_CHALLENGER_WINS, proof_system_client, wait_for_challenge_with_timeout, +}; +use alloy_eips::BlockId; +use alloy_network::EthereumWallet; +use alloy_primitives::{Address, B256}; +use alloy_provider::{Provider, ProviderBuilder}; +use alloy_signer_local::PrivateKeySigner; +use std::{str::FromStr, time::Duration}; +use world_chain_proof_protocol::{IMultiProofGame::IMultiProofGameInstance, LineageProvider}; +use world_chain_proposer::{Proposal, ProposalSubmission, ProposerClient}; + +#[tokio::test] +#[ignore] +async fn submit_2_bad_consecutive_proposals() { + // fetch env vars + let l1_private_key_str = std::env::var("L1_PRIVATE_KEY").unwrap(); + let l1_rpc_endpoint = std::env::var("L1_RPC_ENDPOINT").unwrap(); + let dispute_game_factory_str = std::env::var("DISPUTE_GAME_FACTORY").unwrap(); + let dispute_game_facatory_addr = Address::from_str(&dispute_game_factory_str).unwrap(); + // create L1 signer provider + let local_signer = PrivateKeySigner::from_str(&l1_private_key_str).unwrap(); + let l1_provider = ProviderBuilder::new() + .wallet(EthereumWallet::from(local_signer)) + .connect(&l1_rpc_endpoint) + .await + .unwrap(); + // create Alloy proof system client + let alloy_proof_system_client = proof_system_client(l1_provider, dispute_game_facatory_addr) + .await + .unwrap(); + // create a bad proposal with a bad root claim + let anchor = alloy_proof_system_client.lineage_anchor().await.unwrap(); + let registered_block_interval = alloy_proof_system_client + .registered_lineage_config() + .block_interval; + let bad_root_claim = B256::with_last_byte(3); + let l2_block_number = anchor + .l2_block_number + .saturating_add(registered_block_interval); + let bad_proposal = Proposal { + parent_ref: anchor.address, + root_claim: bad_root_claim, + l2_block_number, + attempt: 0, + }; + // submit first bad proposal + let first_proposal_submission = alloy_proof_system_client + .submit_proposal(&bad_proposal) + .await + .unwrap(); + // create a child invalid game + let bad_root_claim = B256::with_last_byte(4); + let l2_block_number = l2_block_number.saturating_add(registered_block_interval); + let bad_proposal = Proposal { + parent_ref: first_proposal_submission.game_address, + root_claim: bad_root_claim, + l2_block_number, + attempt: 0, + }; + // submit second bad proposal + let second_proposal_submission = alloy_proof_system_client + .submit_proposal(&bad_proposal) + .await + .unwrap(); + // save ProposalSubmissions to a .json file + let proposal_submissions = vec![first_proposal_submission, second_proposal_submission]; + std::fs::write( + "proposal_submissions.json", + serde_json::to_string_pretty(&proposal_submissions).unwrap(), + ) + .unwrap() +} + +#[tokio::test] +#[ignore] +async fn wait_for_challenger() { + // fetch env vars + let l1_private_key_str = std::env::var("L1_PRIVATE_KEY").unwrap(); + let l1_rpc_endpoint = std::env::var("L1_RPC_ENDPOINT").unwrap(); + // create L1 signer provider + let local_signer = PrivateKeySigner::from_str(&l1_private_key_str).unwrap(); + let l1_provider = ProviderBuilder::new() + .wallet(EthereumWallet::from(local_signer)) + .connect(&l1_rpc_endpoint) + .await + .unwrap(); + // read ProposalSubmissions from .json file + let proposal_submissions: Vec = + serde_json::from_slice(&std::fs::read("proposal_submissions.json").unwrap()).unwrap(); + assert_eq!(proposal_submissions.len(), 2); + // wait for the 1st game to be challenged + let timeout = Duration::from_secs(10); + let first_game_addr = proposal_submissions[0].game_address; + let game_instance = IMultiProofGameInstance::new(first_game_addr, &l1_provider); + let challenger_addr = wait_for_challenge_with_timeout(&game_instance, timeout) + .await + .unwrap(); + println!("challenger address of 1st game: {challenger_addr}"); + // assert defender is not defending this game + let proof_bitmap = game_instance.proofBitmap().call().await.unwrap(); + assert_eq!(proof_bitmap, 0); + // wait for the 2nd game to be challenged + let timeout = Duration::from_secs(10); + let second_game_addr = proposal_submissions[1].game_address; + let game_instance = IMultiProofGameInstance::new(second_game_addr, &l1_provider); + let challenger_addr = wait_for_challenge_with_timeout(&game_instance, timeout) + .await + .unwrap(); + println!("challenger address of 2nd game: {challenger_addr}"); + // assert defender is not defending this game + let proof_bitmap = game_instance.proofBitmap().call().await.unwrap(); + assert_eq!(proof_bitmap, 0); +} + +#[tokio::test] +#[ignore] +async fn wait_for_challenger_wins() { + // fetch env vars + let l1_private_key_str = std::env::var("L1_PRIVATE_KEY").unwrap(); + let l1_rpc_endpoint = std::env::var("L1_RPC_ENDPOINT").unwrap(); + // create L1 signer provider + let local_signer = PrivateKeySigner::from_str(&l1_private_key_str).unwrap(); + let l1_provider = ProviderBuilder::new() + .wallet(EthereumWallet::from(local_signer)) + .connect(&l1_rpc_endpoint) + .await + .unwrap(); + // read ProposalSubmissions from .json file + let proposal_submissions: Vec = + serde_json::from_slice(&std::fs::read("proposal_submissions.json").unwrap()).unwrap(); + assert_eq!(proposal_submissions.len(), 2); + // assert proof deadline of 2nd game is elapsed, this way proof deadline of 1st game is elapsed too + let second_game_addr = proposal_submissions[1].game_address; + let second_game_instance = IMultiProofGameInstance::new(second_game_addr, &l1_provider); + let proof_deadline = second_game_instance.proofDeadline().call().await.unwrap(); + let latest_block = l1_provider + .get_block(BlockId::latest()) + .await + .unwrap() + .unwrap(); + let latest_block_timestamp = latest_block.header.timestamp; + assert!( + latest_block_timestamp > proof_deadline, + "proof deadline has not elapsed yet - latest block timestamp: {latest_block_timestamp}, proof deadline: {proof_deadline}" + ); + // assert that the 1st game has resolved `CHALLENGER_WINS` + let first_game_addr = proposal_submissions[0].game_address; + let first_game_instance = IMultiProofGameInstance::new(first_game_addr, &l1_provider); + let status = first_game_instance.status().call().await.unwrap(); + assert_eq!(status, GAME_CHALLENGER_WINS); + // assert that the 2nd game has resolved `CHALLENGER_WINS` + let status = second_game_instance.status().call().await.unwrap(); + assert_eq!(status, GAME_CHALLENGER_WINS); +} diff --git a/e2e-tests/src/it/alphanet/mod.rs b/e2e-tests/src/it/alphanet/mod.rs new file mode 100644 index 000000000..da62f6928 --- /dev/null +++ b/e2e-tests/src/it/alphanet/mod.rs @@ -0,0 +1,6 @@ +mod already_challenged_game_is_ignored; +mod bad_proposal_is_challenged_and_invalidated; +mod challenge_valid_game; +mod invalid_game_with_invalid_parent; +mod valid_game_with_invalid_parent; +mod withdrawal; diff --git a/e2e-tests/src/it/alphanet/valid_game_with_invalid_parent.rs b/e2e-tests/src/it/alphanet/valid_game_with_invalid_parent.rs new file mode 100644 index 000000000..5f8b50c79 --- /dev/null +++ b/e2e-tests/src/it/alphanet/valid_game_with_invalid_parent.rs @@ -0,0 +1,168 @@ +use crate::it::utils::devnet::{ + GAME_CHALLENGER_WINS, INVALIDATION_REASON_INVALID_PARENT, INVALIDATION_REASON_PROOF_TIMEOUT, + proof_system_client, wait_for_challenge_with_timeout, +}; +use alloy_eips::BlockId; +use alloy_network::EthereumWallet; +use alloy_primitives::{Address, B256}; +use alloy_provider::{Provider, ProviderBuilder}; +use alloy_signer_local::PrivateKeySigner; +use std::{str::FromStr, time::Duration}; +use world_chain_proof_protocol::{ + ConsensusProvider, IMultiProofGame::IMultiProofGameInstance, LineageProvider, + OptimismConsensusClient, +}; +use world_chain_proposer::{Proposal, ProposalSubmission, ProposerClient}; + +#[tokio::test] +#[ignore] +async fn submit_1_bad_1_valid_games() { + // fetch env vars + let l1_private_key_str = std::env::var("L1_PRIVATE_KEY").unwrap(); + let l1_rpc_endpoint = std::env::var("L1_RPC_ENDPOINT").unwrap(); + let l2_op_consensus_endpoint = std::env::var("L2_OP_CONSENSUS_ENDPOINT").unwrap(); + let dispute_game_factory_str = std::env::var("DISPUTE_GAME_FACTORY").unwrap(); + let dispute_game_facatory_addr = Address::from_str(&dispute_game_factory_str).unwrap(); + // create L1 signer provider + let local_signer = PrivateKeySigner::from_str(&l1_private_key_str).unwrap(); + let l1_provider = ProviderBuilder::new() + .wallet(EthereumWallet::from(local_signer)) + .connect(&l1_rpc_endpoint) + .await + .unwrap(); + // create Alloy proof system client + let alloy_proof_system_client = proof_system_client(l1_provider, dispute_game_facatory_addr) + .await + .unwrap(); + // create OptimismConsensusClient to fetch output roots + let op_consensus_client = OptimismConsensusClient::new(&l2_op_consensus_endpoint); + // create a bad proposal with a bad root claim + let anchor = alloy_proof_system_client.lineage_anchor().await.unwrap(); + let registered_block_interval = alloy_proof_system_client + .registered_lineage_config() + .block_interval; + let bad_root_claim = B256::with_last_byte(5); + let l2_block_number = anchor + .l2_block_number + .saturating_add(registered_block_interval); + let bad_proposal = Proposal { + parent_ref: anchor.address, + root_claim: bad_root_claim, + l2_block_number, + attempt: 0, + }; + // submit first bad proposal + let first_proposal_submission = alloy_proof_system_client + .submit_proposal(&bad_proposal) + .await + .unwrap(); + // create a child valid game (that will still be invalidated due to `INVALID_PARENT`) + let l2_block_number = l2_block_number.saturating_add(registered_block_interval); + let valid_root_claim = op_consensus_client + .output_root_at_block(l2_block_number) + .await + .unwrap(); + let bad_proposal = Proposal { + parent_ref: first_proposal_submission.game_address, + root_claim: valid_root_claim, + l2_block_number, + attempt: 0, + }; + // submit second proposal + let second_proposal_submission = alloy_proof_system_client + .submit_proposal(&bad_proposal) + .await + .unwrap(); + // save ProposalSubmissions to a .json file + let proposal_submissions = vec![first_proposal_submission, second_proposal_submission]; + std::fs::write( + "proposal_subs.json", + serde_json::to_string_pretty(&proposal_submissions).unwrap(), + ) + .unwrap() +} + +#[tokio::test] +#[ignore] +async fn wait_for_challenger() { + // fetch env vars + let l1_private_key_str = std::env::var("L1_PRIVATE_KEY").unwrap(); + let l1_rpc_endpoint = std::env::var("L1_RPC_ENDPOINT").unwrap(); + // create L1 signer provider + let local_signer = PrivateKeySigner::from_str(&l1_private_key_str).unwrap(); + let l1_provider = ProviderBuilder::new() + .wallet(EthereumWallet::from(local_signer)) + .connect(&l1_rpc_endpoint) + .await + .unwrap(); + // read ProposalSubmissions from .json file + let proposal_submissions: Vec = + serde_json::from_slice(&std::fs::read("proposal_subs.json").unwrap()).unwrap(); + assert_eq!(proposal_submissions.len(), 2); + // wait for the 1st game to be challenged + let timeout = Duration::from_secs(10); + let first_game_addr = proposal_submissions[0].game_address; + let game_instance = IMultiProofGameInstance::new(first_game_addr, &l1_provider); + let challenger_addr = wait_for_challenge_with_timeout(&game_instance, timeout) + .await + .unwrap(); + println!("challenger address of 1st game: {challenger_addr}"); + // assert defender is not defending this game + let proof_bitmap = game_instance.proofBitmap().call().await.unwrap(); + assert_eq!(proof_bitmap, 0); + // note that the 2nd child game won't be challenged because it contains a valid root claim. + // It will still end up invalidated with `INVALID_PARENT` as invalidation reason. +} + +#[tokio::test] +#[ignore] +async fn wait_for_challenger_wins() { + // fetch env vars + let l1_private_key_str = std::env::var("L1_PRIVATE_KEY").unwrap(); + let l1_rpc_endpoint = std::env::var("L1_RPC_ENDPOINT").unwrap(); + // create L1 signer provider + let local_signer = PrivateKeySigner::from_str(&l1_private_key_str).unwrap(); + let l1_provider = ProviderBuilder::new() + .wallet(EthereumWallet::from(local_signer)) + .connect(&l1_rpc_endpoint) + .await + .unwrap(); + // read ProposalSubmissions from .json file + let proposal_submissions: Vec = + serde_json::from_slice(&std::fs::read("proposal_subs.json").unwrap()).unwrap(); + assert_eq!(proposal_submissions.len(), 2); + // assert proof deadline of 2nd game is elapsed, this way proof deadline of 1st game is elapsed too + let second_game_addr = proposal_submissions[1].game_address; + let second_game_instance = IMultiProofGameInstance::new(second_game_addr, &l1_provider); + let proof_deadline = second_game_instance.proofDeadline().call().await.unwrap(); + let latest_block = l1_provider + .get_block(BlockId::latest()) + .await + .unwrap() + .unwrap(); + let latest_block_timestamp = latest_block.header.timestamp; + assert!( + latest_block_timestamp > proof_deadline, + "proof deadline has not elapsed yet - latest block timestamp: {latest_block_timestamp}, proof deadline: {proof_deadline}" + ); + // assert that the 1st game has resolved `CHALLENGER_WINS` + let first_game_addr = proposal_submissions[0].game_address; + let first_game_instance = IMultiProofGameInstance::new(first_game_addr, &l1_provider); + let status = first_game_instance.status().call().await.unwrap(); + assert_eq!(status, GAME_CHALLENGER_WINS); + let invalidation_reason = first_game_instance + .invalidationReason() + .call() + .await + .unwrap(); + assert_eq!(invalidation_reason, INVALIDATION_REASON_PROOF_TIMEOUT); + // assert that the 2nd game has resolved `CHALLENGER_WINS` + let status = second_game_instance.status().call().await.unwrap(); + assert_eq!(status, GAME_CHALLENGER_WINS); + let invalidation_reason = second_game_instance + .invalidationReason() + .call() + .await + .unwrap(); + assert_eq!(invalidation_reason, INVALIDATION_REASON_INVALID_PARENT); +} diff --git a/e2e-tests/src/it/alphanet/withdrawal.rs b/e2e-tests/src/it/alphanet/withdrawal.rs new file mode 100644 index 000000000..c769e219a --- /dev/null +++ b/e2e-tests/src/it/alphanet/withdrawal.rs @@ -0,0 +1,184 @@ +use crate::it::utils::{ + devnet::wait_for_multi_proof_game_with_timeout, + withdrawals::{ + AnchorStateRegistry::AnchorStateRegistryInstance, InitiatedWithdrawal, + OptimismPortal::OptimismPortalInstance, ProveWithdrawal, build_withdrawal_proof, + initiate_withdrawal, + }, +}; +use alloy_eips::BlockId; +use alloy_network::{EthereumWallet, ReceiptResponse}; +use alloy_provider::{Provider, ProviderBuilder}; +use alloy_signer_local::PrivateKeySigner; +use revm_primitives::{Address, U256}; +use std::{str::FromStr, time::Duration}; + +#[tokio::test] +#[ignore] +async fn init_withdrawal() { + // fetch env vars + let l2_private_key_str = std::env::var("L2_PRIVATE_KEY").unwrap(); + let l2_rpc_endpoint = std::env::var("L2_RPC_ENDPOINT").unwrap(); + // create L2 signer provider + let local_signer = PrivateKeySigner::from_str(&l2_private_key_str).unwrap(); + let local_signer_addr = local_signer.address(); + let l2_provider = ProviderBuilder::new() + .wallet(EthereumWallet::from(local_signer)) + .connect(&l2_rpc_endpoint) + .await + .unwrap(); + // target address of the L2 -> L1 withdrawal is the same address that sends the tx on L2 + let target_addr = local_signer_addr; + // sends the initiate_withdrawal transaction to the L2ToL1MessagePasser contract + let initiated_withdrawal = initiate_withdrawal(l2_provider, target_addr).await.unwrap(); + // save the InitiatedWithdrawal data to a .json file + std::fs::write( + "initiated_withdrawal.json", + serde_json::to_string_pretty(&initiated_withdrawal).unwrap(), + ) + .unwrap(); +} + +#[tokio::test] +#[ignore] +async fn prove_withdrawal() { + // fetch env vars + let l1_private_key_str = std::env::var("L1_PRIVATE_KEY").unwrap(); + let l1_rpc_endpoint = std::env::var("L1_RPC_ENDPOINT").unwrap(); + let dispute_game_factory_str = std::env::var("DISPUTE_GAME_FACTORY").unwrap(); + let dispute_game_facatory_addr = Address::from_str(&dispute_game_factory_str).unwrap(); + let l2_rpc_endpoint = std::env::var("L2_RPC_ENDPOINT").unwrap(); + let optimism_portal_str = std::env::var("OPTIMISM_PORTAL").unwrap(); + let optimism_portal_addr = Address::from_str(&optimism_portal_str).unwrap(); + // create L1 signer provider + let local_signer = PrivateKeySigner::from_str(&l1_private_key_str).unwrap(); + let l1_provider = ProviderBuilder::new() + .wallet(EthereumWallet::from(local_signer)) + .connect(&l1_rpc_endpoint) + .await + .unwrap(); + // create L2 provider + let l2_provider = ProviderBuilder::new() + .connect(&l2_rpc_endpoint) + .await + .unwrap(); + // read InitiatedWithdrawl data from .json file + let initiated_withdrawal: InitiatedWithdrawal = + serde_json::from_slice(&std::fs::read("initiated_withdrawal.json").unwrap()).unwrap(); + // wait for a covering WIP1006 game with l2SequenceNumber >= initiated_withdrawal.l2_block + let timeout = Duration::from_secs(10); + let (game_index, game_addr, game_l2_block) = wait_for_multi_proof_game_with_timeout( + &l1_provider, + dispute_game_facatory_addr, + initiated_withdrawal.l2_block, + timeout, + ) + .await + .unwrap(); + // get the output root proof and the withdrawal proof + let (output_root_proof, withdrawal_proof) = + build_withdrawal_proof(l2_provider, game_l2_block, initiated_withdrawal.hash) + .await + .unwrap(); + // send the OptimismPortal::proveWithdrawalTransaction + let optimism_portal = OptimismPortalInstance::new(optimism_portal_addr, &l1_provider); + let pending_tx = optimism_portal + .proveWithdrawalTransaction( + initiated_withdrawal.transaction.clone(), + U256::from(game_index), + output_root_proof, + withdrawal_proof, + ) + .send() + .await + .unwrap(); + let receipt = pending_tx.get_receipt().await.unwrap(); + assert!(receipt.status()); + // get the L1 timestamp of the block that includes this proveWithdrawal + let block_number = receipt.block_number().unwrap(); + let block = l1_provider + .get_block(BlockId::number(block_number)) + .await + .unwrap() + .unwrap(); + let l1_timestamp = block.header.timestamp; + // save useful data into a .json file + let prove_withdrawal = ProveWithdrawal { + transaction: initiated_withdrawal.transaction, + hash: initiated_withdrawal.hash, + game_index, + game_l2_block, + game_addr, + proven_at: l1_timestamp, + }; + std::fs::write( + "prove_withdrawal.json", + serde_json::to_string_pretty(&prove_withdrawal).unwrap(), + ) + .unwrap(); +} + +#[tokio::test] +#[ignore] +async fn finalize_withdrawal() { + // fetch env vars + let l1_private_key_str = std::env::var("L1_PRIVATE_KEY").unwrap(); + let l1_rpc_endpoint = std::env::var("L1_RPC_ENDPOINT").unwrap(); + let anchor_state_registry_str = std::env::var("ANCHOR_STATE_REGISTRY").unwrap(); + let anchor_state_registry_addr = Address::from_str(&anchor_state_registry_str).unwrap(); + let optimism_portal_str = std::env::var("OPTIMISM_PORTAL").unwrap(); + let optimism_portal_addr = Address::from_str(&optimism_portal_str).unwrap(); + // create L1 signer provider + let local_signer = PrivateKeySigner::from_str(&l1_private_key_str).unwrap(); + let l1_provider = ProviderBuilder::new() + .wallet(EthereumWallet::from(local_signer)) + .connect(&l1_rpc_endpoint) + .await + .unwrap(); + // read ProveWithdrawl data from .json file + let prove_withdrawal: ProveWithdrawal = + serde_json::from_slice(&std::fs::read("prove_withdrawal.json").unwrap()).unwrap(); + // check whether the withdrawal is finalizable: + // 1. now - proven.timestamp > OptimismPortal::proofMaturityDelaySeconds() + let optimism_portal = OptimismPortalInstance::new(optimism_portal_addr, &l1_provider); + let latest_block = l1_provider + .get_block(BlockId::latest()) + .await + .unwrap() + .unwrap(); + let now = latest_block.header.timestamp; + let proof_maturity_delay_seconds = optimism_portal + .proofMaturityDelaySeconds() + .call() + .await + .unwrap(); + assert!( + U256::from(now - prove_withdrawal.proven_at) > proof_maturity_delay_seconds, + "proof maturity is not elapsed yet" + ); + // 2. ASR.isGameClaimValid must return true + let anchor_state_registry = + AnchorStateRegistryInstance::new(anchor_state_registry_addr, &l1_provider); + let is_game_claim_valid = anchor_state_registry + .isGameClaimValid(prove_withdrawal.game_addr) + .call() + .await + .unwrap(); + assert!(is_game_claim_valid, "game claim is not valid"); + // send the OptimismPortal::finalizeWithdrawal + let pending_tx = optimism_portal + .finalizeWithdrawalTransaction(prove_withdrawal.transaction) + .send() + .await + .unwrap(); + let receipt = pending_tx.get_receipt().await.unwrap(); + assert!(receipt.status()); + assert!( + optimism_portal + .finalizedWithdrawals(prove_withdrawal.hash) + .call() + .await + .unwrap(), + "Portal did not persist the finalized withdrawal" + ); +} diff --git a/e2e-tests/src/it/devnet_challenge.rs b/e2e-tests/src/it/devnet_challenge.rs index 72d11783e..ebce20acf 100644 --- a/e2e-tests/src/it/devnet_challenge.rs +++ b/e2e-tests/src/it/devnet_challenge.rs @@ -1,13 +1,26 @@ -use alloy_primitives::{B256, U256}; -use eyre::eyre::ensure; -use world_chain_proof_protocol::LineageProvider; +use std::time::Duration; + +use alloy_primitives::{Address, B256, U256, address, utils::parse_ether}; +use alloy_provider::Provider; +use eyre::eyre::{ensure, eyre}; +use world_chain_proof_protocol::{IDisputeGameFactory, LineageProvider}; use world_chain_proposer::{Proposal, ProposerClient}; -use crate::it::utils::devnet::{ - GAME_CHALLENGER_WINS, advance_to_timestamp, funded_throwaway_provider, game_at, l1_contract, - l1_rpc_url, proof_system_client, try_build_ha_devnet, wait_for_challenge, wait_for_status, +use crate::it::utils::{ + bindings::IFaultDisputeGame::{GameStatus, IFaultDisputeGameInstance}, + devnet::{ + GAME_CHALLENGER_WINS, advance_to_timestamp, fund_address, funded_throwaway_provider, + game_at, l1_contract, l1_rpc_url, proof_system_client, try_build_ha_devnet, + try_build_ha_devnet_with_custom_block_time, vault_at, wait_for_challenge, wait_for_status, + }, }; +/// In-process World Chain challenger (`WORLD_CHALLENGER_PRIVATE_KEY` in +/// `crates/devnet/src/full_stack.rs`). +const WORLD_CHALLENGER_ADDRESS: Address = address!("0x743dAA55063C608894C125Cf8eC82Afe83B2d5c5"); +/// Long enough for several challenger poll ticks after the game is L1-finalized. +const CHALLENGER_IDLE_OBSERVATION: Duration = Duration::from_secs(20); + /// End-to-end fault path: a dishonest proposer posts a root that disagrees with consensus, the /// real challenger detects and challenges it, the real defender declines to defend it, and the /// game resolves `ChallengerWins` with the proposer's bond forfeited. @@ -28,7 +41,8 @@ async fn bad_root_proposal_is_challenged_and_invalidated() -> eyre::Result<()> { let factory_address = l1_contract(devnet.dispute_game_factory(), "DisputeGameFactory")?; // A throwaway signer standing in for a dishonest proposer. - let (malicious_address, malicious_provider) = funded_throwaway_provider(l1_rpc).await?; + let (malicious_address, malicious_provider) = + funded_throwaway_provider(l1_rpc, factory_address).await?; let contracts = proof_system_client(malicious_provider.clone(), factory_address).await?; // Wins the first proposal window: the honest proposer can't submit until `block_interval` L2 @@ -75,11 +89,214 @@ async fn bad_root_proposal_is_challenged_and_invalidated() -> eyre::Result<()> { "no proof lane should ever land on an invalidated game" ); ensure!( - game.credit(malicious_address).call().await? == U256::ZERO, - "the dishonest proposer's bond must not be creditable back to them" + game.gameCreator().call().await? == malicious_address, + "the proposal bond must remain attributed to the dishonest proposer" + ); + let vault = vault_at(game.bondVault().call().await?, malicious_provider.clone()); + let game_bond = vault.gameBonds(game_address).call().await?; + ensure!( + game.challenger().call().await? == challenger, + "the game did not attribute the challenge to the observed challenger" + ); + ensure!( + game_bond.proposerBond == game.proposerBond().call().await?, + "the vault did not lock the game's complete proposer bond" + ); + ensure!( + game_bond.challengerBond == game.challengerBond().call().await?, + "the vault did not lock the game's complete challenger bond" ); println!("devnet challenge: bad root at game {game_address} correctly resolved ChallengerWins"); Ok(()) } + +/// The challenger completely ignores games that are already expired. +#[ignore = "requires Docker, Foundry, and the full local OP Stack"] +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn already_expired_game_is_ignored() -> eyre::Result<()> { + reth_tracing::init_test_tracing(); + + let Some(devnet) = try_build_ha_devnet_with_custom_block_time( + "already expired game is ignored", + Duration::from_millis(200), // 200ms block time + ) + .await? + else { + return Ok(()); + }; + + let l1_rpc = l1_rpc_url(&devnet)?; + let factory_address = l1_contract(devnet.dispute_game_factory(), "DisputeGameFactory")?; + + let (address, provider) = funded_throwaway_provider(l1_rpc, factory_address).await?; + let contracts = proof_system_client(provider.clone(), factory_address).await?; + + // Wins the first proposal window: the honest proposer can't submit until `block_interval` L2 + // blocks are safe, several seconds out at devnet block time. + let anchor = contracts.lineage_anchor().await?; + let registered = contracts.registered_lineage_config(); + let bad_root = B256::repeat_byte(0xba); + let bad_proposal = Proposal { + parent_ref: anchor.address, + root_claim: bad_root, + l2_block_number: anchor + .l2_block_number + .saturating_add(registered.block_interval), + attempt: 0, + }; + + let submission = contracts.submit_proposal(&bad_proposal).await?; + let game_address = submission.game_address; + println!( + "devnet challenge: malicious proposer {address} posted bad root {bad_root} for l2 block {} at game {game_address}", + bad_proposal.l2_block_number + ); + let game = game_at(game_address, provider.clone()); + let proof_deadline = game.proofDeadline().call().await?; + advance_to_timestamp(&provider, proof_deadline.saturating_add(1)).await?; + // Sleep for ~30 secs so that the block that contains that game becomes finalized. + // Our challenger only looks at games contained in finalized blocks. + tokio::time::sleep(Duration::from_secs(30)).await; + let game_status = game.status().call().await?; + // The challenger doesn't challenge this game even if it contains an invalid root_claim + // because proof_deadline has already elapsed, therefore this game won't ever be considered + // valid anymore. + let expected_game_status = 0; // IN_PROGRESS + assert_eq!(game_status, expected_game_status); + Ok(()) +} + +/// The challenger completely ignores already challenged games. +/// +/// Game state alone cannot prove this: a second `challenge()` reverts with +/// `ClaimAlreadyChallenged` and leaves `challenger()` unchanged. We instead +/// assert the world challenger's L1 nonce does not move after it has had time +/// to see the finalized game. A mined (even reverted) challenge would bump it. +#[ignore = "requires Docker, Foundry, and the full local OP Stack"] +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn already_challenged_game_is_ignored() -> eyre::Result<()> { + reth_tracing::init_test_tracing(); + + let Some(devnet) = try_build_ha_devnet_with_custom_block_time( + "already challenged game is ignored", + Duration::from_millis(200), // 200ms block time + ) + .await? + else { + return Ok(()); + }; + + let l1_rpc = l1_rpc_url(&devnet)?; + let factory_address = l1_contract(devnet.dispute_game_factory(), "DisputeGameFactory")?; + + let (address, provider) = funded_throwaway_provider(l1_rpc, factory_address).await?; + let contracts = proof_system_client(provider.clone(), factory_address).await?; + + // Wins the first proposal window: the honest proposer can't submit until `block_interval` L2 + // blocks are safe, several seconds out at devnet block time. + let anchor = contracts.lineage_anchor().await?; + let registered = contracts.registered_lineage_config(); + let bad_root = B256::repeat_byte(0xba); + let bad_proposal = Proposal { + parent_ref: anchor.address, + root_claim: bad_root, + l2_block_number: anchor + .l2_block_number + .saturating_add(registered.block_interval), + attempt: 0, + }; + + let submission = contracts.submit_proposal(&bad_proposal).await?; + let game_address = submission.game_address; + println!( + "devnet challenge: malicious proposer {address} posted bad root {bad_root} for l2 block {} at game {game_address}", + bad_proposal.l2_block_number + ); + let game = game_at(game_address, provider.clone()); + // Challenge before L1 finalization so the real challenger first sees an already-challenged game. + let receipt = game.challenge().send().await?.get_receipt().await?; + assert!(receipt.status()); + assert_eq!(game.challenger().call().await?, address); + + // Sleep for ~30 secs so that the block that contains that game becomes finalized. + // Our challenger only looks at games contained in finalized blocks. + tokio::time::sleep(Duration::from_secs(30)).await; + + let nonce_before = provider + .get_transaction_count(WORLD_CHALLENGER_ADDRESS) + .await?; + tokio::time::sleep(CHALLENGER_IDLE_OBSERVATION).await; + let nonce_after = provider + .get_transaction_count(WORLD_CHALLENGER_ADDRESS) + .await?; + + assert_eq!(nonce_after, nonce_before,); + assert_eq!(game.challenger().call().await?, address); + Ok(()) +} + +/// The challenger completely ignores games that are not WIP1006 type. +#[ignore = "requires Docker, Foundry, and the full local OP Stack"] +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn unknown_game_type_is_ignored() -> eyre::Result<()> { + reth_tracing::init_test_tracing(); + // The type must be already set in the `DisputeGameFactory` contract, otherwise the creation + // of a game fails with `NoImplementation` error. + const PERMISSIONED_CANNON: u32 = 1; + const OP_PROPOSER_PRIVATE_KEY: &str = + "0xdbda1821b80551c9d65939329250298aa3472ba22feea921c0cf5d620ea67b97"; + + let Some(devnet) = try_build_ha_devnet_with_custom_block_time( + "unkown game type is ignored", + Duration::from_millis(200), // 200ms block time + ) + .await? + else { + return Ok(()); + }; + let l1_rpc = l1_rpc_url(&devnet)?; + let factory_address = l1_contract(devnet.dispute_game_factory(), "DisputeGameFactory")?; + + let provider = fund_address(l1_rpc, OP_PROPOSER_PRIVATE_KEY).await?; + let factory = + IDisputeGameFactory::IDisputeGameFactoryInstance::new(factory_address, provider.clone()); + + let dummy_root_claim = B256::ZERO; + // Extra data must be 32 bytes long in the permissioned cannon game. + // It represents the l2 block number. + let dummy_extra_data = U256::from(1).to_be_bytes::<32>().into(); + // Set 0.08 ether as the bond value for the game creation + let init_bond = parse_ether("0.08")?; + let pending_create_tx = factory + .create(PERMISSIONED_CANNON, dummy_root_claim, dummy_extra_data) + .value(init_bond) + .send() + .await?; + let receipt = pending_create_tx.get_receipt().await?; + assert!(receipt.status()); + let game_address = receipt + .logs() + .iter() + .filter(|log| log.address() == factory_address) + .find_map(|log| { + log.log_decode_validate::() + .ok() + .map(|decoded| decoded.inner.data) + }) + .filter(|event| { + event.gameType == PERMISSIONED_CANNON && event.rootClaim == dummy_root_claim + }) + .map(|event| event.disputeProxy) + .ok_or_else(|| eyre!("no game created"))?; + // Sleep for ~30 secs so that the block that contains that game becomes finalized. + // Our challenger only looks at games contained in finalized blocks. + tokio::time::sleep(Duration::from_secs(30)).await; + // Ensure that the game is still `IN_PROGRESS` because our challenger isn't triggered + // by an unknown game type that differs from WIP1006. + let fault_dispute_game = IFaultDisputeGameInstance::new(game_address, provider); + let status = fault_dispute_game.status().call().await?; + assert_eq!(status, GameStatus::IN_PROGRESS); + Ok(()) +} diff --git a/e2e-tests/src/it/devnet_proof_invariants.rs b/e2e-tests/src/it/devnet_proof_invariants.rs index 2d93d7542..22ea99ec6 100644 --- a/e2e-tests/src/it/devnet_proof_invariants.rs +++ b/e2e-tests/src/it/devnet_proof_invariants.rs @@ -7,15 +7,17 @@ use alloy_primitives::{Address, B256}; use eyre::eyre::ensure; -use world_chain_proof_protocol::{LineageProvider, ProofLane, encode_compact_proof}; +use world_chain_proof_protocol::{ + ConsensusProvider, LineageProvider, OptimismConsensusClient, ProofLane, encode_compact_proof, +}; use world_chain_proposer::{Proposal, ProposerClient}; use crate::it::utils::devnet::{ GAME_CHALLENGER_WINS, GAME_DEFENDER_WINS, INVALIDATION_REASON_INVALID_PARENT, INVALIDATION_REASON_PROOF_TIMEOUT, advance_to_timestamp, funded_throwaway_provider, game_at, - l1_contract, l1_rpc_url, proof_system_client, resolve_if_still_in_progress, - try_build_ha_devnet, wait_for_challenge, wait_for_multi_proof_game, wait_for_proof_lane, - wait_for_status_or_resolve, + l1_contract, l1_rpc_url, l2_op_node_rpc_url, proof_system_client, resolve_if_still_in_progress, + try_build_ha_devnet, wait_for_challenge, wait_for_multi_proof_game, + wait_for_multi_proof_game_attempt, wait_for_proof_lane, wait_for_status_or_resolve, }; /// A proposal that never accumulates a valid proof cannot win merely by going unchallenged. @@ -27,17 +29,19 @@ use crate::it::utils::devnet::{ /// `ChallengerWins`/`PROOF_TIMEOUT` outcome, whether or not the real challenger races in first. #[ignore = "requires Docker, Foundry, and the full local OP Stack"] #[tokio::test(flavor = "multi_thread", worker_threads = 4)] -async fn unproven_proposal_times_out_to_challenger_wins() -> eyre::Result<()> { +async fn unproven_proposal_with_invalid_root_claim_times_out_to_challenger_wins() -> eyre::Result<()> +{ reth_tracing::init_test_tracing(); - let Some(devnet) = try_build_ha_devnet("proof-timeout E2E").await? else { + let Some(devnet) = try_build_ha_devnet("proof-timeout with invalid root claim E2E").await? + else { return Ok(()); }; let l1_rpc = l1_rpc_url(&devnet)?; let factory_address = l1_contract(devnet.dispute_game_factory(), "DisputeGameFactory")?; - let (_, provider) = funded_throwaway_provider(l1_rpc).await?; + let (_, provider) = funded_throwaway_provider(l1_rpc, factory_address).await?; let contracts = proof_system_client(provider.clone(), factory_address).await?; let anchor = contracts.lineage_anchor().await?; @@ -76,6 +80,172 @@ async fn unproven_proposal_times_out_to_challenger_wins() -> eyre::Result<()> { Ok(()) } +/// A game that contains a valid root_claim but without any proof will still end up as `CHALLENGER_WINS`. +/// +/// This test is the same as the previous one, but this game contains a valid root_claim, instead of the +/// invalid root_claim in the other test. +#[ignore = "requires Docker, Foundry, and the full local OP Stack"] +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn unproven_proposal_with_valid_root_claim_times_out_to_challenger_wins() -> eyre::Result<()> +{ + reth_tracing::init_test_tracing(); + + let Some(mut devnet) = try_build_ha_devnet("proof-timeout with valid root claim E2E").await? + else { + return Ok(()); + }; + + // A valid root sits on the selected lineage, so the live defender would TEE-prove it and + // defeat the "nobody proved" premise. Stop it (and its workers) before submitting. + devnet.stop_defender(); + + let l2_op_node_rpc = l2_op_node_rpc_url(&devnet)?; + let output_root_provider = OptimismConsensusClient::new(l2_op_node_rpc); + let l1_rpc = l1_rpc_url(&devnet)?; + let factory_address = l1_contract(devnet.dispute_game_factory(), "DisputeGameFactory")?; + + let (_, provider) = funded_throwaway_provider(l1_rpc, factory_address).await?; + let contracts = proof_system_client(provider.clone(), factory_address).await?; + + let anchor = contracts.lineage_anchor().await?; + let registered = contracts.registered_lineage_config(); + let l2_block_number = anchor + .l2_block_number + .saturating_add(registered.block_interval); + let root_claim = output_root_provider + .output_root_at_block(l2_block_number) + .await?; + let proposal = Proposal { + parent_ref: anchor.address, + root_claim, + l2_block_number, + attempt: 0, + }; + let submission = contracts.submit_proposal(&proposal).await?; + let game = game_at(submission.game_address, provider.clone()); + + // `proofDeadline()` is always the later deadline (`proofPeriod > challengePeriod`), so + // `gameOver()` holds whether or not the real challenger challenged this first. + let proof_deadline = game.proofDeadline().call().await?; + advance_to_timestamp(&provider, proof_deadline.saturating_add(1)).await?; + + resolve_if_still_in_progress(&game).await?; + + ensure!( + game.proofBitmap().call().await? == 0, + "no proof lane should ever land on a proposal nobody proved" + ); + ensure!( + game.status().call().await? == GAME_CHALLENGER_WINS, + "unproven proposal must resolve ChallengerWins on deadline, whether or not it was formally challenged" + ); + ensure!( + game.invalidationReason().call().await? == INVALIDATION_REASON_PROOF_TIMEOUT, + "unproven proposal must invalidate with PROOF_TIMEOUT" + ); + + Ok(()) +} + +/// A valid root that times out unproven is retried by the live proposer once the defender returns. +/// +/// Stops the defender so the honest claim cannot be TEE-proved, lets attempt 0 resolve +/// `ChallengerWins`/`PROOF_TIMEOUT`, then restarts the defender and asserts the proposer +/// resubmits the same transition at `attempt + 1` and that retry resolves `DefenderWins`. +#[ignore = "requires Docker, Foundry, and the full local OP Stack"] +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn timed_out_valid_root_is_retried_and_defended_after_defender_restart() -> eyre::Result<()> { + reth_tracing::init_test_tracing(); + + let Some(mut devnet) = + try_build_ha_devnet("proof-timeout retry after defender restart E2E").await? + else { + return Ok(()); + }; + + // A valid root sits on the selected lineage, so the live defender would TEE-prove it and + // defeat the "nobody proved" premise. Stop it (and its workers) before submitting. + devnet.stop_defender(); + + let l2_op_node_rpc = l2_op_node_rpc_url(&devnet)?; + let output_root_provider = OptimismConsensusClient::new(l2_op_node_rpc); + let l1_rpc = l1_rpc_url(&devnet)?; + let factory_address = l1_contract(devnet.dispute_game_factory(), "DisputeGameFactory")?; + + let (_, provider) = funded_throwaway_provider(l1_rpc, factory_address).await?; + let contracts = proof_system_client(provider.clone(), factory_address).await?; + + let anchor = contracts.lineage_anchor().await?; + let registered = contracts.registered_lineage_config(); + let l2_block_number = anchor + .l2_block_number + .saturating_add(registered.block_interval); + let root_claim = output_root_provider + .output_root_at_block(l2_block_number) + .await?; + let proposal = Proposal { + parent_ref: anchor.address, + root_claim, + l2_block_number, + attempt: 0, + }; + let submission = contracts.submit_proposal(&proposal).await?; + let game = game_at(submission.game_address, provider.clone()); + + let proof_deadline = game.proofDeadline().call().await?; + advance_to_timestamp(&provider, proof_deadline.saturating_add(1)).await?; + + resolve_if_still_in_progress(&game).await?; + + ensure!( + game.proofBitmap().call().await? == 0, + "no proof lane should ever land on a proposal nobody proved" + ); + ensure!( + game.status().call().await? == GAME_CHALLENGER_WINS, + "unproven proposal must resolve ChallengerWins on deadline" + ); + ensure!( + game.invalidationReason().call().await? == INVALIDATION_REASON_PROOF_TIMEOUT, + "unproven proposal must invalidate with PROOF_TIMEOUT" + ); + + // Bring the defender back; the live proposer should resubmit the same transition at attempt 1. + devnet.start_defender().await?; + + let retry_address = wait_for_multi_proof_game_attempt( + provider.clone(), + factory_address, + proposal.parent_ref, + proposal.l2_block_number, + 1, // attempt should be exactly 1 as 0 has been tried before and failed + ) + .await?; + let retry_game = game_at(retry_address, provider.clone()); + + ensure!( + retry_game.rootClaim().call().await? == root_claim, + "retry must reuse the timed-out game's root claim" + ); + ensure!( + retry_address != submission.game_address, + "retry must create a distinct factory game" + ); + + // Unchallenged, a single TEE lane is enough once the challenge window closes. + wait_for_proof_lane(&retry_game).await?; + let challenge_deadline = retry_game.challengeDeadline().call().await?; + advance_to_timestamp(&provider, challenge_deadline.saturating_add(1)).await?; + wait_for_status_or_resolve(&retry_game, GAME_DEFENDER_WINS).await?; + + ensure!( + retry_game.invalidationReason().call().await? == 0, + "a defended retry must have no invalidation reason" + ); + + Ok(()) +} + /// A game built on an already-invalidated parent must resolve `ChallengerWins` via /// `INVALID_PARENT`, regardless of its own proof or challenge state. /// @@ -88,17 +258,18 @@ async fn unproven_proposal_times_out_to_challenger_wins() -> eyre::Result<()> { /// challenger contesting the parent. #[ignore = "requires Docker, Foundry, and the full local OP Stack"] #[tokio::test(flavor = "multi_thread", worker_threads = 4)] -async fn invalid_parent_cascades_to_challenger_wins() -> eyre::Result<()> { +async fn invalid_game_with_invalid_parent_cascades_to_challenger_wins() -> eyre::Result<()> { reth_tracing::init_test_tracing(); - let Some(devnet) = try_build_ha_devnet("invalid-parent cascade E2E").await? else { + let Some(devnet) = try_build_ha_devnet("invalid game with invalid-parent cascade E2E").await? + else { return Ok(()); }; let l1_rpc = l1_rpc_url(&devnet)?; let factory_address = l1_contract(devnet.dispute_game_factory(), "DisputeGameFactory")?; - let (_, provider) = funded_throwaway_provider(l1_rpc).await?; + let (_, provider) = funded_throwaway_provider(l1_rpc, factory_address).await?; let contracts = proof_system_client(provider.clone(), factory_address).await?; let anchor = contracts.lineage_anchor().await?; @@ -154,6 +325,85 @@ async fn invalid_parent_cascades_to_challenger_wins() -> eyre::Result<()> { Ok(()) } +/// A game that contains a valid root_claim but with an invalid parent will end up to `CHALLENGER_WINS`. +/// +/// This test is the same as the previous one, but this child game contains a valid root_claim, +/// instead of the invalid root_claim in the other test. +#[ignore = "requires Docker, Foundry, and the full local OP Stack"] +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn valid_game_with_invalid_parent_cascades_to_challenger_wins() -> eyre::Result<()> { + reth_tracing::init_test_tracing(); + + let Some(devnet) = try_build_ha_devnet("valid game with invalid-parent cascade E2E").await? + else { + return Ok(()); + }; + + let l2_op_node_rpc = l2_op_node_rpc_url(&devnet)?; + let output_root_provider = OptimismConsensusClient::new(l2_op_node_rpc); + let l1_rpc = l1_rpc_url(&devnet)?; + let factory_address = l1_contract(devnet.dispute_game_factory(), "DisputeGameFactory")?; + + let (_, provider) = funded_throwaway_provider(l1_rpc, factory_address).await?; + let contracts = proof_system_client(provider.clone(), factory_address).await?; + + let anchor = contracts.lineage_anchor().await?; + let registered = contracts.registered_lineage_config(); + + // Parent: a bad root that the real challenger will contest. + let parent_l2_block_number = anchor + .l2_block_number + .saturating_add(registered.block_interval); + let parent_proposal = Proposal { + parent_ref: anchor.address, + root_claim: B256::repeat_byte(0xba), + l2_block_number: parent_l2_block_number, + attempt: 0, + }; + let parent_submission = contracts.submit_proposal(&parent_proposal).await?; + let parent_game = game_at(parent_submission.game_address, provider.clone()); + + // Child must be created *before* the parent resolves: `_isValidParent` + // (MultiProofGame.sol:421-424) rejects parents already known invalid. The cascade under test is + // enforced dynamically in `resolve()`, so this ordering is the realistic case. + let l2_block_number = parent_l2_block_number.saturating_add(registered.block_interval); + let root_claim = output_root_provider + .output_root_at_block(l2_block_number) + .await?; + let child_proposal = Proposal { + parent_ref: parent_submission.game_address, + root_claim, + l2_block_number, + attempt: 0, + }; + let child_submission = contracts.submit_proposal(&child_proposal).await?; + let child_game = game_at(child_submission.game_address, provider.clone()); + + // Wait for the real World Chain challenger to contest the bad parent. + wait_for_challenge(&parent_game).await?; + + // Skip past the parent's proof deadline so its challenge can resolve. + let parent_proof_deadline = parent_game.proofDeadline().call().await?; + advance_to_timestamp(&provider, parent_proof_deadline.saturating_add(1)).await?; + + // Resolved by the real challenger's resolution manager, or by us as a fallback. + wait_for_status_or_resolve(&parent_game, GAME_CHALLENGER_WINS).await?; + + // Its l2 block is far beyond the finalized head, so the real challenger never picks it up. + resolve_if_still_in_progress(&child_game).await?; + + ensure!( + child_game.status().call().await? == GAME_CHALLENGER_WINS, + "child of an invalidated parent must resolve ChallengerWins regardless of its own root claim" + ); + ensure!( + child_game.invalidationReason().call().await? == INVALIDATION_REASON_INVALID_PARENT, + "child of an invalidated parent must invalidate with INVALID_PARENT, not PROOF_TIMEOUT" + ); + + Ok(()) +} + /// A genuinely honest claim must resolve `DefenderWins` even when maliciously challenged, once /// the proof threshold is reached. /// @@ -183,19 +433,13 @@ async fn valid_proposal_survives_adversarial_challenge() -> eyre::Result<()> { let factory_address = l1_contract(devnet.dispute_game_factory(), "DisputeGameFactory")?; // An adversary griefs the honest proposer's perfectly valid claim. - let (adversary_address, adversary_provider) = funded_throwaway_provider(l1_rpc).await?; + let (adversary_address, adversary_provider) = + funded_throwaway_provider(l1_rpc, factory_address).await?; let (_, honest_game_address, _) = wait_for_multi_proof_game(adversary_provider.clone(), factory_address, 0).await?; let game = game_at(honest_game_address, adversary_provider.clone()); - let challenger_bond = game.challengerBond().call().await?; - let receipt = game - .challenge() - .value(challenger_bond) - .send() - .await? - .get_receipt() - .await?; + let receipt = game.challenge().send().await?.get_receipt().await?; ensure!( receipt.status(), "adversarial challenge() transaction reverted" diff --git a/e2e-tests/src/it/devnet_withdrawal.rs b/e2e-tests/src/it/devnet_withdrawal.rs index ad65cb246..afad55ef2 100644 --- a/e2e-tests/src/it/devnet_withdrawal.rs +++ b/e2e-tests/src/it/devnet_withdrawal.rs @@ -1,81 +1,22 @@ -use alloy_consensus::BlockHeader; -use alloy_eips::{BlockId, BlockNumberOrTag}; -use alloy_primitives::{Address, B256, Bytes, U256, address, keccak256}; -use alloy_provider::Provider; +use alloy_primitives::U256; use alloy_signer_local::PrivateKeySigner; -use alloy_sol_types::{SolValue, sol}; use eyre::eyre::{OptionExt, ensure}; use world_chain_devnet::SUPERCHAIN_GUARDIAN_PRIVATE_KEY; use world_chain_proof_protocol::MULTI_PROOF_GAME_TYPE; -use crate::it::utils::devnet::{ - GAME_DEFENDER_WINS, advance_to_timestamp, anchor_at, game_at, l1_contract, l1_rpc_url, - latest_timestamp, signing_provider, try_build_ha_devnet, wait_for_anchor_at_or_beyond, - wait_for_bond_unlock, wait_for_bond_withdrawal, wait_for_game_finality, - wait_for_multi_proof_game, wait_for_proof_lane, wait_for_status, weth_at, +use crate::it::utils::{ + devnet::{ + GAME_DEFENDER_WINS, advance_to_timestamp, anchor_at, game_at, l1_contract, l1_rpc_url, + latest_timestamp, signing_provider, try_build_ha_devnet, vault_at, + wait_for_anchor_at_or_beyond, wait_for_game_finality, wait_for_game_settlement, + wait_for_multi_proof_game, wait_for_proof_lane, wait_for_status, + }, + withdrawals::{OptimismPortal, build_withdrawal_proof, initiate_withdrawal}, }; -const L2_TO_L1_MESSAGE_PASSER: Address = address!("4200000000000000000000000000000000000016"); - -sol! { - struct WithdrawalTransaction { - uint256 nonce; - address sender; - address target; - uint256 value; - uint256 gasLimit; - bytes data; - } - - struct OutputRootProof { - bytes32 version; - bytes32 stateRoot; - bytes32 messagePasserStorageRoot; - bytes32 latestBlockhash; - } - - #[sol(rpc)] - interface L2ToL1MessagePasser { - event MessagePassed( - uint256 indexed nonce, - address indexed sender, - address indexed target, - uint256 value, - uint256 gasLimit, - bytes data, - bytes32 withdrawalHash - ); - - function initiateWithdrawal(address target, uint256 gasLimit, bytes data) external payable; - } - - #[sol(rpc)] - interface OptimismPortal { - function anchorStateRegistry() external view returns (address); - function disputeGameFactory() external view returns (address); - function disputeGameFinalityDelaySeconds() external view returns (uint256); - function proofMaturityDelaySeconds() external view returns (uint256); - function version() external view returns (string); - function proveWithdrawalTransaction( - WithdrawalTransaction tx_, - uint256 disputeGameIndex, - OutputRootProof outputRootProof, - bytes[] withdrawalProof - ) external; - function finalizeWithdrawalTransaction(WithdrawalTransaction tx_) external; - function finalizedWithdrawals(bytes32 withdrawalHash) external view returns (bool); - } -} - -struct InitiatedWithdrawal { - transaction: WithdrawalTransaction, - hash: B256, - l2_block: u64, -} - #[ignore = "requires Docker, Foundry, and the full local OP Stack"] #[tokio::test(flavor = "multi_thread", worker_threads = 4)] -async fn op_native_wip_1006_portal_withdrawal_and_bond_claim() -> eyre::Result<()> { +async fn op_native_wip_1006_portal_withdrawal_and_bond_settlement() -> eyre::Result<()> { reth_tracing::init_test_tracing(); let Some(devnet) = try_build_ha_devnet("Portal withdrawal E2E").await? else { @@ -125,6 +66,10 @@ async fn op_native_wip_1006_portal_withdrawal_and_bond_claim() -> eyre::Result<( anchor.isGameProper(game_address).call().await?, "covering WIP-1006 game is not proper" ); + let proposer = game.gameCreator().call().await?; + let vault = vault_at(game.bondVault().call().await?, l1_provider.clone()); + let available_while_locked = vault.availableBalance(proposer).call().await?; + let proposer_bond = game.proposerBond().call().await?; wait_for_proof_lane(&game).await?; let (output_root_proof, withdrawal_proof) = @@ -195,91 +140,18 @@ async fn op_native_wip_1006_portal_withdrawal_and_bond_claim() -> eyre::Result<( ); wait_for_anchor_at_or_beyond(&anchor, game_l2_block).await?; - let proposer = game.gameCreator().call().await?; - let weth = weth_at(game.weth().call().await?, l1_provider.clone()); - let unlock_at = wait_for_bond_unlock(&weth, game_address, proposer).await?; - advance_to_timestamp(&l1_provider, unlock_at).await?; - wait_for_bond_withdrawal(&weth, game_address, proposer).await?; - - Ok(()) -} - -async fn initiate_withdrawal

( - provider: P, - withdrawal_sender: Address, -) -> eyre::Result -where - P: Provider, -{ - let receipt = L2ToL1MessagePasser::new(L2_TO_L1_MESSAGE_PASSER, provider) - .initiateWithdrawal(withdrawal_sender, U256::from(100_000), Bytes::new()) - .gas(250_000) - .send() - .await? - .get_receipt() - .await?; - ensure!(receipt.status(), "L2 withdrawal initiation reverted"); - - let l2_block = receipt - .block_number - .ok_or_eyre("withdrawal receipt missing L2 block number")?; - let message = receipt - .logs() - .iter() - .find_map(|log| { - log.log_decode_validate::() - .ok() - }) - .ok_or_eyre("withdrawal receipt missing MessagePassed event")?; - let message = message.data(); - - Ok(InitiatedWithdrawal { - transaction: WithdrawalTransaction { - nonce: message.nonce, - sender: message.sender, - target: message.target, - value: message.value, - gasLimit: message.gasLimit, - data: message.data.clone(), - }, - hash: message.withdrawalHash, - l2_block, - }) -} - -async fn build_withdrawal_proof

( - l2_provider: P, - game_l2_block: u64, - withdrawal_hash: B256, -) -> eyre::Result<(OutputRootProof, Vec)> -where - P: Provider, -{ - let block = l2_provider - .get_block_by_number(BlockNumberOrTag::Number(game_l2_block)) - .await? - .ok_or_eyre("WIP-1006 output block missing from L2")?; - let storage_key = keccak256((withdrawal_hash, U256::ZERO).abi_encode_params()); - let account_proof = l2_provider - .get_proof(L2_TO_L1_MESSAGE_PASSER, vec![storage_key]) - .block_id(BlockId::Number(BlockNumberOrTag::Number(game_l2_block))) - .await?; - let storage_proof = account_proof - .storage_proof - .first() - .ok_or_eyre("eth_getProof returned no withdrawal storage proof")?; + wait_for_game_settlement(&vault, game_address).await?; ensure!( - storage_proof.value == U256::from(1), - "withdrawal is absent from the message passer" + game.normalModeCredit(proposer).call().await? == proposer_bond, + "the unchallenged defender win did not return the complete proposer bond" + ); + let expected_available = available_while_locked + .checked_add(proposer_bond) + .ok_or_eyre("settled proposer balance overflow")?; + ensure!( + vault.availableBalance(proposer).call().await? >= expected_available, + "settlement did not restore the proposer bond to reusable vault balance" ); - Ok(( - OutputRootProof { - version: B256::ZERO, - stateRoot: block.header.state_root(), - messagePasserStorageRoot: account_proof.storage_hash, - latestBlockhash: block.header.hash, - }, - storage_proof.proof.clone(), - )) + Ok(()) } diff --git a/e2e-tests/src/it/mod.rs b/e2e-tests/src/it/mod.rs index 7f3649e0e..76714b8aa 100644 --- a/e2e-tests/src/it/mod.rs +++ b/e2e-tests/src/it/mod.rs @@ -1,6 +1,7 @@ #[cfg(test)] mod acceptance_tests; mod admin_tracing; +mod alphanet; mod devnet_challenge; mod devnet_proof_invariants; mod devnet_smoke; diff --git a/e2e-tests/src/it/testsuite.rs b/e2e-tests/src/it/testsuite.rs index 7848d689b..334bcf46b 100644 --- a/e2e-tests/src/it/testsuite.rs +++ b/e2e-tests/src/it/testsuite.rs @@ -749,8 +749,63 @@ async fn test_flashblocks() -> eyre::Result<()> { Ok(()) } +async fn assert_receipt_l1_costs( + clients: Vec, + expected: Vec<(B256, u128, u128)>, + canonical_block: u64, +) -> eyre::Result<()> { + use jsonrpsee::{core::client::ClientT, rpc_params}; + + for (node_idx, rpc) in clients.into_iter().enumerate() { + let block_number: alloy_primitives::U64 = + rpc.request("eth_blockNumber", rpc_params![]).await?; + assert_eq!(block_number.to::(), canonical_block); + + for (hash, l1_fee, l1_gas_used) in &expected { + let receipt = tokio::time::timeout(Duration::from_secs(5), async { + loop { + let receipt: Option = rpc + .request("eth_getTransactionReceipt", rpc_params![hash]) + .await?; + if let Some(receipt) = receipt { + break Ok::<_, eyre::Report>(receipt); + } + sleep(Duration::from_millis(20)).await; + } + }) + .await + .map_err(|_| eyre!("node {node_idx}: timed out waiting for receipt {hash} at canonical block {canonical_block}"))??; + assert_eq!(receipt.inner.block_number, Some(1)); + assert_eq!(receipt.l1_block_info.l1_fee, Some(*l1_fee)); + assert_eq!(receipt.l1_block_info.l1_gas_used, Some(*l1_gas_used)); + } + + // Batch conversion must not reuse one transaction's cached L1 cost for another. + let block_tag = if canonical_block == 0 { + "pending" + } else { + "latest" + }; + let receipts: Vec = rpc + .request("eth_getBlockReceipts", rpc_params![block_tag]) + .await?; + for (hash, l1_fee, l1_gas_used) in &expected { + let receipt = receipts + .iter() + .find(|receipt| receipt.inner.transaction_hash == *hash) + .ok_or_else(|| eyre!("missing block receipt for {hash}"))?; + assert_eq!(receipt.l1_block_info.l1_fee, Some(*l1_fee)); + assert_eq!(receipt.l1_block_info.l1_gas_used, Some(*l1_gas_used)); + } + } + Ok(()) +} + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn test_eth_api_receipt() -> eyre::Result<()> { + use alloy_eips::eip2718::Decodable2718; + use reth_optimism_evm::l1::{RethL1BlockInfo, extract_l1_info_from_tx}; + reth_tracing::init_test_tracing(); let (_, nodes, _tasks, mut env, _spammer) = WorldChainTestBuilder::builder() @@ -760,88 +815,87 @@ async fn test_eth_api_receipt() -> eyre::Result<()> { .setup::() .await?; - let ext_context = nodes[0].ext_context.clone(); let block_hash = nodes[0].node.block_hash(0); - + for node in &nodes { + node.node.update_forkchoice(block_hash, block_hash).await?; + } + let builder_vk = nodes[0] + .ext_context + .as_ref() + .unwrap() + .flashblocks_handle + .builder_sk() + .unwrap() + .verifying_key(); let authorization_generator = world_chain_test_utils::e2e_harness::setup::create_authorization_generator( - block_hash, - ext_context - .unwrap() - .flashblocks_handle - .builder_sk() - .unwrap() - .verifying_key(), + block_hash, builder_vk, ); + let timestamp = world_chain_test_utils::e2e_harness::setup::current_timestamp() + 2; + let chain_spec = nodes[0].node.inner.chain_spec().clone(); - let timestamp = world_chain_test_utils::e2e_harness::setup::current_timestamp(); - let (sender, mut block_rx) = tokio::sync::mpsc::channel(1); - let eip1559_params = world_chain_test_utils::e2e_harness::setup::encode_eip1559_params( - nodes[0].node.inner.chain_spec().as_ref(), - timestamp, - )?; + // Give the Ecotone fixture a nonzero base fee and scalar. + let deposit = OpTxEnvelope::decode_2718(&mut TX_SET_L1_BLOCK.as_ref())?; + let mut deposit = deposit.as_deposit().unwrap().inner().clone(); + let mut input = deposit.input.to_vec(); + input[4..8].copy_from_slice(&1_000_000u32.to_be_bytes()); + input[36..68].copy_from_slice(&U256::from(1_000_000_000u64).to_be_bytes::<32>()); + deposit.input = input.into(); + let deposit = OpTxEnvelope::Deposit(alloy_primitives::Sealed::new(deposit)); + + let mut expected = Vec::new(); + for (nonce, calldata_len, gas_limit) in [(0, 0, 21_000), (1, 50_000, 600_000)] { + let (raw, hash) = + create_priority_transaction(0, nonce, calldata_len, gas_limit, 100).await?; + // Each transaction gets fresh L1 information, independent of the receipt converter's cache. + let mut l1_info = extract_l1_info_from_tx(&deposit)?; + let fee = l1_info.l1_tx_data_fee(chain_spec.as_ref(), timestamp, &raw, false)?; + let gas = l1_info.l1_data_gas(chain_spec.as_ref(), timestamp, &raw)?; + expected.push((hash, fee.to::(), gas.to::())); + assert_eq!(nodes[0].node.rpc.inject_tx(raw).await?, hash); + } + assert!(expected[0].1 > 0); + assert!(expected[0].2 > 0); + assert_ne!(expected[0].1, expected[1].1); + assert_ne!(expected[0].2, expected[1].2); - // Compose a Mine Block action with an eth_getTransactionReceipt action - let attributes = world_chain_test_utils::e2e_harness::setup::build_payload_attributes( + let attributes = build_payload_attributes( timestamp, - eip1559_params, - Some(vec![ - world_chain_test_utils::e2e_harness::setup::TX_SET_L1_BLOCK.clone(), - ]), + encode_eip1559_params(chain_spec.as_ref(), timestamp)?, + Some(vec![deposit.encoded_2718().into()]), ); - - let cannon_flashblocks_stream = nodes[0] - .ext_context - .clone() - .unwrap() - .flashblocks_handle - .flashblock_stream(); - - let mine_block = world_chain_test_utils::e2e_harness::actions::AssertMineBlock::new( - 0, - None, - attributes, - authorization_generator, - std::time::Duration::from_millis(2000), - true, - sender, - ) - .await; - - let transaction_receipt = world_chain_test_utils::e2e_harness::actions::GetReceipts::new( - vec![0, 1, 2], - cannon_flashblocks_stream, - ) - .on_receipts(move |receipts| { - for receipts in receipts { - world_chain_test_utils::e2e_harness::actions::assert::all_some( - &receipts, - "transaction receipt", - )?; - } - - Ok(()) - }); - - let mut action = world_chain_test_utils::e2e_harness::actions::EthApiAction::new( - mine_block, - transaction_receipt, - ); - - let fut = async { action.execute(&mut env).await }; - - futures::future::try_select( - Box::pin(fut), - Box::pin(async { - block_rx - .recv() - .await - .ok_or(eyre!("failed to fetch envelope")) - }), - ) - .await - .map_err(|e| eyre!("{}", e.factor_first().0))?; - + let clients: Vec<_> = env + .node_clients + .iter() + .map(|client| client.rpc.clone()) + .collect(); + let pending_clients = vec![clients[0].clone()]; + let pending_expected = expected.clone(); + let mut driver = world_chain_test_utils::e2e_harness::actions::EngineDriver { + builder_idx: 0, + follower_idxs: vec![1, 2], + initial_parent_hash: Some(block_hash), + num_blocks: 1, + block_interval: Duration::from_secs(2), + flashblocks: true, + authorization_gen: move |_, attrs| authorization_generator(attrs), + attributes_gen: Box::new(move |_, _| Ok(attributes.clone())), + during_build: Some(Box::new(move |_| { + Box::pin(assert_receipt_l1_costs( + pending_clients.clone(), + pending_expected.clone(), + 0, + )) + })), + on_block: Some(Box::new(move |_, _| { + Box::pin(assert_receipt_l1_costs( + clients.clone(), + expected.clone(), + 1, + )) + })), + }; + tokio::time::timeout(Duration::from_secs(30), driver.execute(&mut env)).await??; Ok(()) } diff --git a/e2e-tests/src/it/utils/bindings.rs b/e2e-tests/src/it/utils/bindings.rs new file mode 100644 index 000000000..5e0ccd81c --- /dev/null +++ b/e2e-tests/src/it/utils/bindings.rs @@ -0,0 +1,19 @@ +use alloy_sol_types::sol; + +sol! { + #[sol(rpc)] + interface IFaultDisputeGame { + /// @notice The current status of the dispute game. + #[derive(Debug, PartialEq)] + enum GameStatus { + // The game is currently in progress, and has not been resolved. + IN_PROGRESS, + // The game has concluded, and the `rootClaim` was challenged successfully. + CHALLENGER_WINS, + // The game has concluded, and the `rootClaim` could not be contested. + DEFENDER_WINS + } + + function status() external view returns (GameStatus); + } +} diff --git a/e2e-tests/src/it/utils/devnet.rs b/e2e-tests/src/it/utils/devnet.rs index 7addcd229..e845c1330 100644 --- a/e2e-tests/src/it/utils/devnet.rs +++ b/e2e-tests/src/it/utils/devnet.rs @@ -5,6 +5,7 @@ use std::{ future::Future, + str::FromStr, time::{Duration, Instant}, }; @@ -14,6 +15,7 @@ use alloy_network::EthereumWallet; use alloy_primitives::{Address, U256}; use alloy_provider::{Provider, ProviderBuilder, WalletProvider, ext::AnvilApi}; use alloy_signer_local::PrivateKeySigner; +use alloy_sol_types::sol; use eyre::eyre::{OptionExt, bail, ensure, eyre}; use url::Url; use world_chain_devnet::{ @@ -21,29 +23,38 @@ use world_chain_devnet::{ is_docker_unavailable, }; use world_chain_proof_protocol::{ - DEFAULT_L1_TX_RECEIPT_TIMEOUT_SECONDS, IAnchorStateRegistry, IDelayedWETH, IDisputeGameFactory, - IMultiProofGame, MULTI_PROOF_GAME_TYPE, + DEFAULT_L1_TX_RECEIPT_TIMEOUT_SECONDS, IAnchorStateRegistry, IDisputeGameFactory, + IERC20StakingVault, IMultiProofGame, MULTI_PROOF_GAME_TYPE, read_registered_bond_vault, }; use world_chain_proposer::AlloyProofSystemClient; /// How long any single wait on devnet-driven on-chain state may take before the test fails. -pub(in crate::it) const GAME_WAIT_TIMEOUT: Duration = Duration::from_secs(300); -pub(in crate::it) const GAME_IN_PROGRESS: u8 = 0; -pub(in crate::it) const GAME_CHALLENGER_WINS: u8 = 1; -pub(in crate::it) const GAME_DEFENDER_WINS: u8 = 2; +pub const GAME_WAIT_TIMEOUT: Duration = Duration::from_secs(300); +pub const GAME_IN_PROGRESS: u8 = 0; +pub const GAME_CHALLENGER_WINS: u8 = 1; +pub const GAME_DEFENDER_WINS: u8 = 2; /// `LibProof.InvalidationReason` ordinals (`pkg/contracts/src/dispute/lib/LibProof.sol`). -pub(in crate::it) const INVALIDATION_REASON_PROOF_TIMEOUT: u8 = 1; -pub(in crate::it) const INVALIDATION_REASON_INVALID_PARENT: u8 = 2; +pub const INVALIDATION_REASON_PROOF_TIMEOUT: u8 = 1; +pub const INVALIDATION_REASON_INVALID_PARENT: u8 = 2; /// Funds a throwaway Anvil account well above any bond the factory could demand (100 ETH). const THROWAWAY_ACCOUNT_BALANCE_WEI: u128 = 100_000_000_000_000_000_000; +/// Mock bond tokens deposited for each throwaway proof-system participant (100 tokens). +const THROWAWAY_ACCOUNT_BOND_TOKEN_BALANCE: u128 = 100_000_000_000_000_000_000; const GAME_POLL_INTERVAL: Duration = Duration::from_secs(1); -/// Builds the HA-sequencer full stack every proof-system test runs against. -/// -/// `Ok(None)` means Docker is unavailable — the caller should skip, not fail. -pub(in crate::it) async fn try_build_ha_devnet( +sol! { + #[sol(rpc)] + interface IMockBondToken { + function mint(address recipient, uint256 amount) external; + function approve(address spender, uint256 amount) external returns (bool); + function allowance(address owner, address spender) external view returns (uint256); + } +} + +pub async fn try_build_ha_devnet_with_custom_block_time( skip_label: &str, + block_time: Duration, ) -> eyre::Result> { let ha_config = HaSequencerConfig::default() .with_sequencer_count(2) @@ -52,7 +63,7 @@ pub(in crate::it) async fn try_build_ha_devnet( match WorldDevnetBuilder::new() .preset(WorldDevnetPreset::HaSequencer) .ha_sequencer(ha_config) - .block_time(Duration::from_secs(1)) + .block_time(block_time) .build() .await { @@ -65,14 +76,27 @@ pub(in crate::it) async fn try_build_ha_devnet( } } -pub(in crate::it) fn l1_rpc_url(devnet: &WorldDevnet) -> eyre::Result<&str> { +/// Builds the HA-sequencer full stack every proof-system test runs against. +/// +/// `Ok(None)` means Docker is unavailable — the caller should skip, not fail. +pub async fn try_build_ha_devnet(skip_label: &str) -> eyre::Result> { + try_build_ha_devnet_with_custom_block_time(skip_label, Duration::from_secs(1)).await +} + +pub fn l1_rpc_url(devnet: &WorldDevnet) -> eyre::Result<&str> { devnet .l1_rpc_url() .ok_or_eyre("full-stack devnet missing L1 RPC") } +pub fn l2_op_node_rpc_url(devnet: &WorldDevnet) -> eyre::Result<&str> { + devnet + .l2_op_node_rpc_url() + .ok_or_eyre("full-stack devnet missing L2 op-node RPC") +} + /// Parses one of the devnet's optional L1 contract addresses, naming it if absent. -pub(in crate::it) fn l1_contract(address: Option<&str>, what: &str) -> eyre::Result

{ +pub fn l1_contract(address: Option<&str>, what: &str) -> eyre::Result
{ Ok(address .ok_or_else(|| eyre!("full-stack devnet missing {what}"))? .parse()?) @@ -82,7 +106,7 @@ pub(in crate::it) fn l1_contract(address: Option<&str>, what: &str) -> eyre::Res /// /// Not erased to `DynProvider`: [`AlloyProofSystemClient`]'s proposer traits need /// [`WalletProvider`], which erasure drops. -pub(in crate::it) fn signing_provider( +pub fn signing_provider( rpc: &str, signer: PrivateKeySigner, ) -> eyre::Result> { @@ -91,11 +115,28 @@ pub(in crate::it) fn signing_provider( .connect_http(Url::parse(rpc)?)) } -/// Funds a fresh random account via `anvil_setBalance` and returns it with a signing provider. +/// Funds the address originated from the provided private key with ETH and returns the related provider. +pub async fn fund_address( + l1_rpc: &str, + private_key: &str, +) -> eyre::Result> { + let signer = PrivateKeySigner::from_str(private_key)?; + let address = signer.address(); + ProviderBuilder::new() + .connect_http(Url::parse(l1_rpc)?) + .anvil_set_balance(address, U256::from(THROWAWAY_ACCOUNT_BALANCE_WEI)) + .await?; + + let provider = signing_provider(l1_rpc, signer)?; + Ok(provider) +} + +/// Funds a fresh random account with L1 gas and mock tokens deposited into the active bond vault. /// /// Cheating balance in leaves the shared devnet genesis untouched for every other test. -pub(in crate::it) async fn funded_throwaway_provider( +pub async fn funded_throwaway_provider( l1_rpc: &str, + factory_address: Address, ) -> eyre::Result<(Address, impl Provider + WalletProvider + Clone + use<>)> { let signer = PrivateKeySigner::random(); let address = signer.address(); @@ -104,10 +145,59 @@ pub(in crate::it) async fn funded_throwaway_provider( .anvil_set_balance(address, U256::from(THROWAWAY_ACCOUNT_BALANCE_WEI)) .await?; - Ok((address, signing_provider(l1_rpc, signer)?)) + let provider = signing_provider(l1_rpc, signer)?; + let factory = + IDisputeGameFactory::IDisputeGameFactoryInstance::new(factory_address, provider.clone()); + let vault_address = read_registered_bond_vault(&provider, &factory).await?; + let vault = + IERC20StakingVault::IERC20StakingVaultInstance::new(vault_address, provider.clone()); + let bond_token_address = vault.token().call().await?; + let mock_bond_token = IMockBondToken::new(bond_token_address, provider.clone()); + let amount = U256::from(THROWAWAY_ACCOUNT_BOND_TOKEN_BALANCE); + + ensure!( + mock_bond_token + .mint(address, amount) + .send() + .await? + .get_receipt() + .await? + .status(), + "minting throwaway mock bond tokens reverted" + ); + ensure!( + mock_bond_token + .approve(vault_address, amount) + .send() + .await? + .get_receipt() + .await? + .status(), + "approving throwaway mock bond tokens reverted" + ); + ensure!( + vault + .deposit(address, amount) + .send() + .await? + .get_receipt() + .await? + .status(), + "depositing throwaway mock bond tokens reverted" + ); + ensure!( + mock_bond_token + .allowance(address, vault_address) + .call() + .await? + .is_zero(), + "deposit left a bond-token allowance for the throwaway account" + ); + + Ok((address, provider)) } -pub(in crate::it) async fn proof_system_client

( +pub async fn proof_system_client

( provider: P, factory_address: Address, ) -> eyre::Result> @@ -123,17 +213,14 @@ where .await?) } -pub(in crate::it) fn game_at

( - address: Address, - provider: P, -) -> IMultiProofGame::IMultiProofGameInstance

+pub fn game_at

(address: Address, provider: P) -> IMultiProofGame::IMultiProofGameInstance

where P: Provider, { IMultiProofGame::IMultiProofGameInstance::new(address, provider) } -pub(in crate::it) fn anchor_at

( +pub fn anchor_at

( address: Address, provider: P, ) -> IAnchorStateRegistry::IAnchorStateRegistryInstance

@@ -143,21 +230,25 @@ where IAnchorStateRegistry::IAnchorStateRegistryInstance::new(address, provider) } -pub(in crate::it) fn weth_at

( +pub fn vault_at

( address: Address, provider: P, -) -> IDelayedWETH::IDelayedWETHInstance

+) -> IERC20StakingVault::IERC20StakingVaultInstance

where P: Provider, { - IDelayedWETH::IDelayedWETHInstance::new(address, provider) + IERC20StakingVault::IERC20StakingVaultInstance::new(address, provider) } -/// Polls `probe` until it yields a value, giving up after [`GAME_WAIT_TIMEOUT`]. +/// Polls `probe` until it yields a value, giving up after `timeout`. /// /// `Ok(None)` means keep waiting; an `Err` aborts immediately, which is how callers fail fast on -/// terminal states. `what` completes "timed out after 300s waiting for …". -async fn poll_until(what: &str, mut probe: F) -> eyre::Result +/// terminal states. +async fn poll_until_with_timeout( + what: &str, + mut probe: F, + timeout: Duration, +) -> eyre::Result where F: FnMut() -> Fut, Fut: Future>>, @@ -167,14 +258,22 @@ where if let Some(value) = probe().await? { return Ok(value); } - if started.elapsed() >= GAME_WAIT_TIMEOUT { - bail!("timed out after {GAME_WAIT_TIMEOUT:?} waiting for {what}"); + if started.elapsed() >= timeout { + bail!("timed out after {timeout:?} waiting for {what}"); } tokio::time::sleep(GAME_POLL_INTERVAL).await; } } -pub(in crate::it) async fn latest_timestamp

(provider: &P) -> eyre::Result +async fn poll_until(what: &str, probe: F) -> eyre::Result +where + F: FnMut() -> Fut, + Fut: Future>>, +{ + poll_until_with_timeout(what, probe, GAME_WAIT_TIMEOUT).await +} + +pub async fn latest_timestamp

(provider: &P) -> eyre::Result where P: Provider, { @@ -187,7 +286,7 @@ where } /// Warps Anvil's clock forward to `target` and mines a block so it is observable on-chain. -pub(in crate::it) async fn advance_to_timestamp

(provider: &P, target: u64) -> eyre::Result<()> +pub async fn advance_to_timestamp

(provider: &P, target: u64) -> eyre::Result<()> where P: Provider, { @@ -199,12 +298,11 @@ where Ok(()) } -/// Waits for the newest WIP-1006 game at or beyond `min_l2_block`, returning its factory index, -/// address, and L2 sequence number. Pass `0` for any game at all. -pub(in crate::it) async fn wait_for_multi_proof_game

( +pub async fn wait_for_multi_proof_game_with_timeout

( provider: P, factory_address: Address, min_l2_block: u64, + timeout: Duration, ) -> eyre::Result<(u64, Address, u64)> where P: Provider + Clone, @@ -227,7 +325,7 @@ where } } - if started.elapsed() >= GAME_WAIT_TIMEOUT { + if started.elapsed() >= timeout { bail!( "timed out waiting for a respected WIP-1006 game at or beyond L2 block {min_l2_block}" ); @@ -236,30 +334,103 @@ where } } +/// Waits for the newest WIP-1006 game at or beyond `min_l2_block`, returning its factory index, +/// address, and L2 sequence number. Pass `0` for any game at all. +pub async fn wait_for_multi_proof_game

( + provider: P, + factory_address: Address, + min_l2_block: u64, +) -> eyre::Result<(u64, Address, u64)> +where + P: Provider + Clone, +{ + wait_for_multi_proof_game_with_timeout( + provider, + factory_address, + min_l2_block, + GAME_WAIT_TIMEOUT, + ) + .await +} + +/// Waits for a WIP-1006 game matching `parent_ref`, `l2_block`, and `attempt`. +pub async fn wait_for_multi_proof_game_attempt

( + provider: P, + factory_address: Address, + parent_ref: Address, + l2_block: u64, + attempt: u64, +) -> eyre::Result

+where + P: Provider + Clone, +{ + let factory = + IDisputeGameFactory::IDisputeGameFactoryInstance::new(factory_address, provider.clone()); + let started = Instant::now(); + + loop { + let game_count: u64 = factory.gameCount().call().await?.try_into()?; + for index in (0..game_count).rev() { + let entry = factory.gameAtIndex(U256::from(index)).call().await?; + if entry.gameType != MULTI_PROOF_GAME_TYPE { + continue; + } + let game = game_at(entry.proxy, provider.clone()); + let game_l2_block: u64 = game.l2SequenceNumber().call().await?.try_into()?; + let game_attempt: u64 = game.attempt().call().await?.try_into()?; + let game_parent = game.parentRef().call().await?; + if game_l2_block == l2_block && game_attempt == attempt && game_parent == parent_ref { + return Ok(entry.proxy); + } + } + + if started.elapsed() >= GAME_WAIT_TIMEOUT { + bail!( + "timed out waiting for WIP-1006 game parent={parent_ref} l2={l2_block} attempt={attempt}" + ); + } + tokio::time::sleep(Duration::from_secs(2)).await; + } +} + /// Waits for `game` to be challenged, returning the challenger's address. -pub(in crate::it) async fn wait_for_challenge

( +pub async fn wait_for_challenge_with_timeout

( game: &IMultiProofGame::IMultiProofGameInstance

, + timeout: Duration, ) -> eyre::Result

where P: Provider, { let address = *game.address(); - poll_until(&format!("game {address} to be challenged"), || async { - let challenger = game.challenger().call().await?; - if challenger != Address::ZERO { - return Ok(Some(challenger)); - } - ensure!( - game.status().call().await? == GAME_IN_PROGRESS, - "game {address} resolved before it was ever challenged" - ); - Ok(None) - }) + poll_until_with_timeout( + &format!("game {address} to be challenged"), + || async { + let challenger = game.challenger().call().await?; + if challenger != Address::ZERO { + return Ok(Some(challenger)); + } + ensure!( + game.status().call().await? == GAME_IN_PROGRESS, + "game {address} resolved before it was ever challenged" + ); + Ok(None) + }, + timeout, + ) .await } +pub async fn wait_for_challenge

( + game: &IMultiProofGame::IMultiProofGameInstance

, +) -> eyre::Result

+where + P: Provider, +{ + wait_for_challenge_with_timeout(game, GAME_WAIT_TIMEOUT).await +} + /// Waits for at least one proof lane to land on `game`. -pub(in crate::it) async fn wait_for_proof_lane

( +pub async fn wait_for_proof_lane

( game: &IMultiProofGame::IMultiProofGameInstance

, ) -> eyre::Result<()> where @@ -280,7 +451,7 @@ where } /// Waits for `game` to resolve to `expected`, failing fast if it resolves to anything else. -pub(in crate::it) async fn wait_for_status

( +pub async fn wait_for_status

( game: &IMultiProofGame::IMultiProofGameInstance

, expected: u8, ) -> eyre::Result<()> @@ -309,7 +480,7 @@ where /// /// Needed where no service is watching the game; it would sit `InProgress` forever otherwise. The /// final status must still be `expected`. -pub(in crate::it) async fn wait_for_status_or_resolve

( +pub async fn wait_for_status_or_resolve

( game: &IMultiProofGame::IMultiProofGameInstance

, expected: u8, ) -> eyre::Result<()> @@ -338,7 +509,7 @@ where } /// Calls `resolve()` unless another actor already did; only the final outcome matters. -pub(in crate::it) async fn resolve_if_still_in_progress

( +pub async fn resolve_if_still_in_progress

( game: &IMultiProofGame::IMultiProofGameInstance

, ) -> eyre::Result<()> where @@ -352,7 +523,7 @@ where } /// Waits for `game_address` to clear the `AnchorStateRegistry`'s finality airgap. -pub(in crate::it) async fn wait_for_game_finality

( +pub async fn wait_for_game_finality

( anchor: &IAnchorStateRegistry::IAnchorStateRegistryInstance

, game_address: Address, ) -> eyre::Result<()> @@ -373,7 +544,7 @@ where } /// Waits for the `AnchorStateRegistry` anchor to advance to at least `game_l2_block`. -pub(in crate::it) async fn wait_for_anchor_at_or_beyond

( +pub async fn wait_for_anchor_at_or_beyond

( anchor: &IAnchorStateRegistry::IAnchorStateRegistryInstance

, game_l2_block: u64, ) -> eyre::Result<()> @@ -390,48 +561,20 @@ where .await } -/// Waits for `proposer`'s bond on `game_address` to be credited in `DelayedWETH`, returning the -/// timestamp at which the withdrawal delay expires. -pub(in crate::it) async fn wait_for_bond_unlock

( - weth: &IDelayedWETH::IDelayedWETHInstance

, - game_address: Address, - proposer: Address, -) -> eyre::Result -where - P: Provider, -{ - let delay = weth.delay().call().await?; - poll_until("proposer bond credit to unlock", || async { - let pending = weth.withdrawals(game_address, proposer).call().await?; - if pending.amount.is_zero() { - return Ok(None); - } - let unlock_at: u64 = pending - .timestamp - .checked_add(delay) - .ok_or_eyre("DelayedWETH unlock timestamp overflow")? - .try_into()?; - Ok(Some(unlock_at)) - }) - .await -} - -/// Waits for `proposer`'s bond on `game_address` to be fully withdrawn from `DelayedWETH`. -pub(in crate::it) async fn wait_for_bond_withdrawal

( - weth: &IDelayedWETH::IDelayedWETHInstance

, +/// Waits for the complete bond pot of `game_address` to be settled into reusable vault balances. +pub async fn wait_for_game_settlement

( + vault: &IERC20StakingVault::IERC20StakingVaultInstance

, game_address: Address, - proposer: Address, ) -> eyre::Result<()> where P: Provider, { - poll_until("proposer bond withdrawal", || async { - Ok(weth - .withdrawals(game_address, proposer) + poll_until("game bond settlement", || async { + Ok(vault + .gameBonds(game_address) .call() .await? - .amount - .is_zero() + .settled .then_some(())) }) .await diff --git a/e2e-tests/src/it/utils/mod.rs b/e2e-tests/src/it/utils/mod.rs index b10e56c89..4e32b49e6 100644 --- a/e2e-tests/src/it/utils/mod.rs +++ b/e2e-tests/src/it/utils/mod.rs @@ -1 +1,3 @@ +pub mod bindings; pub mod devnet; +pub mod withdrawals; diff --git a/e2e-tests/src/it/utils/withdrawals.rs b/e2e-tests/src/it/utils/withdrawals.rs new file mode 100644 index 000000000..06ada44b2 --- /dev/null +++ b/e2e-tests/src/it/utils/withdrawals.rs @@ -0,0 +1,164 @@ +use alloy_consensus::BlockHeader; +use alloy_eips::{BlockId, BlockNumberOrTag}; +use alloy_primitives::{Address, B256, Bytes, U256, address, keccak256}; +use alloy_provider::Provider; +use alloy_sol_types::{SolValue, sol}; +use eyre::eyre::{OptionExt, ensure}; +use serde::{Deserialize, Serialize}; + +const L2_TO_L1_MESSAGE_PASSER: Address = address!("4200000000000000000000000000000000000016"); + +sol! { + #[derive(Debug, Serialize, Deserialize)] + struct WithdrawalTransaction { + uint256 nonce; + address sender; + address target; + uint256 value; + uint256 gasLimit; + bytes data; + } + + struct OutputRootProof { + bytes32 version; + bytes32 stateRoot; + bytes32 messagePasserStorageRoot; + bytes32 latestBlockhash; + } + + #[sol(rpc)] + interface L2ToL1MessagePasser { + event MessagePassed( + uint256 indexed nonce, + address indexed sender, + address indexed target, + uint256 value, + uint256 gasLimit, + bytes data, + bytes32 withdrawalHash + ); + + function initiateWithdrawal(address target, uint256 gasLimit, bytes data) external payable; + } + + #[sol(rpc)] + interface OptimismPortal { + function anchorStateRegistry() external view returns (address); + function disputeGameFactory() external view returns (address); + function disputeGameFinalityDelaySeconds() external view returns (uint256); + function proofMaturityDelaySeconds() external view returns (uint256); + function version() external view returns (string); + function proveWithdrawalTransaction( + WithdrawalTransaction tx_, + uint256 disputeGameIndex, + OutputRootProof outputRootProof, + bytes[] withdrawalProof + ) external; + function finalizeWithdrawalTransaction(WithdrawalTransaction tx_) external; + function finalizedWithdrawals(bytes32 withdrawalHash) external view returns (bool); + } + + interface IDisputeGame {} + + #[sol(rpc)] + interface AnchorStateRegistry { + function isGameClaimValid(IDisputeGame _game) public view returns (bool); + } +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct InitiatedWithdrawal { + pub transaction: WithdrawalTransaction, + pub hash: B256, + pub l2_block: u64, +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct ProveWithdrawal { + pub transaction: WithdrawalTransaction, + pub hash: B256, + pub game_index: u64, + pub game_l2_block: u64, + pub game_addr: Address, + pub proven_at: u64, +} + +pub async fn initiate_withdrawal

( + provider: P, + target_addr: Address, +) -> eyre::Result +where + P: Provider, +{ + let receipt = L2ToL1MessagePasser::new(L2_TO_L1_MESSAGE_PASSER, provider) + .initiateWithdrawal(target_addr, U256::from(100_000), Bytes::new()) + .gas(250_000) + .send() + .await? + .get_receipt() + .await?; + ensure!(receipt.status(), "L2 withdrawal initiation reverted"); + + let l2_block = receipt + .block_number + .ok_or_eyre("withdrawal receipt missing L2 block number")?; + let message = receipt + .logs() + .iter() + .find_map(|log| { + log.log_decode_validate::() + .ok() + }) + .ok_or_eyre("withdrawal receipt missing MessagePassed event")?; + let message = message.data(); + + Ok(InitiatedWithdrawal { + transaction: WithdrawalTransaction { + nonce: message.nonce, + sender: message.sender, + target: message.target, + value: message.value, + gasLimit: message.gasLimit, + data: message.data.clone(), + }, + hash: message.withdrawalHash, + l2_block, + }) +} + +pub async fn build_withdrawal_proof

( + l2_provider: P, + game_l2_block: u64, + withdrawal_hash: B256, +) -> eyre::Result<(OutputRootProof, Vec)> +where + P: Provider, +{ + let block = l2_provider + .get_block_by_number(BlockNumberOrTag::Number(game_l2_block)) + .await? + .ok_or_eyre("WIP-1006 output block missing from L2")?; + let storage_key = keccak256((withdrawal_hash, U256::ZERO).abi_encode_params()); + let account_proof = l2_provider + .get_proof(L2_TO_L1_MESSAGE_PASSER, vec![storage_key]) + .block_id(BlockId::Number(BlockNumberOrTag::Number(game_l2_block))) + .await?; + let storage_proof = account_proof + .storage_proof + .first() + .ok_or_eyre("eth_getProof returned no withdrawal storage proof")?; + ensure!( + storage_proof.value == U256::from(1), + "withdrawal is absent from the message passer" + ); + + Ok(( + OutputRootProof { + version: B256::ZERO, + stateRoot: block.header.state_root(), + messagePasserStorageRoot: account_proof.storage_hash, + latestBlockhash: block.header.hash, + }, + storage_proof.proof.clone(), + )) +} diff --git a/flake.lock b/flake.lock index 61df252b6..6c0e3dcff 100644 --- a/flake.lock +++ b/flake.lock @@ -73,17 +73,17 @@ "optimism": { "flake": false, "locked": { - "lastModified": 1787344944, - "narHash": "sha256-n8DDGbG/4AeUxU8a+8APRoMO05lyCq01BlSbDj1iCzE=", + "lastModified": 1790802614, + "narHash": "sha256-cih4EP8So8LmJPWhfx21CPF/bvjMnvWmfohe7gjOpo4=", "owner": "ethereum-optimism", "repo": "optimism", - "rev": "96ffbb2a94f19886fe7e27c45f3310e64ccd18b3", + "rev": "da6d3252491754837a778061db0cc47236ec13c6", "type": "github" }, "original": { "owner": "ethereum-optimism", "repo": "optimism", - "rev": "96ffbb2a94f19886fe7e27c45f3310e64ccd18b3", + "rev": "da6d3252491754837a778061db0cc47236ec13c6", "type": "github" } }, @@ -103,11 +103,11 @@ ] }, "locked": { - "lastModified": 1787540965, - "narHash": "sha256-48/4bbmK3W3Av3YPnrFb/tVQXPvBwU6kyM3Pb13VVD8=", + "lastModified": 1791620365, + "narHash": "sha256-CVZXIDNw7HEwyD8X6q9Ln370Sc0ZqRlTzDRwOZ1hJMY=", "owner": "oxalica", "repo": "rust-overlay", - "rev": "ab450d47a3f906d19de1b332915bfc6e5b29c853", + "rev": "e90fafa71b440fabcd52dd7fb017ab2da81c781a", "type": "github" }, "original": { diff --git a/flake.nix b/flake.nix index f7058499a..c13ec707a 100644 --- a/flake.nix +++ b/flake.nix @@ -9,7 +9,7 @@ inputs.nixpkgs.follows = "nixpkgs"; }; optimism = { - url = "github:ethereum-optimism/optimism/96ffbb2a94f19886fe7e27c45f3310e64ccd18b3"; + url = "github:ethereum-optimism/optimism/da6d3252491754837a778061db0cc47236ec13c6"; flake = false; }; nitro-util = { @@ -34,7 +34,24 @@ # hashes, so there is no hash to paste in here and none to go stale. rustToolchain = pkgs.rust-bin.fromRustupToolchainFile ./rust-toolchain.toml; - craneLib = (crane.mkLib pkgs).overrideToolchain rustToolchain; + craneLib = ((crane.mkLib pkgs).overrideToolchain rustToolchain).overrideScope ( + _final: prev: { + # Crane fetches Git dependencies with all submodules by default. Kona needs + # only Optimism's Rust sources, so reuse the locked, submodule-free flake + # input instead of fetching its unrelated Solidity dependencies. Override + # src before extraction; overrideVendorGitCheckout runs after that fetch. + downloadCargoPackageFromGit = args: + let + checkout = prev.downloadCargoPackageFromGit args; + in + if args.git == "https://github.com/ethereum-optimism/optimism" then + assert lib.assertMsg (args.rev == checkedOptimism.rev) + "Optimism vendor revision must match the locked flake input"; + checkout.overrideAttrs (_old: { src = checkedOptimism; }) + else + checkout; + } + ); # Only the measured sources, and within them only files cargo actually reads. Whole # directories would make the derivation hash move when a README or a Dockerfile next to diff --git a/justfiles/proof.just b/justfiles/proof.just index ed3634896..b492b3753 100644 --- a/justfiles/proof.just +++ b/justfiles/proof.just @@ -19,23 +19,29 @@ # Workflow phases owned by this repo: # Phase 0a proof-rollup-config-hash – Compute rollup config hash from an L2 RPC # Phase 1 proof-deploy-nitro – Deploy Nitro attestation contracts -# Phase 1b proof-deploy-mocks – Deploy proof-lane test doubles (devnet only) -# Phase 2 proof-deploy-system – Deploy proof system contracts +# Phase 1b proof-deploy-mock-bond-token – Deploy a mintable bond token (devnet only) +# Phase 1c proof-deploy-mocks – Deploy proof-lane test doubles (devnet only) +# Phase 2 proof-deploy-system – Deploy proof system implementation and vault +# Phase 2b proof-fund-mock-bonds – Fund persistent devnet bond accounts (devnet only) # Phase 3a proof-certmanager-prewarm – Pre-warm CertManager with CA certs # Phase 3b proof-approve-pcrs – Approve a PCR set on the verifier -# — proof-activate-system – Activate the registered WIP-1006 game +# — proof-activate-system – Validate, register, and activate WIP-1006 # # Required env vars (varies by target): # PRIVATE_KEY, OWNER, OWNER_KEY, L1_RPC_URL, # WORLD_CHAIN_L2_CHAIN_ID, ROLLUP_CONFIG_HASH, # AGGREGATION_VKEY, RANGE_VKEY_COMMITMENT, TEE_IMAGE_ID, -# CERT_MANAGER_ADDRESS, NITRO_ATTESTATION_VERIFIER +# CERT_MANAGER_ADDRESS, NITRO_ATTESTATION_VERIFIER, +# DISPUTE_GAME_FACTORY, ANCHOR_STATE_REGISTRY, SYSTEM_CONFIG, +# OP_CHAIN_PROXY_ADMIN, BOND_TOKEN, DGF_OWNER_KEY, +# GUARDIAN_KEY (when switching the respected game type) # # PCR0/PCR1/PCR2 are inputs here, not discovered: measure the running enclave # with `just proof-pcrs ` in the infrastructure repo. # # Simulation mode (no on-chain broadcast): # dry_run=true Simulate without broadcasting (all other steps still run) +# Broadcasts use RPC gas estimates because local EVM pricing can lag L1 upgrades. # ============================================================================== # Set dry_run=true on the command line to simulate without broadcasting. @@ -132,11 +138,13 @@ proof-deploy-nitro env="alphanet": #!/usr/bin/env bash set -euo pipefail : "${PRIVATE_KEY:?PRIVATE_KEY is required}" - : "${OWNER:?OWNER is required}" + if [ "${GOVERNANCE_MODE:-eoa}" != "safe" ]; then + : "${OWNER:?OWNER is required}" + fi : "${L1_RPC_URL:?L1_RPC_URL is required}" BROADCAST_FLAG="" if [ "{{dry_run}}" = "false" ]; then - BROADCAST_FLAG="--broadcast" + BROADCAST_FLAG="--broadcast --skip-simulation" fi # A dry run must not overwrite the record of the live Nitro stack: the simulated addresses # are never deployed, and this file is what proof-approve-pcrs and proof-register-key read. @@ -147,7 +155,28 @@ proof-deploy-nitro env="alphanet": fi echo "Deploying Nitro contracts (deployment → $NITRO_DEPLOYMENT_OUT)$([ -n "$BROADCAST_FLAG" ] || echo ' [DRY RUN]')…" cd pkg/contracts && mkdir -p deployments && forge script scripts/devnet/DeployNitro.s.sol:DeployNitro \ - --rpc-url "$L1_RPC_URL" --private-key "$PRIVATE_KEY" $BROADCAST_FLAG --slow + --rpc-url "$L1_RPC_URL" --rpc-timeout "${TIMEOUT:-50}" --private-key "$PRIVATE_KEY" $BROADCAST_FLAG --slow + +# Phase 1b (devnet only) – Deploy only the mintable token for a real-verifier devnet. +[doc("Phase 1b (devnet only) - Deploy a mintable ERC-20 proof bond token.")] +[group('proof')] +proof-deploy-mock-bond-token env="alphanet": + #!/usr/bin/env bash + set -euo pipefail + : "${PRIVATE_KEY:?PRIVATE_KEY is required}" + : "${L1_RPC_URL:?L1_RPC_URL is required}" + BROADCAST_FLAG="" + if [ "{{dry_run}}" = "false" ]; then + BROADCAST_FLAG="--broadcast --skip-simulation" + fi + if [ -n "$BROADCAST_FLAG" ]; then + export MOCK_BOND_TOKEN_DEPLOYMENT_OUT="deployments/{{env}}-mock-bond-token.json" + else + export MOCK_BOND_TOKEN_DEPLOYMENT_OUT="deployments/{{env}}-mock-bond-token.dryrun.json" + fi + echo "WARNING: deploying an unrestricted mintable mock bond token for '{{env}}'." >&2 + cd pkg/contracts && mkdir -p deployments && forge script scripts/devnet/DeployMockBondToken.s.sol:DeployMockBondToken \ + --rpc-url "$L1_RPC_URL" --rpc-timeout "${TIMEOUT:-50}" --private-key "$PRIVATE_KEY" $BROADCAST_FLAG --slow # Writes deployments/-proof-mocks.json for proof-deploy-system to consume. # MockRootIdVerifier accepts every proof: never run this against a chain whose @@ -162,7 +191,7 @@ proof-deploy-mocks env="alphanet": : "${L1_RPC_URL:?L1_RPC_URL is required}" BROADCAST_FLAG="" if [ "{{dry_run}}" = "false" ]; then - BROADCAST_FLAG="--broadcast" + BROADCAST_FLAG="--broadcast --skip-simulation" fi # Same reasoning as proof-deploy-system: a dry run must not clobber a real record. if [ -n "$BROADCAST_FLAG" ]; then @@ -170,18 +199,19 @@ proof-deploy-mocks env="alphanet": else export PROOF_MOCKS_DEPLOYMENT_OUT="deployments/{{env}}-proof-mocks.dryrun.json" fi - echo "WARNING: deploying MOCK proof verifiers (accept any proof) for '{{env}}'." >&2 + echo "WARNING: deploying MOCK proof-system dependencies (accept-any verifiers and a mintable bond token) for '{{env}}'." >&2 echo "Deploying proof mocks (deployment → $PROOF_MOCKS_DEPLOYMENT_OUT)$([ -n "$BROADCAST_FLAG" ] || echo ' [DRY RUN]')…" cd pkg/contracts && mkdir -p deployments && forge script scripts/devnet/DeployProofMocks.s.sol:DeployProofMocks \ - --rpc-url "$L1_RPC_URL" --private-key "$PRIVATE_KEY" $BROADCAST_FLAG --slow + --rpc-url "$L1_RPC_URL" --rpc-timeout "${TIMEOUT:-50}" --private-key "$PRIVATE_KEY" $BROADCAST_FLAG --slow -# The three proof-lane verifiers and the staking registry are required inputs — this +# The three proof-lane verifiers are required inputs — this # script never deploys them, and rejects addresses that hold no code or that repeat # across lanes. Reuse the SP1 verifier when only the game-pinned vkeys change; rotate # its address only if the verifier gateway or proof interface changes. For a devnet, # run `proof-deploy-mocks` first and read the four addresses out of -# deployments/-proof-mocks.json. -# Phase 2 – Deploy the proof system contracts and register game type 1006. +# deployments/-proof-mocks.json. An existing deployment record supplies the singleton +# ERC-20 vault automatically during rotations unless ERC20_STAKING_VAULT is set explicitly. +# Phase 2 – Deploy the proof system implementation and vault. [group('proof')] proof-deploy-system env="alphanet": #!/usr/bin/env bash @@ -197,47 +227,85 @@ proof-deploy-system env="alphanet": : "${ANCHOR_STATE_REGISTRY:?ANCHOR_STATE_REGISTRY is required (op-deployer AnchorStateRegistryProxy)}" : "${SYSTEM_CONFIG:?SYSTEM_CONFIG is required (op-deployer SystemConfigProxy)}" : "${OP_CHAIN_PROXY_ADMIN:?OP_CHAIN_PROXY_ADMIN is required (op-deployer ProxyAdmin)}" - : "${OP_CHAIN_PROXY_ADMIN_OWNER_PRIVATE_KEY:?OP_CHAIN_PROXY_ADMIN_OWNER_PRIVATE_KEY is required}" - : "${DGF_OWNER_KEY:?DGF_OWNER_KEY is required}" - : "${PROTOCOL_FEE_RECIPIENT:?PROTOCOL_FEE_RECIPIENT is required (challenge-fee proceeds)}" + : "${BOND_TOKEN:?BOND_TOKEN is required}" + : "${PROTOCOL_FEE_RECIPIENT:?PROTOCOL_FEE_RECIPIENT is required (proof-timeout forfeitures)}" : "${VALIDITY_PROOF_VERIFIER:?VALIDITY_PROOF_VERIFIER is required (e.g. SP1ValidityVerifier; devnet: proof-deploy-mocks)}" : "${TEE_VERIFIER:?TEE_VERIFIER is required (e.g. NitroProofVerifier from proof-deploy-nitro)}" : "${SECURITY_COUNCIL_VERIFIER:?SECURITY_COUNCIL_VERIFIER is required (council attestation verifier)}" export CHALLENGE_PERIOD="${CHALLENGE_PERIOD:-86400}" export PROOF_PERIOD="${PROOF_PERIOD:-604800}" export PROPOSER_BOND="${PROPOSER_BOND:-10000000000000000}" - export CHALLENGER_BOND="${CHALLENGER_BOND:-1000000000000000}" - export CHALLENGE_FEE="${CHALLENGE_FEE:-100000000000000}" + export CHALLENGER_BOND="${CHALLENGER_BOND:-10000000000000000}" export PROOF_THRESHOLD="${PROOF_THRESHOLD:-2}" - export DELAYED_WETH_DELAY="${DELAYED_WETH_DELAY:-300}" + export ERC20_WITHDRAWAL_DELAY="${ERC20_WITHDRAWAL_DELAY:-300}" + DEPLOYMENTS_FILE="pkg/contracts/deployments/{{env}}-proof-system.json" + if [ -z "${ERC20_STAKING_VAULT:-}" ] && [ -f "$DEPLOYMENTS_FILE" ]; then + ERC20_STAKING_VAULT=$(jq -r '.erc20StakingVault // empty' "$DEPLOYMENTS_FILE") + export ERC20_STAKING_VAULT + fi + if [ "${GOVERNANCE_MODE:-eoa}" != "safe" ] && { [ -z "${ERC20_STAKING_VAULT:-}" ] || [ "$ERC20_STAKING_VAULT" = "0x0000000000000000000000000000000000000000" ]; }; then + : "${OP_CHAIN_PROXY_ADMIN_OWNER_PRIVATE_KEY:?OP_CHAIN_PROXY_ADMIN_OWNER_PRIVATE_KEY is required for the first vault deployment}" + fi BROADCAST_FLAG="" if [ "{{dry_run}}" = "false" ]; then - BROADCAST_FLAG="--broadcast" + BROADCAST_FLAG="--broadcast --skip-simulation" fi echo "Proof-system parameters:" >&2 echo " challenge period: $CHALLENGE_PERIOD seconds" >&2 echo " proof period: $PROOF_PERIOD seconds" >&2 - echo " proposer bond: $PROPOSER_BOND wei" >&2 - echo " challenger bond: $CHALLENGER_BOND wei" >&2 - echo " challenge fee: $CHALLENGE_FEE wei" >&2 + echo " proposer bond: $PROPOSER_BOND bond-token base units" >&2 + echo " challenger bond: $CHALLENGER_BOND bond-token base units" >&2 + echo " ERC-20 vault: ${ERC20_STAKING_VAULT:-new singleton}" >&2 echo " aggregation vkey: $AGGREGATION_VKEY" >&2 echo " range vkey commitment: $RANGE_VKEY_COMMITMENT" >&2 echo " TEE image ID: $TEE_IMAGE_ID" >&2 # A dry run must never overwrite the record of a live deployment: the simulated game and - # WETH addresses are never deployed, so writing them to the real path silently replaces a + # contract addresses are never deployed, so writing them to the real path silently replaces a # true record with fictional addresses. if [ -n "$BROADCAST_FLAG" ]; then export PROOF_SYSTEM_DEPLOYMENT_OUT="deployments/{{env}}-proof-system.json" else export PROOF_SYSTEM_DEPLOYMENT_OUT="deployments/{{env}}-proof-system.dryrun.json" fi + if [ "${GOVERNANCE_MODE:-eoa}" = "safe" ]; then + export SAFE_TX_OUT="${SAFE_TX_OUT:-${PROOF_SYSTEM_DEPLOYMENT_OUT%.json}.safe.json}" + fi echo "Deploying proof system contracts (deployment → $PROOF_SYSTEM_DEPLOYMENT_OUT)$([ -n "$BROADCAST_FLAG" ] || echo ' [DRY RUN]')…" cd pkg/contracts && mkdir -p deployments && forge script scripts/devnet/DeployProofSystem.s.sol:DeployProofSystem \ - --rpc-url "$L1_RPC_URL" --private-key "$PRIVATE_KEY" $BROADCAST_FLAG --slow + --rpc-url "$L1_RPC_URL" --rpc-timeout "${TIMEOUT:-50}" --private-key "$PRIVATE_KEY" $BROADCAST_FLAG --slow -# Activate the registered WIP-1006 implementation after validating its wiring and current anchor. +# Phase 2b (devnet only) – Mint mock bond tokens and top up proof-system bond accounts. +# The vault's deposit API credits selected accounts, so the funding operator does not need service +# keys. Targets make the operation idempotent and account for tokens already returned by settled games. +# Run this after deploying the vault and before starting the proposer or challenger. +[doc("Phase 2b (devnet only) - Fund mock-token vault balances for proof-system bond accounts.")] +[group('proof')] +proof-fund-mock-bonds env="alphanet": + #!/usr/bin/env bash + set -euo pipefail + : "${PRIVATE_KEY:?PRIVATE_KEY is required}" + : "${L1_RPC_URL:?L1_RPC_URL is required}" + : "${BOND_ACCOUNTS:?BOND_ACCOUNTS is required (comma-separated addresses)}" + SYSTEM_FILE="pkg/contracts/deployments/{{env}}-proof-system.json" + if [ -z "${ERC20_STAKING_VAULT:-}" ] && [ -f "$SYSTEM_FILE" ]; then + ERC20_STAKING_VAULT=$(jq -r '.erc20StakingVault // empty' "$SYSTEM_FILE") + export ERC20_STAKING_VAULT + fi + : "${ERC20_STAKING_VAULT:?ERC20_STAKING_VAULT is required (or deploy the proof system first)}" + export VAULT_BALANCE_TARGET="${VAULT_BALANCE_TARGET:-10000000000000000000000}" + BROADCAST_FLAG="" + if [ "{{dry_run}}" = "false" ]; then + BROADCAST_FLAG="--broadcast --skip-simulation" + fi + echo "WARNING: minting unrestricted mock bond tokens for proof-system accounts on '{{env}}'." >&2 + echo " accounts: $BOND_ACCOUNTS" >&2 + echo " available vault balance target: $VAULT_BALANCE_TARGET base units per account" >&2 + cd pkg/contracts && forge script scripts/devnet/FundProofBondAccounts.s.sol:FundProofBondAccounts \ + --rpc-url "$L1_RPC_URL" --rpc-timeout "${TIMEOUT:-50}" --private-key "$PRIVATE_KEY" $BROADCAST_FLAG --slow + +# Register and activate the WIP-1006 implementation after validating its wiring and current anchor. # Set REQUIRE_FRESH_ANCHOR=true during a clean chain bootstrap. -[doc("Activate the registered WIP-1006 implementation after validating its wiring.")] +[doc("Validate, register, and activate a WIP-1006 implementation.")] [group('proof')] proof-activate-system env="alphanet": #!/usr/bin/env bash @@ -246,15 +314,33 @@ proof-activate-system env="alphanet": : "${DISPUTE_GAME_FACTORY:?DISPUTE_GAME_FACTORY is required}" : "${ANCHOR_STATE_REGISTRY:?ANCHOR_STATE_REGISTRY is required}" : "${SYSTEM_CONFIG:?SYSTEM_CONFIG is required}" - : "${GUARDIAN_KEY:?GUARDIAN_KEY is required}" + : "${OP_CHAIN_PROXY_ADMIN:?OP_CHAIN_PROXY_ADMIN is required}" + : "${BOND_TOKEN:?BOND_TOKEN is required}" + if [ "${GOVERNANCE_MODE:-eoa}" != "safe" ]; then + : "${DGF_OWNER_KEY:?DGF_OWNER_KEY is required}" + fi + DEPLOYMENTS_FILE="pkg/contracts/deployments/{{env}}-proof-system.json" + if [ -z "${GAME_IMPLEMENTATION:-}" ] && [ -f "$DEPLOYMENTS_FILE" ]; then + GAME_IMPLEMENTATION=$(jq -r '.gameImplementation // empty' "$DEPLOYMENTS_FILE") + export GAME_IMPLEMENTATION + fi + : "${GAME_IMPLEMENTATION:?GAME_IMPLEMENTATION is required (or deploy first)}" export REQUIRE_FRESH_ANCHOR="${REQUIRE_FRESH_ANCHOR:-false}" BROADCAST_FLAG="" if [ "{{dry_run}}" = "false" ]; then - BROADCAST_FLAG="--broadcast" + BROADCAST_FLAG="--broadcast --skip-simulation" + fi + if [ "${GOVERNANCE_MODE:-eoa}" = "safe" ]; then + if [ "{{dry_run}}" = "true" ]; then + export SAFE_TX_OUT="${SAFE_TX_OUT:-deployments/{{env}}-activation.dryrun.safe.json}" + else + export SAFE_TX_OUT="${SAFE_TX_OUT:-deployments/{{env}}-activation.safe.json}" + fi + BROADCAST_FLAG="" fi - echo "Activating WIP-1006 (require fresh anchor: $REQUIRE_FRESH_ANCHOR)$([ -n "$BROADCAST_FLAG" ] || echo ' [DRY RUN]')…" >&2 + echo "Registering and activating WIP-1006 implementation $GAME_IMPLEMENTATION (require fresh anchor: $REQUIRE_FRESH_ANCHOR)$([ -n "$BROADCAST_FLAG" ] || echo ' [DRY RUN]')…" >&2 cd pkg/contracts && forge script scripts/devnet/ActivateProofSystem.s.sol:ActivateProofSystem \ - --rpc-url "$L1_RPC_URL" --private-key "$GUARDIAN_KEY" $BROADCAST_FLAG --slow + --rpc-url "$L1_RPC_URL" --rpc-timeout "${TIMEOUT:-50}" $BROADCAST_FLAG --slow # Phase 3a – Pre-warm CertManager with the AWS Nitro CA cert chain. # @@ -306,14 +392,14 @@ proof-certmanager-prewarm env="alphanet": BROADCAST_FLAG="" PREWARM_SKIP_IF_UNDEPLOYED="false" if [ "{{dry_run}}" = "false" ]; then - BROADCAST_FLAG="--broadcast" + BROADCAST_FLAG="--broadcast --skip-simulation" else PREWARM_SKIP_IF_UNDEPLOYED="true" fi cd pkg/contracts && CERT_MANAGER_ADDRESS="$CERT_MANAGER_ADDRESS" PREWARM_PLAN="$PREWARM_PLAN" \ PREWARM_SKIP_IF_UNDEPLOYED="$PREWARM_SKIP_IF_UNDEPLOYED" \ forge script scripts/devnet/PrewarmCertManager.s.sol:PrewarmCertManager \ - --rpc-url "$L1_RPC_URL" --private-key "$PRIVATE_KEY" $BROADCAST_FLAG --slow + --rpc-url "$L1_RPC_URL" --rpc-timeout "${TIMEOUT:-50}" --private-key "$PRIVATE_KEY" $BROADCAST_FLAG --slow # Phase 3b – Approve the PCR set on NitroAttestationVerifier. [group('proof')] @@ -327,7 +413,9 @@ proof-approve-pcrs env="alphanet": export NITRO_ATTESTATION_VERIFIER fi : "${NITRO_ATTESTATION_VERIFIER:?NITRO_ATTESTATION_VERIFIER is required}" - : "${OWNER_KEY:?OWNER_KEY is required}" + if [ "${GOVERNANCE_MODE:-eoa}" != "safe" ]; then + : "${OWNER_KEY:?OWNER_KEY is required}" + fi : "${L1_RPC_URL:?L1_RPC_URL is required}" : "${PCR0:?PCR0 is required (48-byte hex)}" : "${PCR1:?PCR1 is required (48-byte hex)}" @@ -337,17 +425,18 @@ proof-approve-pcrs env="alphanet": [[ "$PCR0" == 0x* ]] || PCR0="0x$PCR0" [[ "$PCR1" == 0x* ]] || PCR1="0x$PCR1" [[ "$PCR2" == 0x* ]] || PCR2="0x$PCR2" - if [ "{{dry_run}}" = "true" ]; then - echo "[DRY RUN] Estimating gas…" - cast estimate "$NITRO_ATTESTATION_VERIFIER" \ - "approvePCRSet(bytes32,bytes32,bytes32)" \ - "$(cast keccak "$PCR0")" "$(cast keccak "$PCR1")" "$(cast keccak "$PCR2")" \ - --rpc-url "$L1_RPC_URL" --from "$(cast wallet address --private-key "$OWNER_KEY")" - else - cast send "$NITRO_ATTESTATION_VERIFIER" \ - "approvePCRSet(bytes32,bytes32,bytes32)" \ - "$(cast keccak "$PCR0")" "$(cast keccak "$PCR1")" "$(cast keccak "$PCR2")" \ - --rpc-url "$L1_RPC_URL" --private-key "$OWNER_KEY" + for pcr in "$PCR0" "$PCR1" "$PCR2"; do + [[ "$pcr" =~ ^0x[0-9a-fA-F]{96}$ ]] || { echo "Error: PCR must be 48-byte hex" >&2; exit 1; } + done + export GOVERNANCE_TARGET="$NITRO_ATTESTATION_VERIFIER" + GOVERNANCE_CALLDATA="$(cast calldata 'approvePCRSet(bytes32,bytes32,bytes32)' "$(cast keccak "$PCR0")" "$(cast keccak "$PCR1")" "$(cast keccak "$PCR2")")" + export GOVERNANCE_CALLDATA + just dry_run={{dry_run}} proof-governance-call + if [ "${GOVERNANCE_MODE:-eoa}" = "safe" ]; then + echo "PCR approval prepared; execute the exported transaction in Safe before using these measurements." + exit 0 + fi + if [ "{{dry_run}}" != "true" ]; then # Record which measurements are actually approved on this verifier. DeployNitro only # writes addresses, so without this the deployment file cannot tell an approved # allowlist from an empty one — and an unprovisioned verifier rejects every @@ -360,4 +449,100 @@ proof-approve-pcrs env="alphanet": echo "Recorded approved PCR set in $DEPLOYMENTS_FILE" fi fi - echo "PCR set approved." + if [ "{{dry_run}}" = "true" ]; then + echo "PCR approval simulation complete." + else + echo "PCR set approved." + fi + +# Safe mode reuses GOVERNANCE_SAFE; the default EOA council is a 1-of-1 Safe. +[group('proof')] +proof-deploy-council env="alphanet": + #!/usr/bin/env bash + set -euo pipefail + : "${PRIVATE_KEY:?PRIVATE_KEY is required}" + : "${L1_RPC_URL:?L1_RPC_URL is required}" + if [ "${GOVERNANCE_MODE:-eoa}" != "safe" ] && [ -z "${COUNCIL_OWNERS:-}" ]; then + : "${ADMIN_PRIVATE_KEY:?ADMIN_PRIVATE_KEY or COUNCIL_OWNERS is required}" + export COUNCIL_OWNERS="$(cast wallet address --private-key "$ADMIN_PRIVATE_KEY")" + fi + BROADCAST_FLAG="" + if [ "{{dry_run}}" = "false" ]; then + BROADCAST_FLAG="--broadcast --skip-simulation" + export COUNCIL_DEPLOYMENT_OUT="deployments/{{env}}-council.json" + else + export COUNCIL_DEPLOYMENT_OUT="deployments/{{env}}-council.dryrun.json" + fi + cd pkg/contracts && mkdir -p deployments && forge script scripts/devnet/DeployCouncilSafe.s.sol:DeployCouncilSafe \ + --rpc-url "$L1_RPC_URL" --rpc-timeout "${TIMEOUT:-50}" $BROADCAST_FLAG --slow + +# GOVERNANCE_TARGET and GOVERNANCE_CALLDATA describe a single privileged call. +[group('proof')] +proof-governance-call: + #!/usr/bin/env bash + set -euo pipefail + : "${L1_RPC_URL:?L1_RPC_URL is required}" + BROADCAST_FLAG="" + if [ "{{dry_run}}" = "false" ]; then BROADCAST_FLAG="--broadcast --skip-simulation"; fi + if [ "${GOVERNANCE_MODE:-eoa}" = "safe" ]; then + export SAFE_TX_OUT="${SAFE_TX_OUT:-deployments/governance.safe.json}" + BROADCAST_FLAG="" + fi + cd pkg/contracts && forge script scripts/devnet/Governance.s.sol:ExecuteGovernance \ + --rpc-url "$L1_RPC_URL" --rpc-timeout "${TIMEOUT:-50}" $BROADCAST_FLAG --slow + +# Explicit handoff: GOVERNANCE_MODE describes the current authority; NEW_NITRO_OWNER is the target. +[group('proof')] +proof-transfer-nitro-ownership env="alphanet": + #!/usr/bin/env bash + set -euo pipefail + : "${L1_RPC_URL:?L1_RPC_URL is required}" + : "${NEW_NITRO_OWNER:?NEW_NITRO_OWNER is required}" + DEPLOYMENTS_FILE="pkg/contracts/deployments/{{env}}-nitro.json" + if [ -f "$DEPLOYMENTS_FILE" ]; then + export CERT_MANAGER_ADDRESS="${CERT_MANAGER_ADDRESS:-$(jq -r '.certManager' "$DEPLOYMENTS_FILE")}" + export NITRO_ATTESTATION_VERIFIER="${NITRO_ATTESTATION_VERIFIER:-$(jq -r '.nitroAttestationVerifier' "$DEPLOYMENTS_FILE")}" + export NITRO_ENCLAVE_KEY_REGISTRY="${NITRO_ENCLAVE_KEY_REGISTRY:-$(jq -r '.nitroEnclaveKeyRegistry' "$DEPLOYMENTS_FILE")}" + fi + BROADCAST_FLAG="" + if [ "{{dry_run}}" = "false" ]; then BROADCAST_FLAG="--broadcast --skip-simulation"; fi + if [ "${GOVERNANCE_MODE:-eoa}" = "safe" ]; then + export SAFE_TX_OUT="${SAFE_TX_OUT:-deployments/{{env}}-nitro-handoff.safe.json}" + BROADCAST_FLAG="" + fi + (cd pkg/contracts && forge script scripts/devnet/TransferNitroOwnership.s.sol:TransferNitroOwnership \ + --rpc-url "$L1_RPC_URL" --rpc-timeout "${TIMEOUT:-50}" $BROADCAST_FLAG --slow) + if [ "${GOVERNANCE_MODE:-eoa}" = "safe" ]; then + echo "Handoff prepared; execute in Safe, then verify owners and CertManager revoker." + exit 0 + fi + if [ "{{dry_run}}" = "false" ]; then + for contract in "$CERT_MANAGER_ADDRESS" "$NITRO_ATTESTATION_VERIFIER" "$NITRO_ENCLAVE_KEY_REGISTRY"; do + ACTUAL_OWNER="$(cast call "$contract" 'owner()(address)' --rpc-url "$L1_RPC_URL" --rpc-timeout "${TIMEOUT:-50}")" + [[ "${ACTUAL_OWNER,,}" = "${NEW_NITRO_OWNER,,}" ]] || { echo "Nitro handoff owner verification failed for $contract" >&2; exit 1; } + done + ACTUAL_REVOKER="$(cast call "$CERT_MANAGER_ADDRESS" 'revoker()(address)' --rpc-url "$L1_RPC_URL" --rpc-timeout "${TIMEOUT:-50}")" + [[ "${ACTUAL_REVOKER,,}" = "${NEW_NITRO_OWNER,,}" ]] || { echo "Nitro handoff revoker verification failed" >&2; exit 1; } + if [ -f "$DEPLOYMENTS_FILE" ]; then + TMP_DEPLOYMENTS="$(mktemp)" + jq --arg owner "$NEW_NITRO_OWNER" --arg cm "$CERT_MANAGER_ADDRESS" --arg verifier "$NITRO_ATTESTATION_VERIFIER" --arg registry "$NITRO_ENCLAVE_KEY_REGISTRY" \ + 'if (.certManager | ascii_downcase) == ($cm | ascii_downcase) and (.nitroAttestationVerifier | ascii_downcase) == ($verifier | ascii_downcase) and (.nitroEnclaveKeyRegistry | ascii_downcase) == ($registry | ascii_downcase) then .owner = $owner | .revoker = $owner else error("Nitro deployment record addresses differ from handoff") end' \ + "$DEPLOYMENTS_FILE" > "$TMP_DEPLOYMENTS" + mv "$TMP_DEPLOYMENTS" "$DEPLOYMENTS_FILE" + fi + fi + +[group('proof')] +proof-submit-council: + #!/usr/bin/env bash + set -euo pipefail + : "${L1_RPC_URL:?L1_RPC_URL is required}" + BROADCAST_FLAG="" + if [ "{{dry_run}}" = "false" ]; then BROADCAST_FLAG="--broadcast --skip-simulation"; fi + cd pkg/contracts && forge script scripts/devnet/SubmitSecurityCouncilProof.s.sol:SubmitSecurityCouncilProof \ + --rpc-url "$L1_RPC_URL" --rpc-timeout "${TIMEOUT:-50}" $BROADCAST_FLAG --slow + +# Prepare calldata, or propose a council transaction with one owner's wallet; never execute. +[group('proof')] +safe-operation *args: + python3 scripts/safe-operation.py "$@" diff --git a/justfiles/rust.just b/justfiles/rust.just index bece7015a..2cb21ebd4 100644 --- a/justfiles/rust.just +++ b/justfiles/rust.just @@ -35,15 +35,15 @@ test-verbose *args='': [group('lint')] clippy: - cargo +nightly-2026-07-01 clippy --workspace --all-targets --all-features + cargo +nightly-2026-10-10 clippy --workspace --all-targets --all-features [group('lint')] fmt: fmt-fix fmt-check contracts-fmt [group('lint')] fmt-fix: - cargo +nightly-2026-07-01 fmt --all + cargo +nightly-2026-10-10 fmt --all [group('lint')] fmt-check: - cargo +nightly-2026-07-01 fmt --all -- --check + cargo +nightly-2026-10-10 fmt --all -- --check diff --git a/pkg/contracts/README.md b/pkg/contracts/README.md index bd5f5b0d7..76cfc0490 100644 --- a/pkg/contracts/README.md +++ b/pkg/contracts/README.md @@ -10,11 +10,11 @@ This repository contains smart contracts for World Chain, including PBH (Priorit ## Proof System Bond Claims -`MultiProofGame.resolve()` records the game outcome and assigns pull-based bond credit in the game type's OP Stack `DelayedWETH` contract. It does not transfer ETH during resolution. +WIP-1006 proposal and challenge bonds use a deployment-selected token held one-to-one in the upgradeable `ERC20StakingVault`; World Chain configures WLD as that bond token. Participants deposit the token once, without leaving a standing allowance. The stock `DisputeGameFactory` remains unchanged and its type-1006 ETH initialization bond is zero. A proposer calls the stock factory directly; during `initialize` the vault authenticates the clone against the factory's deterministic deployment address and locks the bond from `gameCreator`'s available balance. -`credit(recipient)` returns the amount assigned to `recipient`. `claimCredit(recipient)` is permissionless and always pays `recipient`: its first call unlocks the credit in `DelayedWETH`, and a call after the withdrawal delay transfers the funds. Automation must retain resolved games until both phases complete. +`MultiProofGame.resolve()` records the outcome and payout credits without moving funds. After ASR finality, `closeGame()` selects normal or refund mode and atomically credits the complete game pot to recipients' reusable vault balances. Each account may later request a token withdrawal and transfer it after the vault delay; new requests reset the delay for the full pending amount. -Every accepted challenge deducts the implementation's immutable `challengeFee` from the challenger bond and credits it to the immutable `protocolFeeRecipient`. The fee remains charged in both normal and refund settlement modes, preventing a proposer and challenger under common control from recycling the full bond while forcing an additional proof. The proposer bond must exceed the challenge fee, making a successful challenge gross-profitable before transaction costs. +The vault is WIP-1006-only and supports old registered game implementations after upgrades. It exposes no administrative path for moving participant balances or extracting backing tokens directly. The DisputeGameFactory owner and vault ProxyAdmin owner must remain the same governance authority; new bond locks fail closed if they diverge. ## OP Stack Withdrawal Boundary @@ -33,7 +33,7 @@ Blacklisting an individual game immediately makes it improper for Portal proofs. The full-stack withdrawal E2E test uses the real OP-deployer Portal, factory, and registry. It proves against an in-progress WIP-1006 game, verifies the proof-maturity and registry-finality delays, finalizes after `DEFENDER_WINS`, and checks that a blacklisted game is rejected. -The devnet deployment registers `MultiProofGame` as game type `1006`, configures its bond and `DelayedWETH`, and changes the stock registry's respected game type. It deploys mock verifier and staking contracts and is not a production deployment procedure. A production activation must use real audited verifier dependencies and the audited OP governance process for registering and respecting the new game type; it does not upgrade or replace the factory or registry. +The first devnet deployment creates the `MultiProofGame` implementation and its ERC-20 staking vault. The separate activation validates the complete wiring, sets the factory ETH bond to zero, registers game type `1006`, and changes the stock registry's respected game type when needed. Later game-implementation rotations must reuse the existing vault, preserving one capital pool across versions. The scripts deploy mock verifier contracts and are not a production deployment procedure. A production activation must use the intended canonical bond token, real audited verifier dependencies, and the audited OP governance process for registering and respecting the new game type; it does not upgrade or replace the factory or registry. ## PBH Contracts @@ -91,3 +91,88 @@ The `FeeEscrow` contract handles the conversion of ETH to WLD for burning. Key f - Includes slippage protection (0.03%) to ensure fair execution The burn mechanism requires executors to implement the `IBurnCallback` interface, providing flexibility in how the ETH-to-WLD swap is performed (e.g., via Uniswap V3). + +## Devnet governance + +`GOVERNANCE_MODE=eoa` is the default. Existing EOA keys (`DGF_OWNER_KEY`, +`GUARDIAN_KEY`, `OP_CHAIN_PROXY_ADMIN_OWNER_PRIVATE_KEY`, Nitro `OWNER` / `OWNER_KEY`) +continue to work, and council deployment defaults to threshold one. + +`GOVERNANCE_MODE=safe` uses a manually created `GOVERNANCE_SAFE` with two owners, +threshold two, no enabled modules, and the compatibility fallback handler for +ERC-1271 council attestations. Bootstrap requires its address and never needs either +owner's private key. `PRIVATE_KEY` funds deployments. The council verifier is bound +to the same Safe as the owners and guardian. + +- `just proof-deploy-council ` binds a new verifier to an existing Safe. In EOA + mode it deploys a council Safe from `COUNCIL_OWNERS` or `ADMIN_PRIVATE_KEY`, with + threshold one by default. +- `just proof-deploy-nitro ` assigns the selected owner immediately to + CertManager (including its revoker), NitroAttestationVerifier and NitroEnclaveKeyRegistry. +- In Safe mode, `proof-deploy-system` exports the new vault initialization and stops + before deploying the game. After Safe execution, resume with `ERC20_STAKING_VAULT` + set to the initialized vault. `proof-activate-system` exports registration, + zero native bond and respected-game-type calls as a Transaction Builder batch. +- `proof-governance-call`, `proof-approve-pcrs`, and `proof-transfer-nitro-ownership` + export Safe transactions; preparation never reports an approval as executed. + Their EOA paths still broadcast by default unless `dry_run=true`. +- `just safe-operation --out /tmp/operation.json call '' ` + prepares a zero-value CALL for Transaction Builder. Supply `GOVERNANCE_SAFE` and + `L1_RPC_URL`, and optionally `L1_CHAIN_ID` (default Sepolia). World-chain recipes + do not load devnet's env files; devnet's `just safe-operation ...` does. +- `council-submit --game

` prepares one atomic Safe transaction: approve + the exact council attestation through `SignMessageLib`, then call the game's + `submitProofLane` with an empty proof body. The tool validates game registration, + council, active proof state, and canonical version-matched library code, then + simulates the batch without persisting state. The output is a Safe transaction + proposal, not a Transaction Builder import; the approval requires DELEGATECALL. +- `just safe-operation propose --transaction --sender --browser` + signs the prepared council transaction as one owner and publishes it to the Safe + Transaction Service. The other owner confirms and executes in the Safe UI. Use + `--interactive`, `--account `, `--ledger` or `--trezor` instead of + `--browser` when appropriate. No signature files or shared owner keys are needed. + Nonce conflicts fail before signing; `council-submit --nonce ` can + queue after existing proposals. The tool never executes a transaction. +- When using MetaMask as a standard EOA executor, + [revert smart account functionality](https://support.metamask.io/configure/accounts/switch-to-or-revert-from-a-smart-account/) + for that account on Sepolia and confirm the revocation transaction. Disabling + smart account requests alone does not clear existing EIP-7702 delegation. Check + `cast code --rpc-url "$L1_RPC_URL" --rpc-timeout 20`: standard EOA code is + `0x`; `0xef0100...` indicates an active delegation. Safe still enforces its + two-owner threshold. The executing wallet estimates outer transaction gas; + Transaction Builder files only supply the calls. +- Council proposals support Sepolia Safes 1.3.0, 1.4.1 and 1.5.0. Library addresses + and code hashes are pinned to the official Safe deployment registry. Other + versions fail explicitly until their audited library entries are added. + `SAFE_TRANSACTION_SERVICE_URL` defaults to the official Sepolia API base URL; + set `SAFE_TRANSACTION_SERVICE_API_KEY` for authenticated access if needed. + Service calls have bounded timeouts and never automatically retry proposals. +- `proof-submit-council` retains the default EOA council's `COUNCIL_SIGNER_KEY` flow. + Supplied combined `COUNCIL_SIGNATURES` can still be relayed with `PRIVATE_KEY`. + +The direct Forge scripts retain their earlier two-key execution path for existing +callers without `SAFE_TX_OUT`. The recipes above always prepare transactions in Safe +mode. Use the manual workflow to test independent approvals. + +Reused Nitro contracts require an explicit ownership handoff. Set +`CERT_MANAGER_ADDRESS`, `NITRO_ATTESTATION_VERIFIER`, `NITRO_ENCLAVE_KEY_REGISTRY` +(or supply the matching `-nitro.json`), and `NEW_NITRO_OWNER`. Set +`GOVERNANCE_MODE` and keys for the **current** authority, then simulate: + +```bash +just dry_run=true proof-transfer-nitro-ownership alphanet +``` + +In EOA mode the recipe broadcasts by default when `dry_run` is omitted. In Safe +mode it exports a batch for review and execution. It moves all three owners and +the CertManager revoker, checks the wiring, and supports resuming a partially +completed handoff. It preserves verifier addresses and existing games' +Nitro identities. Moving Nitro authority does not revoke approved PCRs or registered +keys. Existing games keep their council verifier; a new council address is selected +by deploying/activating a new game implementation. + +The devnet repository orchestrates these settings before `just setup `. +Safe mode pauses with exit status 75 and prints the file to approve. Execute it in +Safe, then use `just resume-setup `; resume never resets the OP Stack state. +See [the full reset runbook](../../docs/proof/devnet-reset.md) for both modes. +Existing proof parameters and mock bond tokens remain development settings. diff --git a/pkg/contracts/deployments/alphanet-council.json b/pkg/contracts/deployments/alphanet-council.json index dc907311e..a44f05664 100644 --- a/pkg/contracts/deployments/alphanet-council.json +++ b/pkg/contracts/deployments/alphanet-council.json @@ -1,12 +1,13 @@ { "councilOwners": [ - "0x629D8810D0177cB7f2315272F8237E68A8E2017f" + "0x629D8810D0177cB7f2315272F8237E68A8E2017f", + "0x4E3C095FCA073e987EfE42917733fB0DCf10A777" ], - "councilSafe": "0xDd84fc8Ec84a735979d34fc5e4e1d5adeBad3554", - "councilThreshold": 1, - "safeFallbackHandler": "0xA049D897Eb1831a3973d4a8F8B67b3b4aAb9c33C", - "safeProxyFactory": "0xf0F01686E119d49dFCa13c64Bc997c16a05A0f25", + "councilSafe": "0x3EEAC67cf59Eb61A995F9F34859F042DA819E27A", + "councilThreshold": 2, + "safeFallbackHandler": "0x0000000000000000000000000000000000000000", + "safeProxyFactory": "0x0000000000000000000000000000000000000000", "safeSaltNonce": 0, - "safeSingleton": "0xf98ac01CcC2ef34DDc84c474f01c162B39732Bc3", - "securityCouncilVerifier": "0x9Ea4EF54aF8eBC385D915FF60B27a614EC942674" -} + "safeSingleton": "0x0000000000000000000000000000000000000000", + "securityCouncilVerifier": "0xE72e8E2DB2B67a40e56e4EF7442d85f9D0317Da3" +} \ No newline at end of file diff --git a/pkg/contracts/deployments/alphanet-mock-bond-token.json b/pkg/contracts/deployments/alphanet-mock-bond-token.json new file mode 100644 index 000000000..05cf517f9 --- /dev/null +++ b/pkg/contracts/deployments/alphanet-mock-bond-token.json @@ -0,0 +1,3 @@ +{ + "bondToken": "0x47803844EB248cEBE6c8De0e918E75923Da02C6B" +} \ No newline at end of file diff --git a/pkg/contracts/deployments/alphanet-nitro.json b/pkg/contracts/deployments/alphanet-nitro.json index c2ac1cb6a..2bf5a37d7 100644 --- a/pkg/contracts/deployments/alphanet-nitro.json +++ b/pkg/contracts/deployments/alphanet-nitro.json @@ -1,21 +1,16 @@ { - "p384Verifier": "0x937f4d3B2560dCd5F5Bc20a6cA4C34E3555C27bA", - "certManager": "0x6Dde293815EEe33522CAA5e31705a2EB323dbC58", - "nitroAttestationVerifier": "0xbabc1a3B2b239C3b73008a8f8B7D2800e40911BA", - "nitroEnclaveKeyRegistry": "0xbD9536a734756A92f7598CB6e4f837273Fc7A300", - "nitroProofVerifier": "0x1E21Ac0cdC246ED3A6f705d2a1EE923d02213649", + "p384Verifier": "0xE5Da4f6D83c7954b988973AE77c944ea63128438", + "certManager": "0xb4F086822516adB5B50b9a622cd1D49e6c5F5260", + "nitroAttestationVerifier": "0xa22d3dDC3BF4fE4329F4dF93A52d89FCDa05DE4E", + "nitroEnclaveKeyRegistry": "0x8242A5Dc01B0B181a40582d943349bbc2475D8ab", + "nitroProofVerifier": "0x4D7313543cF99712223733F6f20B2f4701AE2ED6", "approvedPCRSets": [ { "verifier": "0xbabc1a3B2b239C3b73008a8f8B7D2800e40911BA", - "pcr0": "0x4cac3584d154bc223e6280d1f7b8593f6150306a64d4d1c3c02d2e8bf3461c9ad4a7577e5be3e571f5a10ca8100fe4ae", - "pcr1": "0x0343b056cd8485ca7890ddd833476d78460aed2aa161548e4e26bedf321726696257d623e8805f3f605946b3d8b0c6aa", - "pcr2": "0x3e5902b61c0763b8d528854979c9a3e3303d2be1fa24ac6a7654644874eec6ef700447822dc2b95cd53329cb13dca64b" - }, - { - "verifier": "0xbabc1a3B2b239C3b73008a8f8B7D2800e40911BA", - "pcr0": "0x1047a9abb6fdfc70f1e4df56faf857fba33b7c2643833e0845060d21133a1812d31c113af3ff4582dfcb5ee5af3a5477", + "pcr0": "0x78a5ad6bfa18df38634005d8dde4adde28da71c73727429e29bc50eab7acafbea73b8b72639903d1cd2d6453a44ef259", "pcr1": "0xab92a79f22cbca162b415c97f3406327ab858f9a73ffd4f7720710529eee87f085d21c3dd2819ef63263b0dad0b4a9d6", - "pcr2": "0x94bc876bd0dfc0f5c8d8f1c34cbdbc0c4e6f2521428805901b660c85391afca77b435b1b1cace64aba01313ae91d2c3b" + "pcr2": "0xaf4a041a0fb5566cf3cf7fed205acd80315aaa22566681e812bc8ec26a7c1d617041ce23d94142be5ab0dbd3fc479148" } - ] -} + ], + "owner": "0x3EEAC67cf59Eb61A995F9F34859F042DA819E27A" +} \ No newline at end of file diff --git a/pkg/contracts/deployments/alphanet-proof-system.json b/pkg/contracts/deployments/alphanet-proof-system.json index c3433070e..624acb8eb 100644 --- a/pkg/contracts/deployments/alphanet-proof-system.json +++ b/pkg/contracts/deployments/alphanet-proof-system.json @@ -1,30 +1,31 @@ { - "aggregationVKey": "0x004d15ae5aedd4ec4fec8102118493fe024110c82762229a04868700603a5aff", + "aggregationVKey": "0x00efdc175d0174ae50b58d2aec7c3d5b0415eb107b1b33ec23321fe48bb9e2d4", "anchorGameAtDeployment": "0x0000000000000000000000000000000000000000", - "anchorStateRegistry": "0x9EA304a78C3fDEC69EfCe0d1E66e678100F67e9f", - "blockInterval": 1800, - "challengePeriod": 86400, + "anchorStateRegistry": "0x3Efdb71E5518D50F467FEaA585D4f7be8fDB6E3C", + "blockInterval": 450, + "bondToken": "0x47803844EB248cEBE6c8De0e918E75923Da02C6B", + "challengePeriod": 10800, "challengerBond": 1000000000000000, - "delayedWeth": "0x6644F4d3f631D4Fef4c67363D8A9Da64f4CE4C52", - "delayedWethDelay": 300, - "delayedWethProxyAdmin": "0x0d9B73080AE8871317e91616B1125a155406dB8f", - "disputeGameFactory": "0xD41b89fF74e26585d98cd3f780d501b8fcC7Ca94", - "gameImplementation": "0x8294910e1e35E53B95D0b8F14eEc8E552b2925Ce", + "disputeGameFactory": "0x1582E8b301AE6478547b813001d4f0F6ec45aF46", + "erc20StakingVault": "0x454a5C79beA35FF2efF7145F21dc1F9D1790Ee37", + "erc20StakingVaultProxyAdmin": "0x96e6B9317fAd6222e482C08b3D166168dF568239", + "erc20WithdrawalDelay": 300, + "gameImplementation": "0x2D91722faA1466199FD3646558076e415E55f81C", "gameType": 1006, "l2ChainId": 5496749, - "opChainProxyAdmin": "0x0d9B73080AE8871317e91616B1125a155406dB8f", - "proofPeriod": 604800, - "proofSystemFactory": "0xD41b89fF74e26585d98cd3f780d501b8fcC7Ca94", + "opChainProxyAdmin": "0x96e6B9317fAd6222e482C08b3D166168dF568239", + "proofPeriod": 36000, + "proofSystemFactory": "0x1582E8b301AE6478547b813001d4f0F6ec45aF46", "proofSystemVersion": 1, "proofThreshold": 2, "proposerBond": 10000000000000000, - "protocolFeeRecipient": "0x629D8810D0177cB7f2315272F8237E68A8E2017f", - "rangeVKeyCommitment": "0x4082e07347e801d82c3e8fb252fe6f734d48af3a18c6d36b0646caa060291f6e", - "retirementTimestampAtDeployment": 1787564904, - "rollupConfigHash": "0x596e1d47ebb3b3114b02d4fa51a23e617278aa0417cbd8e4f8bd7ae067078aee", - "securityCouncil": "0x9Ea4EF54aF8eBC385D915FF60B27a614EC942674", - "systemConfig": "0xcD4E41670E7da9fC3D95Fbf31AbAB5FF32E97fe5", - "teeImageId": "0x9ad7ecef4da6531324b5e8f956c5d5bf37416c71791349647be257d49a2d6a44", - "teeVerifier": "0x1E21Ac0cdC246ED3A6f705d2a1EE923d02213649", + "protocolFeeRecipient": "0x3EEAC67cf59Eb61A995F9F34859F042DA819E27A", + "rangeVKeyCommitment": "0x7aa8501d5a48de8d631ab8c54adb69d20d819d6e59247edf199c8a161e98aacc", + "retirementTimestampAtDeployment": 1791367404, + "rollupConfigHash": "0x8d329e8e50a6d3892308ce86f1804bf98ef1b56f4969ab19c639e781f861c6d6", + "securityCouncil": "0xE72e8E2DB2B67a40e56e4EF7442d85f9D0317Da3", + "systemConfig": "0x82D65aA4952a09C2a145d5cc2bc57AC8B026EF3E", + "teeImageId": "0xbdbbc594aa2c45a91889a01d97d897c4b3c255f2ba01c598d8c2bc20d727e9b7", + "teeVerifier": "0x4D7313543cF99712223733F6f20B2f4701AE2ED6", "validityProofVerifier": "0x1DAB10b47703e775720Af3a845E9d94723A0c241" } \ No newline at end of file diff --git a/pkg/contracts/deployments/betanet-mock-bond-token.json b/pkg/contracts/deployments/betanet-mock-bond-token.json new file mode 100644 index 000000000..a2bf2a76f --- /dev/null +++ b/pkg/contracts/deployments/betanet-mock-bond-token.json @@ -0,0 +1,3 @@ +{ + "bondToken": "0xe0173550bd00BA4A148D55485F82910Fb9C757e5" +} \ No newline at end of file diff --git a/pkg/contracts/deployments/betanet-nitro.json b/pkg/contracts/deployments/betanet-nitro.json new file mode 100644 index 000000000..dfe5ad8e4 --- /dev/null +++ b/pkg/contracts/deployments/betanet-nitro.json @@ -0,0 +1,15 @@ +{ + "p384Verifier": "0x7129D6CEe216ed7239133fD953a76e00b5621ee1", + "certManager": "0x58F880BBD5a6c2B8a4eA797dE39326562bEf8356", + "nitroAttestationVerifier": "0x5d3034664893a16775f469c1d6ec9e5684118E81", + "nitroEnclaveKeyRegistry": "0x93cf740F1023A4a64268066FC2EC6e7Dbf063bA4", + "nitroProofVerifier": "0xB0d4c0FB34AA9701EF062d1Ab4726605a3eA01bd", + "approvedPCRSets": [ + { + "verifier": "0x5d3034664893a16775f469c1d6ec9e5684118E81", + "pcr0": "0x78a5ad6bfa18df38634005d8dde4adde28da71c73727429e29bc50eab7acafbea73b8b72639903d1cd2d6453a44ef259", + "pcr1": "0xab92a79f22cbca162b415c97f3406327ab858f9a73ffd4f7720710529eee87f085d21c3dd2819ef63263b0dad0b4a9d6", + "pcr2": "0xaf4a041a0fb5566cf3cf7fed205acd80315aaa22566681e812bc8ec26a7c1d617041ce23d94142be5ab0dbd3fc479148" + } + ] +} diff --git a/pkg/contracts/deployments/betanet-proof-system.json b/pkg/contracts/deployments/betanet-proof-system.json new file mode 100644 index 000000000..fdbfe8027 --- /dev/null +++ b/pkg/contracts/deployments/betanet-proof-system.json @@ -0,0 +1,31 @@ +{ + "aggregationVKey": "0x00efdc175d0174ae50b58d2aec7c3d5b0415eb107b1b33ec23321fe48bb9e2d4", + "anchorGameAtDeployment": "0x0000000000000000000000000000000000000000", + "anchorStateRegistry": "0xaA7B2985D5867F064D92F74e5E57Eb087eDAa193", + "blockInterval": 450, + "bondToken": "0xe0173550bd00BA4A148D55485F82910Fb9C757e5", + "challengePeriod": 10800, + "challengerBond": 1000000000000000, + "disputeGameFactory": "0x561408Ab33d00E8437718df80845A0A0b42bf60B", + "erc20StakingVault": "0x04aa05566F39570845B015912C4365aE1354c4B8", + "erc20StakingVaultProxyAdmin": "0x07c045C4C36c2bA1403b69248993Feac0158eE84", + "erc20WithdrawalDelay": 300, + "gameImplementation": "0x1F8785d0F638eD1eE83D345dA72F1d3A2861822A", + "gameType": 1006, + "l2ChainId": 4801222, + "opChainProxyAdmin": "0x07c045C4C36c2bA1403b69248993Feac0158eE84", + "proofPeriod": 36000, + "proofSystemFactory": "0x561408Ab33d00E8437718df80845A0A0b42bf60B", + "proofSystemVersion": 1, + "proofThreshold": 2, + "proposerBond": 10000000000000000, + "protocolFeeRecipient": "0x629D8810D0177cB7f2315272F8237E68A8E2017f", + "rangeVKeyCommitment": "0x7aa8501d5a48de8d631ab8c54adb69d20d819d6e59247edf199c8a161e98aacc", + "retirementTimestampAtDeployment": 1790756496, + "rollupConfigHash": "0x7f618d5976ab6db5dfc02746c988bbb34ec2fe9727e3a6ad0856c63e36f484d8", + "securityCouncil": "0x9Ea4EF54aF8eBC385D915FF60B27a614EC942674", + "systemConfig": "0x94f31bBc000Ed7C41E37B2B34d7aAe37058cA06D", + "teeImageId": "0xbdbbc594aa2c45a91889a01d97d897c4b3c255f2ba01c598d8c2bc20d727e9b7", + "teeVerifier": "0xB0d4c0FB34AA9701EF062d1Ab4726605a3eA01bd", + "validityProofVerifier": "0x1DAB10b47703e775720Af3a845E9d94723A0c241" +} \ No newline at end of file diff --git a/pkg/contracts/foundry.lock b/pkg/contracts/foundry.lock index 082139a36..384b40de4 100644 --- a/pkg/contracts/foundry.lock +++ b/pkg/contracts/foundry.lock @@ -9,7 +9,7 @@ "rev": "77041d2ce690e692d6e03cc812b57d1ddaa4d505" }, "lib/nitro-validator": { - "rev": "c0a9f217b6a51325c59c103a22939f9a3742a90d" + "rev": "0ea0d12366b4fa44f9e07e4755f2ad36561cb674" }, "lib/openzeppelin-contracts": { "rev": "69c8def5f222ff96f2b5beff05dfba996368aa79" diff --git a/pkg/contracts/lib/nitro-validator b/pkg/contracts/lib/nitro-validator index c0a9f217b..0ea0d1236 160000 --- a/pkg/contracts/lib/nitro-validator +++ b/pkg/contracts/lib/nitro-validator @@ -1 +1 @@ -Subproject commit c0a9f217b6a51325c59c103a22939f9a3742a90d +Subproject commit 0ea0d12366b4fa44f9e07e4755f2ad36561cb674 diff --git a/pkg/contracts/scripts/devnet/ActivateProofSystem.s.sol b/pkg/contracts/scripts/devnet/ActivateProofSystem.s.sol index 9f7e79893..71460d481 100644 --- a/pkg/contracts/scripts/devnet/ActivateProofSystem.s.sol +++ b/pkg/contracts/scripts/devnet/ActivateProofSystem.s.sol @@ -1,39 +1,92 @@ // SPDX-License-Identifier: MIT pragma solidity 0.8.28; -import {Script} from "forge-std/Script.sol"; +import {SecurityCouncilVerifier} from "../../src/dispute/council/SecurityCouncilVerifier.sol"; +import {Governance} from "./Governance.s.sol"; import {GameTypes} from "../../src/dispute/lib/GameTypes.sol"; import {IMultiProofGame} from "../../src/dispute/interfaces/IMultiProofGame.sol"; +import {IERC20StakingVault} from "../../src/dispute/interfaces/IERC20StakingVault.sol"; import {GameStatus} from "@optimism-bedrock/src/dispute/lib/Types.sol"; import {IDisputeGame} from "@optimism-bedrock/interfaces/dispute/IDisputeGame.sol"; import {IDisputeGameFactory} from "@optimism-bedrock/interfaces/dispute/IDisputeGameFactory.sol"; import {IAnchorStateRegistry} from "@optimism-bedrock/interfaces/dispute/IAnchorStateRegistry.sol"; +import {IProxyAdmin} from "@optimism-bedrock/interfaces/universal/IProxyAdmin.sol"; import {ISystemConfig} from "@optimism-bedrock/interfaces/L1/ISystemConfig.sol"; +import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; -/// @notice Activates an already-registered WIP-1006 implementation after verifying that its -/// wiring, bond and current ASR anchor allow new games to be created safely. -/// @dev This script never changes the ASR retirement timestamp. A nonzero anchor must satisfy -/// the same parent-validity conditions enforced by `MultiProofGame.initialize()`. -contract ActivateProofSystem is Script { +/// @notice Registers and activates a WIP-1006 implementation after verifying that its +/// wiring, vault, and ASR pointer are consistent enough for factory rotation. +/// @dev This script never changes the ASR retirement timestamp. A nonzero anchor must still be +/// registered, respected, and not retired. Blacklisting the current anchor is an incident +/// recovery case: the occupied factory UUID requires a new proof domain, so this script +/// must still be able to register the replacement implementation. +contract ActivateProofSystem is Governance { struct Config { uint256 guardianKey; + uint256 dgfOwnerKey; IDisputeGameFactory disputeGameFactory; IAnchorStateRegistry anchorStateRegistry; ISystemConfig systemConfig; + IProxyAdmin proxyAdmin; + IERC20 bondToken; + IMultiProofGame gameImplementation; bool requireFreshAnchor; } function run() external returns (IMultiProofGame gameImpl) { Config memory config = _readConfig(); - gameImpl = IMultiProofGame(address(config.disputeGameFactory.gameImpls(GameTypes.MULTI_PROOF_GAME_TYPE))); + gameImpl = config.gameImplementation; _validate(config, gameImpl); + _executeGovernance( + config.dgfOwnerKey, + address(config.disputeGameFactory), + abi.encodeWithSignature( + "setImplementation(uint32,address,bytes)", + GameTypes.MULTI_PROOF_GAME_TYPE.raw(), + address(gameImpl), + hex"" + ) + ); + // Register first so the transaction gap cannot allow zero-bond legacy games. + _executeGovernance( + config.dgfOwnerKey, + address(config.disputeGameFactory), + abi.encodeCall(IDisputeGameFactory.setInitBond, (GameTypes.MULTI_PROOF_GAME_TYPE, 0)) + ); + + if (_preparingSafe()) { + if (config.anchorStateRegistry.respectedGameType().raw() != GameTypes.MULTI_PROOF_GAME_TYPE.raw()) { + _executeGovernance( + config.guardianKey, + address(config.anchorStateRegistry), + abi.encodeCall(IAnchorStateRegistry.setRespectedGameType, (GameTypes.MULTI_PROOF_GAME_TYPE)) + ); + } + return gameImpl; + } + + require( + address(config.disputeGameFactory.gameImpls(GameTypes.MULTI_PROOF_GAME_TYPE)) == address(gameImpl), + "ActivateProofSystem: game implementation not registered" + ); + require( + config.disputeGameFactory.gameArgs(GameTypes.MULTI_PROOF_GAME_TYPE).length == 0, + "ActivateProofSystem: stale game implementation args" + ); + require( + config.disputeGameFactory.initBonds(GameTypes.MULTI_PROOF_GAME_TYPE) == 0, + "ActivateProofSystem: factory bond must be zero" + ); + if (config.anchorStateRegistry.respectedGameType().raw() != GameTypes.MULTI_PROOF_GAME_TYPE.raw()) { - vm.startBroadcast(config.guardianKey); - config.anchorStateRegistry.setRespectedGameType(GameTypes.MULTI_PROOF_GAME_TYPE); - vm.stopBroadcast(); + _executeGovernance( + config.guardianKey, + address(config.anchorStateRegistry), + abi.encodeCall(IAnchorStateRegistry.setRespectedGameType, (GameTypes.MULTI_PROOF_GAME_TYPE)) + ); } require( @@ -42,19 +95,33 @@ contract ActivateProofSystem is Script { ); } - function _readConfig() internal view returns (Config memory config) { - config.guardianKey = vm.envUint("GUARDIAN_KEY"); + function _readConfig() internal view virtual returns (Config memory config) { + config.guardianKey = vm.envOr("GUARDIAN_KEY", uint256(0)); + config.dgfOwnerKey = vm.envOr("DGF_OWNER_KEY", uint256(0)); config.disputeGameFactory = IDisputeGameFactory(vm.envAddress("DISPUTE_GAME_FACTORY")); config.anchorStateRegistry = IAnchorStateRegistry(vm.envAddress("ANCHOR_STATE_REGISTRY")); config.systemConfig = ISystemConfig(vm.envAddress("SYSTEM_CONFIG")); + config.proxyAdmin = IProxyAdmin(vm.envAddress("OP_CHAIN_PROXY_ADMIN")); + config.bondToken = IERC20(vm.envAddress("BOND_TOKEN")); + config.gameImplementation = IMultiProofGame(vm.envAddress("GAME_IMPLEMENTATION")); config.requireFreshAnchor = vm.envOr("REQUIRE_FRESH_ANCHOR", false); } function _validate(Config memory config, IMultiProofGame gameImpl) internal view { - require(config.guardianKey != 0, "ActivateProofSystem: guardian key required"); require( - vm.addr(config.guardianKey) == config.systemConfig.guardian(), "ActivateProofSystem: guardian key mismatch" + _governanceAddress(config.dgfOwnerKey) == config.disputeGameFactory.owner(), + "ActivateProofSystem: DGF owner key mismatch" ); + require( + config.disputeGameFactory.owner() == config.proxyAdmin.owner(), + "ActivateProofSystem: DGF and ProxyAdmin owners must match" + ); + if (config.anchorStateRegistry.respectedGameType().raw() != GameTypes.MULTI_PROOF_GAME_TYPE.raw()) { + require( + _governanceAddress(config.guardianKey) == config.systemConfig.guardian(), + "ActivateProofSystem: guardian key mismatch" + ); + } require(address(gameImpl).code.length > 0, "ActivateProofSystem: game implementation required"); require( gameImpl.gameType().raw() == GameTypes.MULTI_PROOF_GAME_TYPE.raw(), "ActivateProofSystem: wrong game type" @@ -75,16 +142,45 @@ contract ActivateProofSystem is Script { address(gameImpl.anchorStateRegistry()) == address(config.anchorStateRegistry), "ActivateProofSystem: game ASR mismatch" ); - require( - config.disputeGameFactory.initBonds(GameTypes.MULTI_PROOF_GAME_TYPE) == gameImpl.proposerBond(), - "ActivateProofSystem: init bond mismatch" - ); require( address(gameImpl.validityProofVerifier()).code.length > 0, "ActivateProofSystem: validity verifier missing" ); require(address(gameImpl.teeVerifier()).code.length > 0, "ActivateProofSystem: TEE verifier missing"); require(address(gameImpl.securityCouncil()).code.length > 0, "ActivateProofSystem: council verifier missing"); - require(address(gameImpl.weth()).code.length > 0, "ActivateProofSystem: DelayedWETH missing"); + require( + gameImpl.validityProofVerifier() != gameImpl.teeVerifier() + && gameImpl.validityProofVerifier() != gameImpl.securityCouncil() + && gameImpl.teeVerifier() != gameImpl.securityCouncil(), + "ActivateProofSystem: proof lane verifiers must be distinct" + ); + if (_safeMode()) { + require( + SecurityCouncilVerifier(address(gameImpl.securityCouncil())).council() == address(_governanceSafe()), + "ActivateProofSystem: council must be governance Safe" + ); + } + require(address(gameImpl.bondVault()).code.length > 0, "ActivateProofSystem: ERC-20 staking vault missing"); + require(gameImpl.proposerBond() > 0, "ActivateProofSystem: proposer bond missing"); + require(gameImpl.challengerBond() > 0, "ActivateProofSystem: challenger bond missing"); + require( + address(gameImpl.bondVault().disputeGameFactory()) == address(config.disputeGameFactory), + "ActivateProofSystem: vault factory mismatch" + ); + require( + address(gameImpl.bondVault().systemConfig()) == address(config.systemConfig), + "ActivateProofSystem: vault SystemConfig mismatch" + ); + require(gameImpl.bondVault().token() == config.bondToken, "ActivateProofSystem: vault token mismatch"); + require(address(config.bondToken).code.length > 0, "ActivateProofSystem: bond token missing"); + require( + gameImpl.bondVault().proxyAdmin() == config.proxyAdmin, "ActivateProofSystem: vault ProxyAdmin mismatch" + ); + + IERC20StakingVault currentBondVault = _currentBondVault(config.disputeGameFactory); + require( + address(currentBondVault) == address(0) || currentBondVault == gameImpl.bondVault(), + "ActivateProofSystem: must reuse current ERC-20 vault" + ); require(gameImpl.aggregationVKey() != bytes32(0), "ActivateProofSystem: aggregation vkey missing"); require(gameImpl.rangeVKeyCommitment() != bytes32(0), "ActivateProofSystem: range vkey missing"); require(gameImpl.teeImageId() != bytes32(0), "ActivateProofSystem: TEE image ID missing"); @@ -101,12 +197,19 @@ contract ActivateProofSystem is Script { config.anchorStateRegistry.isGameRespected(anchorGame), "ActivateProofSystem: anchor game was not respected" ); - require( - !config.anchorStateRegistry.isGameBlacklisted(anchorGame), - "ActivateProofSystem: anchor game blacklisted" - ); require(!config.anchorStateRegistry.isGameRetired(anchorGame), "ActivateProofSystem: anchor game retired"); require(anchorGame.status() != GameStatus.CHALLENGER_WINS, "ActivateProofSystem: anchor game invalid"); } } + + function _currentBondVault(IDisputeGameFactory factory) internal view returns (IERC20StakingVault bondVault) { + IDisputeGame currentImplementation = factory.gameImpls(GameTypes.MULTI_PROOF_GAME_TYPE); + if (address(currentImplementation) == address(0)) return IERC20StakingVault(address(0)); + + try IMultiProofGame(address(currentImplementation)).bondVault() returns (IERC20StakingVault currentBondVault) { + bondVault = currentBondVault; + } catch { + // The first ERC-20 bond migration may replace a legacy implementation without this getter. + } + } } diff --git a/pkg/contracts/scripts/devnet/DeployCouncilSafe.s.sol b/pkg/contracts/scripts/devnet/DeployCouncilSafe.s.sol index 7e4193df0..9f70f4556 100644 --- a/pkg/contracts/scripts/devnet/DeployCouncilSafe.s.sol +++ b/pkg/contracts/scripts/devnet/DeployCouncilSafe.s.sol @@ -1,16 +1,12 @@ // SPDX-License-Identifier: MIT pragma solidity 0.8.28; -import {Script} from "forge-std/Script.sol"; +import {Governance} from "./Governance.s.sol"; -import { - SecurityCouncilVerifier -} from "../../src/dispute/council/SecurityCouncilVerifier.sol"; +import {SecurityCouncilVerifier} from "../../src/dispute/council/SecurityCouncilVerifier.sol"; import {Safe} from "@safe-global/safe-contracts/contracts/Safe.sol"; -import { - SafeProxyFactory -} from "@safe-global/safe-contracts/contracts/proxies/SafeProxyFactory.sol"; +import {SafeProxyFactory} from "@safe-global/safe-contracts/contracts/proxies/SafeProxyFactory.sol"; import { CompatibilityFallbackHandler } from "@safe-global/safe-contracts/contracts/handler/CompatibilityFallbackHandler.sol"; @@ -31,7 +27,7 @@ import { /// through EIP-1271, which only exists on `CompatibilityFallbackHandler`. A Safe set up with /// a zero handler makes every council `verify` return false and silently disables the lane, /// so this script refuses to configure one. -contract DeployCouncilSafe is Script { +contract DeployCouncilSafe is Governance { struct Deployment { Safe councilSafe; SecurityCouncilVerifier verifier; @@ -44,51 +40,58 @@ contract DeployCouncilSafe is Script { function run() external returns (Deployment memory deployment) { uint256 privateKey = vm.envUint("PRIVATE_KEY"); - address[] memory owners = vm.envAddress("COUNCIL_OWNERS", ","); - uint256 threshold = vm.envUint("COUNCIL_THRESHOLD"); + address[] memory owners; + uint256 threshold; + if (_safeMode()) { + if (_safeAddress() != address(0)) { + owners = _governanceSafe().getOwners(); + } else { + // Retained for existing automated devnet callers; manual setup supplies a Safe. + (uint256 firstKey, uint256 secondKey) = _signerKeys(); + require( + firstKey != 0 && secondKey != 0 && firstKey != secondKey, "Governance: two distinct keys required" + ); + owners = new address[](2); + owners[0] = vm.addr(firstKey); + owners[1] = vm.addr(secondKey); + } + threshold = 2; + } else { + owners = vm.envAddress("COUNCIL_OWNERS", ","); + threshold = vm.envOr("COUNCIL_THRESHOLD", uint256(1)); + } + address existingSafe = _safeMode() ? _safeAddress() : address(0); + if (_safeMode() && existingSafe != address(0)) { + deployment.councilSafe = _governanceSafe(); + deployment.threshold = threshold; + vm.startBroadcast(privateKey); + deployment.verifier = new SecurityCouncilVerifier(existingSafe); + vm.stopBroadcast(); + _validateCouncil(deployment); + _writeDeployment(deployment, owners); + return deployment; + } // Bump to get a fresh Safe address for the same owner set (CREATE2 salt input). uint256 saltNonce = vm.envOr("COUNCIL_SAFE_SALT_NONCE", uint256(0)); - require( - owners.length > 0, - "DeployCouncilSafe: COUNCIL_OWNERS is empty" - ); - require( - threshold > 0, - "DeployCouncilSafe: COUNCIL_THRESHOLD must be non-zero" - ); - require( - threshold <= owners.length, - "DeployCouncilSafe: COUNCIL_THRESHOLD exceeds owner count" - ); + require(owners.length > 0, "DeployCouncilSafe: COUNCIL_OWNERS is empty"); + require(threshold > 0, "DeployCouncilSafe: COUNCIL_THRESHOLD must be non-zero"); + require(threshold <= owners.length, "DeployCouncilSafe: COUNCIL_THRESHOLD exceeds owner count"); address singleton = vm.envOr("SAFE_SINGLETON", address(0)); address factory = vm.envOr("SAFE_PROXY_FACTORY", address(0)); address handler = vm.envOr("SAFE_FALLBACK_HANDLER", address(0)); - bool reuse = singleton != address(0) || - factory != address(0) || - handler != address(0); + bool reuse = singleton != address(0) || factory != address(0) || handler != address(0); if (reuse) { // Partial reuse silently mixes a fresh singleton with a foreign factory; demand all // three or none so the resulting Safe's provenance is unambiguous. require( - singleton != address(0) && - factory != address(0) && - handler != address(0), + singleton != address(0) && factory != address(0) && handler != address(0), "DeployCouncilSafe: set SAFE_SINGLETON, SAFE_PROXY_FACTORY and SAFE_FALLBACK_HANDLER together" ); - require( - singleton.code.length > 0, - "DeployCouncilSafe: SAFE_SINGLETON has no code" - ); - require( - factory.code.length > 0, - "DeployCouncilSafe: SAFE_PROXY_FACTORY has no code" - ); - require( - handler.code.length > 0, - "DeployCouncilSafe: SAFE_FALLBACK_HANDLER has no code" - ); + require(singleton.code.length > 0, "DeployCouncilSafe: SAFE_SINGLETON has no code"); + require(factory.code.length > 0, "DeployCouncilSafe: SAFE_PROXY_FACTORY has no code"); + require(handler.code.length > 0, "DeployCouncilSafe: SAFE_FALLBACK_HANDLER has no code"); } vm.startBroadcast(privateKey); @@ -99,33 +102,12 @@ contract DeployCouncilSafe is Script { } bytes memory initializer = abi.encodeCall( - Safe.setup, - ( - owners, - threshold, - address(0), - "", - handler, - address(0), - 0, - payable(address(0)) - ) - ); - deployment.councilSafe = Safe( - payable( - address( - SafeProxyFactory(factory).createProxyWithNonce( - singleton, - initializer, - saltNonce - ) - ) - ) + Safe.setup, (owners, threshold, address(0), "", handler, address(0), 0, payable(address(0))) ); + deployment.councilSafe = + Safe(payable(address(SafeProxyFactory(factory).createProxyWithNonce(singleton, initializer, saltNonce)))); - deployment.verifier = new SecurityCouncilVerifier( - address(deployment.councilSafe) - ); + deployment.verifier = new SecurityCouncilVerifier(address(deployment.councilSafe)); vm.stopBroadcast(); deployment.singleton = singleton; @@ -134,51 +116,43 @@ contract DeployCouncilSafe is Script { deployment.threshold = threshold; deployment.saltNonce = saltNonce; + require(deployment.councilSafe.getThreshold() == threshold, "DeployCouncilSafe: threshold not set"); require( - deployment.councilSafe.getThreshold() == threshold, - "DeployCouncilSafe: threshold not set" - ); - require( - address(deployment.verifier.council()) == - address(deployment.councilSafe), + address(deployment.verifier.council()) == address(deployment.councilSafe), "DeployCouncilSafe: verifier not bound to the council Safe" ); + if (_safeMode()) { + _validateSafe(deployment.councilSafe); + } + _validateCouncil(deployment); _writeDeployment(deployment, owners); } - function _writeDeployment( - Deployment memory deployment, - address[] memory owners - ) internal { + function _validateCouncil(Deployment memory deployment) internal view { + bytes32 rootId = keccak256("devnet council configuration check"); + (bool success, bytes memory result) = address(deployment.councilSafe) + .staticcall( + abi.encodeWithSignature( + "getMessageHash(bytes)", abi.encode(deployment.verifier.attestationDigest(rootId)) + ) + ); + require(success && result.length == 32, "DeployCouncilSafe: compatibility handler required"); + } + + function _writeDeployment(Deployment memory deployment, address[] memory owners) internal { string memory out = vm.envOr("COUNCIL_DEPLOYMENT_OUT", string("")); if (bytes(out).length == 0) return; string memory root = "council"; - vm.serializeAddress( - root, - "securityCouncilVerifier", - address(deployment.verifier) - ); - vm.serializeAddress( - root, - "councilSafe", - address(deployment.councilSafe) - ); + vm.serializeAddress(root, "securityCouncilVerifier", address(deployment.verifier)); + vm.serializeAddress(root, "councilSafe", address(deployment.councilSafe)); vm.serializeAddress(root, "safeSingleton", deployment.singleton); vm.serializeAddress(root, "safeProxyFactory", deployment.proxyFactory); - vm.serializeAddress( - root, - "safeFallbackHandler", - deployment.fallbackHandler - ); + vm.serializeAddress(root, "safeFallbackHandler", deployment.fallbackHandler); vm.serializeAddress(root, "councilOwners", owners); vm.serializeUint(root, "safeSaltNonce", deployment.saltNonce); - string memory json = vm.serializeUint( - root, - "councilThreshold", - deployment.threshold - ); + string memory json = vm.serializeUint(root, "councilThreshold", deployment.threshold); vm.writeJson(json, out); } } diff --git a/pkg/contracts/scripts/devnet/DeployMockBondToken.s.sol b/pkg/contracts/scripts/devnet/DeployMockBondToken.s.sol new file mode 100644 index 000000000..1731219d6 --- /dev/null +++ b/pkg/contracts/scripts/devnet/DeployMockBondToken.s.sol @@ -0,0 +1,24 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.28; + +import {Script} from "forge-std/Script.sol"; + +import {MockBondToken} from "../../test/mocks/MockBondToken.sol"; + +/// @notice Deploys the mintable ERC-20 bond token used by a devnet with real proof verifiers. +/// @dev Devnet only. This is separate from DeployProofMocks so deployments do not create +/// accept-any verifier contracts when only a mock bond token is needed. +contract DeployMockBondToken is Script { + function run() external returns (MockBondToken bondToken) { + uint256 privateKey = vm.envUint("PRIVATE_KEY"); + vm.startBroadcast(privateKey); + bondToken = new MockBondToken(); + vm.stopBroadcast(); + + string memory out = vm.envOr("MOCK_BOND_TOKEN_DEPLOYMENT_OUT", string("")); + if (bytes(out).length != 0) { + string memory json = vm.serializeAddress("mockBondToken", "bondToken", address(bondToken)); + vm.writeJson(json, out); + } + } +} diff --git a/pkg/contracts/scripts/devnet/DeployNitro.s.sol b/pkg/contracts/scripts/devnet/DeployNitro.s.sol index 418d9021b..9d8e5083b 100644 --- a/pkg/contracts/scripts/devnet/DeployNitro.s.sol +++ b/pkg/contracts/scripts/devnet/DeployNitro.s.sol @@ -1,7 +1,7 @@ // SPDX-License-Identifier: MIT pragma solidity ^0.8.28; -import {Script} from "forge-std/Script.sol"; +import {Governance} from "./Governance.s.sol"; import {console} from "forge-std/console.sol"; import {CertManager} from "@nitro-validator/CertManager.sol"; import {ICertManager} from "@nitro-validator/ICertManager.sol"; @@ -41,15 +41,12 @@ import {NitroProofVerifier} from "../../src/dispute/nitro/NitroProofVerifier.sol /// for every approved EIF. The raw PCRs are the 48-byte SHA-384 hashes /// reported by `nitro-cli describe-eif`. /// -/// ## Operator pre-warm step (required before first registerKey) +/// ## Certificate prewarming before first registerKey /// `CertManager` caches verified certificates so the expensive X.509 + -/// P-384 chain check is paid only once per intermediate. Operators MUST -/// pre-warm by calling `verifyCACertWithHints(cert, parentCertHash, hints)` -/// for every intermediate in the AWS Nitro PKI (root → top-level -/// intermediate → … → leaf's immediate issuer) in separate transactions -/// before any user calls `NitroEnclaveKeyRegistry.registerKey`. -/// Use `lib/nitro-validator/tools/hinted_attestation_calls.js` to -/// generate the full call sequence with pre-computed hints. +/// P-384 chain check is paid only once per intermediate. The Nitro proof +/// worker handles this automatically at startup with `AUTO_REGISTER=true`, +/// before registering its enclave signer. Manual operators can instead use +/// `lib/nitro-validator/tools/hinted_attestation_calls.js` for the call sequence. /// /// ## Enclave image upgrade flow /// When a new enclave image (EIF) is built: @@ -67,9 +64,17 @@ import {NitroProofVerifier} from "../../src/dispute/nitro/NitroProofVerifier.sol /// `newPcr0` reject old-image signers. Optionally revoke the old PCR /// set to stop future old-image registrations. Revoke an individual /// signer only if its key may be compromised. -contract DeployNitro is Script { - function run() external { - address owner = vm.envAddress("OWNER"); +contract DeployNitro is Governance { + struct Deployment { + CertManager certManager; + NitroAttestationVerifier verifier; + NitroEnclaveKeyRegistry registry; + NitroProofVerifier proofVerifier; + } + + function run() external returns (Deployment memory deployment) { + address owner = _safeMode() ? address(_governanceSafe()) : vm.envAddress("OWNER"); + require(owner != address(0), "DeployNitro: owner required"); vm.startBroadcast(); @@ -77,7 +82,7 @@ contract DeployNitro is Script { P384Verifier p384Verifier = new P384Verifier(); console.log("P384Verifier:", address(p384Verifier)); - CertManager certManager = new CertManager(IP384Verifier(address(p384Verifier))); + CertManager certManager = new CertManager(IP384Verifier(address(p384Verifier)), owner, owner); console.log("CertManager:", address(certManager)); NitroAttestationVerifier verifier = new NitroAttestationVerifier( @@ -92,51 +97,17 @@ contract DeployNitro is Script { console.log("NitroProofVerifier:", address(proofVerifier)); vm.stopBroadcast(); + deployment = Deployment(certManager, verifier, registry, proofVerifier); _writeDeployment( - address(p384Verifier), - address(certManager), - address(verifier), - address(registry), - address(proofVerifier) + address(p384Verifier), address(certManager), address(verifier), address(registry), address(proofVerifier) ); - // ════════════════════════════════════════════════════════════════════ - // IMPORTANT: NEXT STEP — pre-warm CertManager *before* any user call - // ════════════════════════════════════════════════════════════════════ - // CertManager caches verified X.509 certs so the expensive chain check - // is paid once per intermediate, not once per attestation. Skipping - // the pre-warm means the FIRST `NitroEnclaveKeyRegistry.registerKey` - // call will attempt full chain validation inside a single tx and OOG. - // - // Use `lib/nitro-validator/tools/hinted_attestation_calls.js` to - // generate the full pre-warm + registration call sequence with hints. - // - // Owner script outline (run before opening up registerKey): - // - // bytes memory rootHints = ; - // bytes32 rootHash = certManager.verifyCACertWithHints(rootCertDer, 0, rootHints); - // bytes memory imHints = ; - // bytes32 imHash = certManager.verifyCACertWithHints(intermediateDer, rootHash, imHints); - // bytes memory issHints = ; - // bytes32 issHash = certManager.verifyCACertWithHints(issuerDer, imHash, issHints); - // // …repeat for every additional intermediate, parent-hash chained. - // - // Then approve at least one PCR set so verifyAttestation can succeed: - // - // verifier.approvePCRSet( - // keccak256(rawPcr0), keccak256(rawPcr1), keccak256(rawPcr2) - // ); - // - // (rawPcr* are the 48-byte SHA-384 values from `nitro-cli describe-eif`.) - // ════════════════════════════════════════════════════════════════════ console.log(""); - console.log("NEXT STEPS (owner) -- mandatory before any registerKey call:"); - console.log(" 1. certManager.verifyCACertWithHints(cert, parentHash, hints) for each cert"); - console.log(" in the AWS Nitro PKI chain (root -> intermediates -> issuer)."); - console.log(" Use tools/hinted_attestation_calls.js to generate calls + hints."); - console.log(" Without this, the first registerKey will OOG."); - console.log(" 2. verifier.approvePCRSet(pcr0, pcr1, pcr2) for each approved EIF."); + console.log("NEXT STEPS:"); + console.log(" 1. Owner: approvePCRSet(keccak256(rawPCR0), keccak256(rawPCR1), keccak256(rawPCR2))."); + console.log(" 2. Start the Nitro proof worker with AUTO_REGISTER=true."); + console.log(" It prewarms CertManager and registers the enclave signer automatically."); } /// @notice Writes deployed addresses to a JSON file if NITRO_DEPLOYMENT_OUT is set. @@ -157,6 +128,7 @@ contract DeployNitro is Script { } // Write each address to its own key, preserving any existing fields. + vm.writeJson(vm.toString(_safeMode() ? address(_governanceSafe()) : vm.envAddress("OWNER")), out, ".owner"); vm.writeJson(vm.toString(p384Verifier), out, ".p384Verifier"); vm.writeJson(vm.toString(certManager), out, ".certManager"); vm.writeJson(vm.toString(nitroAttestationVerifier), out, ".nitroAttestationVerifier"); diff --git a/pkg/contracts/scripts/devnet/DeployProofMocks.s.sol b/pkg/contracts/scripts/devnet/DeployProofMocks.s.sol index 7630f2b0b..dd6500894 100644 --- a/pkg/contracts/scripts/devnet/DeployProofMocks.s.sol +++ b/pkg/contracts/scripts/devnet/DeployProofMocks.s.sol @@ -4,10 +4,10 @@ pragma solidity 0.8.28; import {Script} from "forge-std/Script.sol"; import {MockRootIdVerifier} from "../../test/mocks/MockRootIdVerifier.sol"; +import {MockBondToken} from "../../test/mocks/MockBondToken.sol"; -/// @notice Deploys the proof-lane test doubles for a local devnet and writes their addresses, -/// for `DeployProofSystem.s.sol` to consume via `VALIDITY_PROOF_VERIFIER`, -/// `TEE_VERIFIER`, and `SECURITY_COUNCIL_VERIFIER`. +/// @notice Deploys proof-system test doubles for a local devnet and writes their addresses for +/// `DeployProofSystem.s.sol` to consume. /// /// Split out of `DeployProofSystem.s.sol` so that script cannot mint its own verifiers: a /// deployer that fabricates its verifiers can silently register a game type that accepts any @@ -20,6 +20,7 @@ contract DeployProofMocks is Script { MockRootIdVerifier validityVerifier; MockRootIdVerifier teeVerifier; MockRootIdVerifier councilVerifier; + MockBondToken bondToken; } function run() external returns (Deployment memory deployment) { @@ -30,6 +31,7 @@ contract DeployProofMocks is Script { deployment.validityVerifier = new MockRootIdVerifier(true); deployment.teeVerifier = new MockRootIdVerifier(true); deployment.councilVerifier = new MockRootIdVerifier(true); + deployment.bondToken = new MockBondToken(); vm.stopBroadcast(); _writeDeployment(deployment); @@ -42,7 +44,8 @@ contract DeployProofMocks is Script { string memory root = "mocks"; vm.serializeAddress(root, "validityProofVerifier", address(deployment.validityVerifier)); vm.serializeAddress(root, "teeVerifier", address(deployment.teeVerifier)); - string memory json = vm.serializeAddress(root, "securityCouncil", address(deployment.councilVerifier)); + vm.serializeAddress(root, "securityCouncil", address(deployment.councilVerifier)); + string memory json = vm.serializeAddress(root, "bondToken", address(deployment.bondToken)); vm.writeJson(json, out); } } diff --git a/pkg/contracts/scripts/devnet/DeployProofSystem.s.sol b/pkg/contracts/scripts/devnet/DeployProofSystem.s.sol index 07b188ba2..747f389a0 100644 --- a/pkg/contracts/scripts/devnet/DeployProofSystem.s.sol +++ b/pkg/contracts/scripts/devnet/DeployProofSystem.s.sol @@ -1,31 +1,33 @@ // SPDX-License-Identifier: MIT pragma solidity 0.8.28; -import {Script} from "forge-std/Script.sol"; +import {SecurityCouncilVerifier} from "../../src/dispute/council/SecurityCouncilVerifier.sol"; +import {Governance} from "./Governance.s.sol"; import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol"; import {GameTypes} from "../../src/dispute/lib/GameTypes.sol"; import {LibProof} from "../../src/dispute/lib/LibProof.sol"; import {MultiProofGame} from "../../src/dispute/MultiProofGame.sol"; +import {ERC20StakingVault} from "../../src/dispute/ERC20StakingVault.sol"; import {IMultiProofGame} from "../../src/dispute/interfaces/IMultiProofGame.sol"; +import {IERC20StakingVault} from "../../src/dispute/interfaces/IERC20StakingVault.sol"; import {IWorldChainProofVerifier} from "../../src/dispute/interfaces/IWorldChainProofVerifier.sol"; import {GameType} from "@optimism-bedrock/src/dispute/lib/Types.sol"; import {IDisputeGame} from "@optimism-bedrock/interfaces/dispute/IDisputeGame.sol"; import {IDisputeGameFactory} from "@optimism-bedrock/interfaces/dispute/IDisputeGameFactory.sol"; import {IAnchorStateRegistry} from "@optimism-bedrock/interfaces/dispute/IAnchorStateRegistry.sol"; -import {IDelayedWETH} from "@optimism-bedrock/interfaces/dispute/IDelayedWETH.sol"; import {IProxyAdmin} from "@optimism-bedrock/interfaces/universal/IProxyAdmin.sol"; import {ISystemConfig} from "@optimism-bedrock/interfaces/L1/ISystemConfig.sol"; +import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; -/// @notice Registers the World Chain proof-system game on the stock OP Stack dispute +/// @notice Deploys the World Chain proof-system game implementation for the stock OP Stack dispute /// infrastructure deployed by op-deployer. /// -/// Deploys a DelayedWETH proxy dedicated to the World Chain game type and the -/// `MultiProofGame` implementation, then registers that implementation on the existing -/// `DisputeGameFactory` (`setImplementation` + `setInitBond`). Activation is deliberately -/// separate: run `ActivateProofSystem.s.sol` after deployment records and offchain inputs are -/// ready. This script never changes the respected game type or retirement timestamp. +/// Deploys the WIP-1006 singleton ERC-20 staking-vault proxy, or reuses the existing vault during +/// a game rotation, then deploys the `MultiProofGame` implementation. Registration and activation +/// are deliberately separate: run `ActivateProofSystem.s.sol` after reviewing the deployment +/// record and offchain inputs. This script never changes the factory or respected game type. /// `setImplementation(WC_GAME_TYPE, address(0))` is the kill switch: it stops new game /// creation without touching in-flight games. /// When replacing type 1006, stop the proposer while implementation and bond registration are @@ -45,16 +47,16 @@ import {ISystemConfig} from "@optimism-bedrock/interfaces/L1/ISystemConfig.sol"; /// its output addresses in. That keeps the choice to run against mocks explicit and auditable /// at the call site instead of hidden inside this script. /// -/// Requires `just build-opstack` first: the 0.8.15 OP implementations (DelayedWETH, -/// Proxy, ProxyAdmin) deploy from the `opstack/out` artifacts via `deployCode`. -contract DeployProofSystem is Script { +/// Requires `just build-opstack` first: the 0.8.15 OP Proxy deploys from the +/// `opstack/out` artifacts via `deployCode`. +contract DeployProofSystem is Governance { using SafeCast for uint256; struct Deployment { IDisputeGameFactory disputeGameFactory; IAnchorStateRegistry anchorStateRegistry; - IProxyAdmin wethProxyAdmin; - IDelayedWETH weth; + IProxyAdmin vaultProxyAdmin; + IERC20StakingVault bondVault; MultiProofGame gameImpl; } @@ -79,16 +81,18 @@ contract DeployProofSystem is Script { IAnchorStateRegistry anchorStateRegistry; ISystemConfig systemConfig; IProxyAdmin proxyAdmin; - uint256 delayedWethDelay; + IERC20 bondToken; + IERC20StakingVault existingBondVault; + uint256 erc20WithdrawalDelay; uint256 proxyAdminOwnerKey; - uint256 dgfOwnerKey; } uint64 internal constant DEFAULT_CHALLENGE_PERIOD = 1 days; uint64 internal constant DEFAULT_PROOF_PERIOD = 7 days; uint256 internal constant DEFAULT_BLOCK_INTERVAL = 450; - uint256 internal constant DEFAULT_PROPOSER_BOND = 0.01 ether; - uint256 internal constant DEFAULT_CHALLENGER_BOND = 0.001 ether; + uint256 internal constant TOKEN_UNIT = 1e18; + uint256 internal constant DEFAULT_PROPOSER_BOND = TOKEN_UNIT / 100; + uint256 internal constant DEFAULT_CHALLENGER_BOND = DEFAULT_PROPOSER_BOND; uint8 internal constant DEFAULT_PROOF_THRESHOLD = 2; function run() external returns (Deployment memory deployment) { @@ -97,58 +101,50 @@ contract DeployProofSystem is Script { deployment.disputeGameFactory = config.disputeGameFactory; deployment.anchorStateRegistry = config.anchorStateRegistry; - // 1. DelayedWETH + game implementation, from the deployer key. Verifiers are - // pre-existing inputs validated in `_validateConfig`. - vm.startBroadcast(config.privateKey); - - // The dedicated DelayedWETH proxy is administered by the chain's existing ProxyAdmin. - deployment.wethProxyAdmin = config.proxyAdmin; - address wethImpl = - deployCode("opstack/out/DelayedWETH.sol/DelayedWETH.json", abi.encode(config.delayedWethDelay)); - deployment.weth = IDelayedWETH( - payable(deployCode("opstack/out/Proxy.sol/Proxy.json", abi.encode(address(config.proxyAdmin)))) - ); - vm.stopBroadcast(); + deployment.vaultProxyAdmin = config.proxyAdmin; + if (address(config.existingBondVault) == address(0)) { + vm.startBroadcast(config.privateKey); + ERC20StakingVault vaultImpl = new ERC20StakingVault(config.erc20WithdrawalDelay); + deployment.bondVault = IERC20StakingVault( + deployCode("opstack/out/Proxy.sol/Proxy.json", abi.encode(address(config.proxyAdmin))) + ); + vm.stopBroadcast(); - vm.startBroadcast(config.proxyAdminOwnerKey); - config.proxyAdmin - .upgradeAndCall( - payable(address(deployment.weth)), - wethImpl, - abi.encodeCall(IDelayedWETH.initialize, (config.systemConfig)) + _executeGovernance( + config.proxyAdminOwnerKey, + address(config.proxyAdmin), + abi.encodeCall( + IProxyAdmin.upgradeAndCall, + ( + payable(address(deployment.bondVault)), + address(vaultImpl), + abi.encodeCall( + IERC20StakingVault.initialize, + (config.bondToken, config.systemConfig, config.disputeGameFactory) + ) + ) + ) ); - vm.stopBroadcast(); + if (_preparingSafe()) { + // MultiProofGame reads the vault's initialized wiring in its constructor. + _writeDeployment(deployment, config); + return deployment; + } + } else { + deployment.bondVault = config.existingBondVault; + } + // Verifiers are pre-existing inputs validated in `_validateConfig`. vm.startBroadcast(config.privateKey); deployment.gameImpl = new MultiProofGame(_gameConfig(deployment, config)); vm.stopBroadcast(); - // 2. Register the game type on the existing DisputeGameFactory (factory owner). - // The three-argument overload explicitly clears any stale implementation args. - vm.startBroadcast(config.dgfOwnerKey); - config.disputeGameFactory - .setImplementation(GameTypes.MULTI_PROOF_GAME_TYPE, IDisputeGame(address(deployment.gameImpl)), hex""); - config.disputeGameFactory.setInitBond(GameTypes.MULTI_PROOF_GAME_TYPE, config.proposerBond); - vm.stopBroadcast(); - - require( - address(config.disputeGameFactory.gameImpls(GameTypes.MULTI_PROOF_GAME_TYPE)) - == address(deployment.gameImpl), - "DeployProofSystem: game implementation not registered" - ); - require( - config.disputeGameFactory.gameArgs(GameTypes.MULTI_PROOF_GAME_TYPE).length == 0, - "DeployProofSystem: stale game implementation args" - ); - require( - config.disputeGameFactory.initBonds(GameTypes.MULTI_PROOF_GAME_TYPE) == deployment.gameImpl.proposerBond(), - "DeployProofSystem: init bond does not match proposer bond" - ); + require(deployment.gameImpl.bondVault() == deployment.bondVault, "DeployProofSystem: vault wiring mismatch"); _writeDeployment(deployment, config); } - function _readConfig() internal view returns (Config memory config) { + function _readConfig() internal view virtual returns (Config memory config) { config.privateKey = vm.envUint("PRIVATE_KEY"); config.l2ChainId = vm.envUint("WORLD_CHAIN_L2_CHAIN_ID"); config.rollupConfigHash = vm.envBytes32("ROLLUP_CONFIG_HASH"); @@ -172,9 +168,10 @@ contract DeployProofSystem is Script { config.anchorStateRegistry = IAnchorStateRegistry(vm.envAddress("ANCHOR_STATE_REGISTRY")); config.systemConfig = ISystemConfig(vm.envAddress("SYSTEM_CONFIG")); config.proxyAdmin = IProxyAdmin(vm.envAddress("OP_CHAIN_PROXY_ADMIN")); - config.delayedWethDelay = vm.envOr("DELAYED_WETH_DELAY", uint256(300)); - config.proxyAdminOwnerKey = vm.envUint("OP_CHAIN_PROXY_ADMIN_OWNER_PRIVATE_KEY"); - config.dgfOwnerKey = vm.envUint("DGF_OWNER_KEY"); + config.bondToken = IERC20(vm.envAddress("BOND_TOKEN")); + config.existingBondVault = IERC20StakingVault(vm.envOr("ERC20_STAKING_VAULT", address(0))); + config.erc20WithdrawalDelay = vm.envOr("ERC20_WITHDRAWAL_DELAY", uint256(300)); + config.proxyAdminOwnerKey = vm.envOr("OP_CHAIN_PROXY_ADMIN_OWNER_PRIVATE_KEY", uint256(0)); } /// @dev A zero or codeless verifier would make the whole lane unverifiable, and @@ -189,6 +186,7 @@ contract DeployProofSystem is Script { _requireContract(address(config.validityProofVerifier), "VALIDITY_PROOF_VERIFIER"); _requireContract(address(config.teeVerifier), "TEE_VERIFIER"); _requireContract(address(config.securityCouncil), "SECURITY_COUNCIL_VERIFIER"); + _requireContract(address(config.bondToken), "BOND_TOKEN"); // The 2-of-3 threshold only means anything if the lanes are independent: pointing two // lanes at one verifier lets a single party satisfy both and resolve on its own. @@ -199,6 +197,12 @@ contract DeployProofSystem is Script { "DeployProofSystem: proof lane verifiers must be distinct" ); + if (_safeMode()) { + require( + SecurityCouncilVerifier(address(config.securityCouncil)).council() == address(_governanceSafe()), + "DeployProofSystem: council must be governance Safe" + ); + } require( address(config.anchorStateRegistry.disputeGameFactory()) == address(config.disputeGameFactory), "DeployProofSystem: ASR factory mismatch" @@ -208,16 +212,42 @@ contract DeployProofSystem is Script { "DeployProofSystem: ASR SystemConfig mismatch" ); require(config.systemConfig.l2ChainId() == config.l2ChainId, "DeployProofSystem: L2 chain ID mismatch"); - require(config.dgfOwnerKey != 0, "DeployProofSystem: DGF owner key required"); - require(config.proxyAdminOwnerKey != 0, "DeployProofSystem: ProxyAdmin owner key required"); - require( - vm.addr(config.dgfOwnerKey) == config.disputeGameFactory.owner(), - "DeployProofSystem: DGF owner key mismatch" - ); require( - vm.addr(config.proxyAdminOwnerKey) == config.proxyAdmin.owner(), - "DeployProofSystem: ProxyAdmin owner key mismatch" + config.disputeGameFactory.owner() == config.proxyAdmin.owner(), + "DeployProofSystem: DGF and ProxyAdmin owners must match" ); + IERC20StakingVault currentBondVault = _currentBondVault(config.disputeGameFactory); + if (address(currentBondVault) != address(0)) { + require( + address(config.existingBondVault) != address(0), "DeployProofSystem: existing ERC-20 vault required" + ); + require(config.existingBondVault == currentBondVault, "DeployProofSystem: must reuse current ERC-20 vault"); + } + if (address(config.existingBondVault) == address(0)) { + require( + _governanceAddress(config.proxyAdminOwnerKey) == config.proxyAdmin.owner(), + "DeployProofSystem: ProxyAdmin owner key mismatch" + ); + } else { + _requireContract(address(config.existingBondVault), "ERC20_STAKING_VAULT"); + require(config.existingBondVault.token() == config.bondToken, "DeployProofSystem: vault token mismatch"); + require( + config.existingBondVault.systemConfig() == config.systemConfig, + "DeployProofSystem: vault SystemConfig mismatch" + ); + require( + config.existingBondVault.disputeGameFactory() == config.disputeGameFactory, + "DeployProofSystem: vault factory mismatch" + ); + require( + config.existingBondVault.proxyAdmin() == config.proxyAdmin, + "DeployProofSystem: vault ProxyAdmin mismatch" + ); + require( + config.existingBondVault.delay() == config.erc20WithdrawalDelay, + "DeployProofSystem: vault withdrawal delay mismatch" + ); + } require(config.protocolFeeRecipient != address(0), "DeployProofSystem: protocol fee recipient required"); require(config.aggregationVKey != bytes32(0), "DeployProofSystem: aggregation vkey required"); require(config.rangeVKeyCommitment != bytes32(0), "DeployProofSystem: range vkey required"); @@ -229,6 +259,17 @@ contract DeployProofSystem is Script { require(config.challengerBond > 0, "DeployProofSystem: challenger bond required"); } + function _currentBondVault(IDisputeGameFactory factory) internal view returns (IERC20StakingVault bondVault) { + IDisputeGame currentImplementation = factory.gameImpls(GameTypes.MULTI_PROOF_GAME_TYPE); + if (address(currentImplementation) == address(0)) return IERC20StakingVault(address(0)); + + try IMultiProofGame(address(currentImplementation)).bondVault() returns (IERC20StakingVault currentBondVault) { + bondVault = currentBondVault; + } catch { + // The first ERC-20 bond migration may replace a legacy implementation without this getter. + } + } + function _gameConfig(Deployment memory deployment, Config memory config) internal pure @@ -250,7 +291,7 @@ contract DeployProofSystem is Script { teeVerifier: config.teeVerifier, securityCouncil: config.securityCouncil, anchorStateRegistry: config.anchorStateRegistry, - weth: deployment.weth + bondVault: deployment.bondVault }); } @@ -271,8 +312,9 @@ contract DeployProofSystem is Script { vm.serializeAddress(root, "securityCouncil", address(config.securityCouncil)); vm.serializeAddress(root, "protocolFeeRecipient", config.protocolFeeRecipient); vm.serializeAddress(root, "gameImplementation", address(deployment.gameImpl)); - vm.serializeAddress(root, "delayedWeth", address(deployment.weth)); - vm.serializeAddress(root, "delayedWethProxyAdmin", address(deployment.wethProxyAdmin)); + vm.serializeAddress(root, "bondToken", address(config.bondToken)); + vm.serializeAddress(root, "erc20StakingVault", address(deployment.bondVault)); + vm.serializeAddress(root, "erc20StakingVaultProxyAdmin", address(deployment.vaultProxyAdmin)); vm.serializeUint(root, "gameType", uint256(GameType.unwrap(GameTypes.MULTI_PROOF_GAME_TYPE))); vm.serializeBytes32(root, "rollupConfigHash", config.rollupConfigHash); vm.serializeBytes32(root, "aggregationVKey", config.aggregationVKey); @@ -285,7 +327,7 @@ contract DeployProofSystem is Script { vm.serializeUint(root, "proofPeriod", config.proofPeriod); vm.serializeUint(root, "proposerBond", config.proposerBond); vm.serializeUint(root, "challengerBond", config.challengerBond); - vm.serializeUint(root, "delayedWethDelay", config.delayedWethDelay); + vm.serializeUint(root, "erc20WithdrawalDelay", config.erc20WithdrawalDelay); vm.serializeUint(root, "retirementTimestampAtDeployment", config.anchorStateRegistry.retirementTimestamp()); vm.serializeAddress(root, "anchorGameAtDeployment", address(config.anchorStateRegistry.anchorGame())); string memory json = vm.serializeUint(root, "proofThreshold", config.proofThreshold); diff --git a/pkg/contracts/scripts/devnet/FundProofBondAccounts.s.sol b/pkg/contracts/scripts/devnet/FundProofBondAccounts.s.sol new file mode 100644 index 000000000..ea1ad2d21 --- /dev/null +++ b/pkg/contracts/scripts/devnet/FundProofBondAccounts.s.sol @@ -0,0 +1,72 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.28; + +import {Script} from "forge-std/Script.sol"; + +import {IERC20StakingVault} from "../../src/dispute/interfaces/IERC20StakingVault.sol"; +import {MockBondToken} from "../../test/mocks/MockBondToken.sol"; + +/// @notice Tops persistent devnet proof-system accounts up to configured reusable vault balances. +/// @dev Devnet only: this script relies on the unrestricted mint function exposed by `MockBondToken`. +/// Run it before bond-paying services start so balances remain stable during broadcasting. +contract FundProofBondAccounts is Script { + uint256 internal constant DEFAULT_VAULT_BALANCE_TARGET = 10_000e18; + + function run() external { + uint256 privateKey = vm.envUint("PRIVATE_KEY"); + address funder = vm.addr(privateKey); + IERC20StakingVault vault = IERC20StakingVault(vm.envAddress("ERC20_STAKING_VAULT")); + MockBondToken bondToken = MockBondToken(address(vault.token())); + address[] memory accounts = vm.envAddress("BOND_ACCOUNTS", ","); + uint256 target = vm.envOr("VAULT_BALANCE_TARGET", DEFAULT_VAULT_BALANCE_TARGET); + + _validate(accounts, target); + + vm.startBroadcast(privateKey); + _fundAccounts(bondToken, vault, funder, accounts, target); + vm.stopBroadcast(); + } + + function _fundAccounts( + MockBondToken bondToken, + IERC20StakingVault vault, + address funder, + address[] memory accounts, + uint256 target + ) internal { + for (uint256 i = 0; i < accounts.length; i++) { + bool duplicate; + for (uint256 j = 0; j < i; j++) { + if (accounts[j] == accounts[i]) { + duplicate = true; + break; + } + } + if (duplicate) continue; + _topUp(bondToken, vault, funder, accounts[i], target); + } + } + + function _validate(address[] memory accounts, uint256 target) internal pure { + require(accounts.length != 0, "FundProofBondAccounts: accounts missing"); + require(target != 0, "FundProofBondAccounts: target missing"); + for (uint256 i = 0; i < accounts.length; i++) { + require(accounts[i] != address(0), "FundProofBondAccounts: account missing"); + } + } + + function _topUp(MockBondToken bondToken, IERC20StakingVault vault, address funder, address account, uint256 target) + internal + { + uint256 available = vault.availableBalance(account); + if (available >= target) return; + + uint256 amount = target - available; + bondToken.mint(funder, amount); + bondToken.approve(address(vault), amount); + vault.deposit(account, amount); + + require(vault.availableBalance(account) >= target, "FundProofBondAccounts: top-up failed"); + require(bondToken.allowance(funder, address(vault)) == 0, "FundProofBondAccounts: allowance remains"); + } +} diff --git a/pkg/contracts/scripts/devnet/Governance.s.sol b/pkg/contracts/scripts/devnet/Governance.s.sol new file mode 100644 index 000000000..8d1f7ecb2 --- /dev/null +++ b/pkg/contracts/scripts/devnet/Governance.s.sol @@ -0,0 +1,171 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.28; + +import {Script} from "forge-std/Script.sol"; +import {Safe} from "@safe-global/safe-contracts/contracts/Safe.sol"; +import {Enum} from "@safe-global/safe-contracts/contracts/common/Enum.sol"; +import {console} from "forge-std/console.sol"; + +/// @notice Shared EOA / 2-of-2 Safe execution for devnet administration. +abstract contract Governance is Script { + function _safeMode() internal view virtual returns (bool) { + bytes32 mode = keccak256(bytes(vm.envOr("GOVERNANCE_MODE", string("eoa")))); + require(mode == keccak256("eoa") || mode == keccak256("safe"), "Governance: invalid mode"); + return mode == keccak256("safe"); + } + + function _governanceAddress(uint256 eoaKey) internal view returns (address) { + if (_safeMode()) return address(_governanceSafe()); + require(eoaKey != 0, "Governance: EOA key required"); + return vm.addr(eoaKey); + } + + function _governanceSafe() internal view returns (Safe account) { + account = Safe(payable(_safeAddress())); + _validateSafe(account); + } + + function _validateSafe(Safe account) internal view { + require(address(account).code.length > 0, "Governance: Safe has no code"); + require(account.getThreshold() == 2 && account.getOwners().length == 2, "Governance: expected 2-of-2 Safe"); + (address[] memory modules,) = account.getModulesPaginated(address(1), 1); + require(modules.length == 0, "Governance: modules bypass threshold"); + bytes memory message = abi.encode(keccak256("devnet council configuration check")); + bytes32 expected = keccak256( + abi.encodePacked( + hex"1901", + account.domainSeparator(), + keccak256(abi.encode(keccak256("SafeMessage(bytes message)"), keccak256(message))) + ) + ); + (bool success, bytes memory result) = + address(account).staticcall(abi.encodeWithSignature("getMessageHash(bytes)", message)); + require( + success && result.length == 32 && abi.decode(result, (bytes32)) == expected, + "Governance: compatibility handler required" + ); + } + + function _safeAddress() internal view virtual returns (address) { + return vm.envOr("GOVERNANCE_SAFE", address(0)); + } + + function _signerKeys() internal view virtual returns (uint256, uint256) { + return (vm.envUint("GOVERNANCE_SIGNER_1_PRIVATE_KEY"), vm.envUint("GOVERNANCE_SIGNER_2_PRIVATE_KEY")); + } + + function _relayerKey() internal view virtual returns (uint256) { + return vm.envUint("PRIVATE_KEY"); + } + + function _safeTxOut() internal view virtual returns (string memory) { + return vm.envOr("SAFE_TX_OUT", string("")); + } + + function _sign(uint256 key, bytes32 digest) internal pure returns (bytes memory) { + (uint8 v, bytes32 r, bytes32 s) = vm.sign(key, digest); + return abi.encodePacked(r, s, v); + } + + function _safeSignatures(bytes32 digest) internal view returns (bytes memory) { + (uint256 firstKey, uint256 secondKey) = _signerKeys(); + require(firstKey != 0 && secondKey != 0 && firstKey != secondKey, "Governance: two distinct keys required"); + Safe account = _governanceSafe(); + require( + account.isOwner(vm.addr(firstKey)) && account.isOwner(vm.addr(secondKey)), "Governance: signer mismatch" + ); + if (vm.addr(firstKey) > vm.addr(secondKey)) (firstKey, secondKey) = (secondKey, firstKey); + return bytes.concat(_sign(firstKey, digest), _sign(secondKey, digest)); + } + + function _preparingSafe() internal view returns (bool) { + return _safeMode() && bytes(_safeTxOut()).length != 0; + } + + string private preparedTransactions; + + function _prepareCall(address target, bytes memory data) internal { + _governanceSafe(); + if (bytes(preparedTransactions).length != 0) preparedTransactions = string.concat(preparedTransactions, ","); + preparedTransactions = string.concat( + preparedTransactions, + '{"to":"', + vm.toString(target), + '","value":"0","data":"', + vm.toString(data), + '","contractMethod":null,"contractInputsValues":null}' + ); + string memory out = _safeTxOut(); + vm.writeFile( + out, + string.concat( + '{"version":"1.0","chainId":"', + vm.toString(block.chainid), + '","createdAt":0,"meta":{"name":"Devnet governance","createdFromSafeAddress":"', + vm.toString(_safeAddress()), + '"},"transactions":[', + preparedTransactions, + "]}" + ) + ); + console.log("Safe approval required; import into Transaction Builder:", out); + } + + function _executeGovernance(uint256 eoaKey, address target, bytes memory data) internal { + require(target.code.length > 0, "Governance: target has no code"); + if (!_safeMode()) { + require(eoaKey != 0, "Governance: EOA key required"); + vm.startBroadcast(eoaKey); + (bool success, bytes memory result) = target.call(data); + vm.stopBroadcast(); + if (!success) { + assembly ("memory-safe") { revert(add(result, 32), mload(result)) } + } + return; + } + if (_preparingSafe()) { + _prepareCall(target, data); + return; + } + Safe account = _governanceSafe(); + bytes32 digest = account.getTransactionHash( + target, 0, data, Enum.Operation.Call, 0, 0, 0, address(0), address(0), account.nonce() + ); + bytes memory signatures = _safeSignatures(digest); + vm.startBroadcast(_relayerKey()); + bool safeSuccess = account.execTransaction( + target, 0, data, Enum.Operation.Call, 0, 0, 0, address(0), payable(address(0)), signatures + ); + vm.stopBroadcast(); + require(safeSuccess, "Governance: Safe execution failed"); + } +} + +/// @notice Execute one administrative call; PRIVATE_KEY pays gas in Safe mode. +contract ExecuteGovernance is Governance { + function run() external { + _executeGovernance( + vm.envOr("OWNER_KEY", uint256(0)), vm.envAddress("GOVERNANCE_TARGET"), vm.envBytes("GOVERNANCE_CALLDATA") + ); + } +} + +/// @notice Read-only check of the configured Safe and council binding. +contract CheckGovernance is Governance { + function run() external view { + require(_safeMode(), "Governance: expected Safe mode"); + Safe account = _governanceSafe(); + address verifier = vm.envAddress("SECURITY_COUNCIL_VERIFIER"); + (bool success, bytes memory result) = verifier.staticcall(abi.encodeWithSignature("council()")); + require( + success && result.length == 32 && abi.decode(result, (address)) == address(account), + "Governance: council mismatch" + ); + bytes32 rootId = keccak256("devnet council configuration check"); + (success, result) = verifier.staticcall(abi.encodeWithSignature("attestationDigest(bytes32)", rootId)); + require(success && result.length == 32, "Governance: council digest unavailable"); + (success, result) = address(account) + .staticcall(abi.encodeWithSignature("getMessageHash(bytes)", abi.encode(abi.decode(result, (bytes32))))); + require(success && result.length == 32, "Governance: compatibility handler required"); + } +} diff --git a/pkg/contracts/scripts/devnet/SubmitSecurityCouncilProof.s.sol b/pkg/contracts/scripts/devnet/SubmitSecurityCouncilProof.s.sol index 20de0bbc4..15306ddd1 100644 --- a/pkg/contracts/scripts/devnet/SubmitSecurityCouncilProof.s.sol +++ b/pkg/contracts/scripts/devnet/SubmitSecurityCouncilProof.s.sol @@ -1,7 +1,7 @@ // SPDX-License-Identifier: MIT pragma solidity 0.8.28; -import {Script} from "forge-std/Script.sol"; +import {Governance} from "./Governance.s.sol"; import {SecurityCouncilVerifier} from "../../src/dispute/council/SecurityCouncilVerifier.sol"; import {IMultiProofGame} from "../../src/dispute/interfaces/IMultiProofGame.sol"; @@ -14,25 +14,37 @@ interface ICouncilSafe { } /// @notice Testing-only helper that signs and submits the Security Council lane for one game. -/// @dev Supports only a 1-of-1 council Safe; production councils require signature aggregation. -contract SubmitSecurityCouncilProof is Script { +/// @dev EOA mode uses the existing 1-of-1 council; Safe mode uses the governance 2-of-2. +contract SubmitSecurityCouncilProof is Governance { + function _firstSignerKey() internal view returns (uint256 key) { + (key,) = _signerKeys(); + } + function run() external { IMultiProofGame game = IMultiProofGame(vm.envAddress("GAME_ADDRESS")); - uint256 signerKey = vm.envUint("COUNCIL_SIGNER_KEY"); + bytes memory suppliedProof = vm.envOr("COUNCIL_SIGNATURES", bytes("")); + uint256 signerKey = _safeMode() + ? (suppliedProof.length == 0 ? _firstSignerKey() : vm.envUint("PRIVATE_KEY")) + : vm.envUint("COUNCIL_SIGNER_KEY"); SecurityCouncilVerifier verifier = SecurityCouncilVerifier(address(game.securityCouncil())); ICouncilSafe council = ICouncilSafe(verifier.council()); address signer = vm.addr(signerKey); - require(council.getThreshold() == 1, "Council threshold is not 1"); - require(council.isOwner(signer), "Signer is not a council owner"); + if (_safeMode()) { + require(address(council) == address(_governanceSafe()), "Council is not the governance Safe"); + } else { + require(council.getThreshold() == 1, "Council threshold is not 1"); + require(council.isOwner(signer), "Signer is not a council owner"); + } bytes32 rootId = game.rootId(); bytes32 attestationDigest = verifier.attestationDigest(rootId); // The Safe handler expects abi.encode(attestationDigest) wrapped as a SafeMessage. bytes32 safeMessageHash = council.getMessageHash(abi.encode(attestationDigest)); - (uint8 v, bytes32 r, bytes32 s) = vm.sign(signerKey, safeMessageHash); - bytes memory proof = abi.encodePacked(r, s, v); + bytes memory proof = suppliedProof.length != 0 + ? suppliedProof + : (_safeMode() ? _safeSignatures(safeMessageHash) : _sign(signerKey, safeMessageHash)); require(verifier.verify(proof, bytes32(0), abi.encode(rootId)), "Council proof verification failed"); diff --git a/pkg/contracts/scripts/devnet/TransferNitroOwnership.s.sol b/pkg/contracts/scripts/devnet/TransferNitroOwnership.s.sol new file mode 100644 index 000000000..4c8f55593 --- /dev/null +++ b/pkg/contracts/scripts/devnet/TransferNitroOwnership.s.sol @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.28; + +import {Governance} from "./Governance.s.sol"; +import {CertManager} from "@nitro-validator/CertManager.sol"; +import {NitroAttestationVerifier} from "../../src/dispute/nitro/NitroAttestationVerifier.sol"; +import {NitroEnclaveKeyRegistry} from "../../src/dispute/nitro/NitroEnclaveKeyRegistry.sol"; + +/// @notice Explicit handoff of a reused Nitro stack; GOVERNANCE_MODE describes its current owner. +contract TransferNitroOwnership is Governance { + struct Config { + address newOwner; + uint256 ownerKey; + CertManager certManager; + NitroAttestationVerifier verifier; + NitroEnclaveKeyRegistry registry; + } + + function _readConfig() internal view virtual returns (Config memory) { + return Config( + vm.envAddress("NEW_NITRO_OWNER"), + vm.envOr("OWNER_KEY", uint256(0)), + CertManager(vm.envAddress("CERT_MANAGER_ADDRESS")), + NitroAttestationVerifier(vm.envAddress("NITRO_ATTESTATION_VERIFIER")), + NitroEnclaveKeyRegistry(vm.envAddress("NITRO_ENCLAVE_KEY_REGISTRY")) + ); + } + + function run() external { + Config memory config = _readConfig(); + address newOwner = config.newOwner; + require(newOwner != address(0), "Nitro handoff: new owner required"); + uint256 ownerKey = config.ownerKey; + address currentOwner = _governanceAddress(ownerKey); + CertManager certManager = config.certManager; + NitroAttestationVerifier verifier = config.verifier; + NitroEnclaveKeyRegistry registry = config.registry; + require( + certManager.owner() == currentOwner || certManager.owner() == newOwner, + "Nitro handoff: CertManager owner mismatch" + ); + require( + verifier.owner() == currentOwner || verifier.owner() == newOwner, "Nitro handoff: verifier owner mismatch" + ); + require( + registry.owner() == currentOwner || registry.owner() == newOwner, "Nitro handoff: registry owner mismatch" + ); + require(address(registry.verifier()) == address(verifier), "Nitro handoff: verifier wiring mismatch"); + require(address(verifier.certManager()) == address(certManager), "Nitro handoff: CertManager wiring mismatch"); + // Revoker is independent; require the current governance authority before moving it. + require( + certManager.revoker() == currentOwner || certManager.revoker() == newOwner, + "Nitro handoff: revoker mismatch" + ); + if (certManager.owner() != newOwner) { + _executeGovernance(ownerKey, address(certManager), abi.encodeCall(CertManager.setRevoker, (newOwner))); + _executeGovernance( + ownerKey, address(certManager), abi.encodeCall(CertManager.transferOwnership, (newOwner)) + ); + } + if (verifier.owner() != newOwner) { + _executeGovernance( + ownerKey, address(verifier), abi.encodeWithSignature("transferOwnership(address)", newOwner) + ); + } + if (registry.owner() != newOwner) { + _executeGovernance( + ownerKey, address(registry), abi.encodeWithSignature("transferOwnership(address)", newOwner) + ); + } + if (_preparingSafe()) return; + require( + certManager.owner() == newOwner && certManager.revoker() == newOwner, + "Nitro handoff: CertManager handoff failed" + ); + require(verifier.owner() == newOwner && registry.owner() == newOwner, "Nitro handoff: handoff failed"); + } +} diff --git a/pkg/contracts/scripts/devnet/deploy_anvil.sh b/pkg/contracts/scripts/devnet/deploy_anvil.sh index 99adbd722..414189b11 100755 --- a/pkg/contracts/scripts/devnet/deploy_anvil.sh +++ b/pkg/contracts/scripts/devnet/deploy_anvil.sh @@ -20,10 +20,10 @@ export SAFE_OWNER_4=0x47e179ec197488593b187f80a00eb0da91f1b9d0b13f8733639f19c30a export SAFE_OWNER_5=0x8b3a350cf5c34c9194ca85829a2df0ec3153be0318b5e2d3348e872092edffba # m/44'/60'/0'/0/5 # Deploy contracts -forge script scripts/devnet/DeployDevnet.s.sol:DeployDevnet --rpc-url http://127.0.0.1:8545 --broadcast +forge script scripts/devnet/DeployDevnet.s.sol:DeployDevnet --rpc-url http://127.0.0.1:8545 --broadcast --skip-simulation # Deploy Fee Vaults -forge script scripts/devnet/DeployFeeVaults.s.sol:DeployFeeVaults --rpc-url http://127.0.0.1:8545 --broadcast +forge script scripts/devnet/DeployFeeVaults.s.sol:DeployFeeVaults --rpc-url http://127.0.0.1:8545 --broadcast --skip-simulation # Wait for anvil to finish wait $ANVIL_PID \ No newline at end of file diff --git a/pkg/contracts/scripts/devnet/deploy_kurtosis.sh b/pkg/contracts/scripts/devnet/deploy_kurtosis.sh index f6db7b8b9..c86911fd7 100755 --- a/pkg/contracts/scripts/devnet/deploy_kurtosis.sh +++ b/pkg/contracts/scripts/devnet/deploy_kurtosis.sh @@ -26,5 +26,5 @@ cast send --rpc-url $BUILDER_SOCKET \ --private-key $PRIVATE_KEY \ --timeout 120 \ --create 0x60a060405262093a806000556040516100179061015e565b604051809103906000f080158015610033573d6000803e3d6000fd5b50600380546001600160a01b03929092166001600160a01b03199092169190911790556004805460ff60a01b1916600160a01b17905534801561007557600080fd5b5060405162002a0938038062002a098339810160408190526100969161016c565b806100aa816100e560201b6106481760201c565b6100d057604051630220cee360e61b815260ff8216600482015260240160405180910390fd5b60ff166080526100df3361010c565b50610196565b60006010602060ff8416821180159061010457508060ff168460ff1611155b949350505050565b600480546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a35050565b611ade8062000f2b83390190565b60006020828403121561017e57600080fd5b815160ff8116811461018f57600080fd5b9392505050565b608051610d79620001b2600039600061016a0152610d796000f3fe608060405234801561001057600080fd5b50600436106100df5760003560e01c8063b242e5341161008c578063d7b0fef111610066578063d7b0fef1146101df578063f1c621ee146101e7578063f2fde38b1461023a578063fbde929b1461024d57600080fd5b8063b242e534146101a6578063b354b37a146101b9578063c70aa727146101cc57600080fd5b80638da5cb5b116100bd5780638da5cb5b1461013b5780638e5cdd5014610163578063b0d690791461019457600080fd5b80630ee04629146100e4578063354ca1201461011e578063715018a614610133575b600080fd5b6004546101099074010000000000000000000000000000000000000000900460ff1681565b60405190151581526020015b60405180910390f35b61013161012c366004610b9c565b610260565b005b610131610317565b60045460405173ffffffffffffffffffffffffffffffffffffffff9091168152602001610115565b60405160ff7f0000000000000000000000000000000000000000000000000000000000000000168152602001610115565b6000545b604051908152602001610115565b6101316101b4366004610c11565b61032b565b6101316101c7366004610c4f565b6104aa565b6101316101da366004610c69565b61052a565b61019861053e565b6102196101f5366004610c69565b6002602052600090815260409020546fffffffffffffffffffffffffffffffff1681565b6040516fffffffffffffffffffffffffffffffff9091168152602001610115565b610131610248366004610c82565b610583565b61013161025b366004610c69565b610637565b6102698561066f565b60035460408051608081018252878152602081018690528082018790526060810185905290517f2357251100000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff909216916323572511916102e091859190600401610ccf565b60006040518083038186803b1580156102f857600080fd5b505afa15801561030c573d6000803e3d6000fd5b505050505050505050565b61031f610731565b6103296000610a02565b565b610333610731565b73ffffffffffffffffffffffffffffffffffffffff82166103db576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152603260248201527f43726f7373446f6d61696e4f776e61626c65333a206e6577206f776e6572206960448201527f7320746865207a65726f2061646472657373000000000000000000000000000060648201526084015b60405180910390fd5b60006103fc60045473ffffffffffffffffffffffffffffffffffffffff1690565b905061040783610a02565b6004805483151574010000000000000000000000000000000000000000027fffffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffff90911617905560405173ffffffffffffffffffffffffffffffffffffffff80851691908316907f7fdc2a4b6eb39ec3363d710d188620bd1e97b3c434161f187b4d0dc0544faa589061049d90861515815260200190565b60405180910390a3505050565b6104b38561066f565b60035460408051608081018252878152602081018690528082018790526060810185905290517ff2457c8d00000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff9092169163f2457c8d916102e091859190600401610cf5565b610532610731565b61053b81610a79565b50565b600060015460000361057c576040517f5b8dabb700000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b5060015490565b61058b610731565b73ffffffffffffffffffffffffffffffffffffffff811661062e576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602660248201527f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206160448201527f646472657373000000000000000000000000000000000000000000000000000060648201526084016103d2565b61053b81610a02565b61063f610731565b61053b81610ab4565b60006010602060ff8416821180159061066757508060ff168460ff1611155b949350505050565b600154810361067b5750565b6000818152600260205260408120546fffffffffffffffffffffffffffffffff16908190036106d6576040517fddae3b7100000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6000546106f56fffffffffffffffffffffffffffffffff831642610d11565b111561072d576040517f3ae7359e00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b5050565b60045474010000000000000000000000000000000000000000900460ff1615610817573361077460045473ffffffffffffffffffffffffffffffffffffffff1690565b73ffffffffffffffffffffffffffffffffffffffff1614610329576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602c60248201527f43726f7373446f6d61696e4f776e61626c65333a2063616c6c6572206973206e60448201527f6f7420746865206f776e6572000000000000000000000000000000000000000060648201526084016103d2565b7342000000000000000000000000000000000000073381146108bb576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152603060248201527f43726f7373446f6d61696e4f776e61626c65333a2063616c6c6572206973206e60448201527f6f7420746865206d657373656e6765720000000000000000000000000000000060648201526084016103d2565b8073ffffffffffffffffffffffffffffffffffffffff16636e296e456040518163ffffffff1660e01b8152600401602060405180830381865afa158015610906573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061092a9190610d4f565b73ffffffffffffffffffffffffffffffffffffffff1661095f60045473ffffffffffffffffffffffffffffffffffffffff1690565b73ffffffffffffffffffffffffffffffffffffffff161461053b576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602c60248201527f43726f7373446f6d61696e4f776e61626c65333a2063616c6c6572206973206e60448201527f6f7420746865206f776e6572000000000000000000000000000000000000000060648201526084016103d2565b6004805473ffffffffffffffffffffffffffffffffffffffff8381167fffffffffffffffffffffffff0000000000000000000000000000000000000000831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a35050565b60008190556040518181527f147b815b6a3a8dd5d49310410e089f6b5e9f3782e944772edc938c8bb48ef1219060200160405180910390a150565b6000818152600260205260409020546fffffffffffffffffffffffffffffffff168015610b0d576040517f6650c4d100000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600182905560008281526002602090815260409182902080547fffffffffffffffffffffffffffffffff0000000000000000000000000000000016426fffffffffffffffffffffffffffffffff8116918217909255835186815292830152917fe97c89cbb137505b36f55ebfc9732fd6c4c73ff43d49db239fc25f6e7a534145910160405180910390a1505050565b6000806000806000610180808789031215610bb657600080fd5b86359550602087013594506040870135935060608701359250878188011115610bde57600080fd5b506080860190509295509295909350565b73ffffffffffffffffffffffffffffffffffffffff8116811461053b57600080fd5b60008060408385031215610c2457600080fd5b8235610c2f81610bef565b915060208301358015158114610c4457600080fd5b809150509250929050565b6000806000806000610100808789031215610bb657600080fd5b600060208284031215610c7b57600080fd5b5035919050565b600060208284031215610c9457600080fd5b8135610c9f81610bef565b9392505050565b8060005b6004811015610cc9578151845260209384019390910190600101610caa565b50505050565b6101808101610100808584376000908301908152610ced8185610ca6565b509392505050565b610100810160808483376080820160008152610ced8185610ca6565b600082821015610d4a577f4e487b7100000000000000000000000000000000000000000000000000000000600052601160045260246000fd5b500390565b600060208284031215610d6157600080fd5b8151610c9f81610bef56fea164736f6c634300080f000a608060405234801561001057600080fd5b50611abe806100206000396000f3fe608060405234801561001057600080fd5b50600436106100415760003560e01c8063235725111461004657806344f636921461005b578063f2457c8d14610084575b600080fd5b61005961005436600461198b565b610097565b005b61006e6100693660046119c2565b61032f565b60405161007b91906119e6565b60405180910390f35b610059610092366004611a17565b61038c565b6000806100a3836106c2565b9150915060006040516101008682377f168e4fddac50a40d5bcff39c7fa9207cd368444c0c01a86690a6645b52f3aa1f6101008201527f2139a256456825daa623957c4f2ea1a0d26f135769e450759142a7159b0a44766101208201527f07859424108de88bfbe5c80a19c0e80ba35fda4383d3fd125305dd04b4c08fe46101408201527f142ad7a93ca0c554a9f0303059e5a24e85400004a730598bd423b0090f4b3d4a6101608201527f2d4d9aa7e302d9df41749d5507949d05dbea33fbb16c643b22f599a2be6df2e26101808201527f14bedd503c37ceb061d8ec60209fe345ce89830a19230301f076caff004d19266101a08201527f0967032fcbf776d1afc985f88877f182d38480a653f2decaa9794cbc3bf3060c6101c08201527f0e187847ad4c798374d0d6732bf501847dd68bc0e071241e0213bc7fc13db7ab6101e08201527e1752a100a72fdf1e5a5d6ea841cc20ec838bccfcf7bd559e79f1c9c759b6a06102008201527f192a8cc13cd9f762871f21e43451c6ca9eeab2cb2987c4e366a185c25dac2e7f61022082015283610240820152826102608201527f198e9393920d483a7260bfb731fb5d25f1aa493335a9e71297e485b7aef312c26102808201527f1800deef121f1e76426a00665e5c4479674322d4f75edadd46debd5cd992f6ed6102a08201527f275dc4a288d1afb3cbb1ac09187524c7db36395df7be3b99e673b13a075a65ec6102c08201527f1d9befcd05a5323e6da4d435f3b617cdb3af83285c2df711ef39c01571827f9d6102e08201526020816103008360085afa905116905080610328576040517f7fcdd1f400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b5050505050565b61033761190d565b61034a82358360015b60200201356109c8565b81526103686060830135604084013560a08501356080860135610b67565b6020830152604082015261038260c0830135836007610340565b6060820152919050565b60008061039f84825b6020020135611041565b909250905060008080806103bb604089013560208a0135611165565b929650909450925090506000806103d38a6003610395565b915091506000806103e38b6106c2565b915091506103ef61192b565b8a8152602081018a905260408101889052606081018990526080810186905260a0810187905260c0810185905260e081018490527f168e4fddac50a40d5bcff39c7fa9207cd368444c0c01a86690a6645b52f3aa1f6101008201527f2139a256456825daa623957c4f2ea1a0d26f135769e450759142a7159b0a44766101208201527f07859424108de88bfbe5c80a19c0e80ba35fda4383d3fd125305dd04b4c08fe46101408201527f142ad7a93ca0c554a9f0303059e5a24e85400004a730598bd423b0090f4b3d4a6101608201527f2d4d9aa7e302d9df41749d5507949d05dbea33fbb16c643b22f599a2be6df2e26101808201527f14bedd503c37ceb061d8ec60209fe345ce89830a19230301f076caff004d19266101a08201527f0967032fcbf776d1afc985f88877f182d38480a653f2decaa9794cbc3bf3060c6101c08201527f0e187847ad4c798374d0d6732bf501847dd68bc0e071241e0213bc7fc13db7ab6101e08201527e1752a100a72fdf1e5a5d6ea841cc20ec838bccfcf7bd559e79f1c9c759b6a06102008201527f192a8cc13cd9f762871f21e43451c6ca9eeab2cb2987c4e366a185c25dac2e7f610220820152610240810183905261026081018290527f198e9393920d483a7260bfb731fb5d25f1aa493335a9e71297e485b7aef312c26102808201527f1800deef121f1e76426a00665e5c4479674322d4f75edadd46debd5cd992f6ed6102a08201527f275dc4a288d1afb3cbb1ac09187524c7db36395df7be3b99e673b13a075a65ec6102c08201527f1d9befcd05a5323e6da4d435f3b617cdb3af83285c2df711ef39c01571827f9d6102e0820152600061065e61194a565b6020816103008560085afa915081158061067a57508051600114155b156106b1576040517f7fcdd1f400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b505050505050505050505050505050565b6000806000600190506040516040810160007f0335f514c2acb9b255aae85514122267cd7d16e374c6231a2c34417d3449125483527f07fa1580c1cc3ed4f6d660c6f60f86afedd8a12fb90b2e8ed4f7e310c88b97f760208401527f20b781dd0db3b7980a4b3814128c86e597e1442d0fc9eb7f932a5229494d6b7982527f17d1cef436eb2f665670c7b34854e62c227043a7b111a539c0295518bbab3ca96020830152863590508060408301527f30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f000000181108416935060408260608460075afa8416935060408360808560065afa841693507f260945445b4205f874ab7e203a18240e51c9d3c896ea300d40132b1c2f50299a82527f11087a8b76b0f957e1c482c909302916795f811a06866059e403689c01c903fb6020830152602087013590508060408301527f30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f000000181108416935060408260608460075afa8416935060408360808560065afa841693507f11d20fd81c0e5cf48ba1469ccb8ac99dcdc7cf746a6e70762a939d63dcc52dbf82527f2d447c5f134eff527d7bcaace88b3842c42b800d8dc049e0a6e72f5efc14293d6020830152604087013590508060408301527f30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f000000181108416935060408260608460075afa8416935060408360808560065afa841693507f107cd54a1606a6a873bed4c1b76af48975e66dcf6c127b4c799ad4fdd230b87c82527f1a51b81f6c07725ebcc56ebb1c482b99340eaa9bcb86cc09aed6f58a28e530b66020830152606087013590508060408301527f30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f00000018110841693505060408160608360075afa831692505060408160808360065afa815160209092015191945090925016806109c2576040517fa54f8e2700000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b50915091565b60007f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd4783101580610a1957507f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd478210155b15610a50576040517f7fcdd1f400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b82158015610a5c575081155b15610a6957506000610b61565b6000610ade7f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd4760037f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47877f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47898a0909086114b0565b9050808303610af3575050600182901b610b61565b7f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd478082068103068303610b2d575050600182811b17610b61565b6040517f7fcdd1f400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b505b92915050565b6000807f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd4786101580610bb957507f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd478510155b80610be457507f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd478410155b80610c0f57507f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd478310155b15610c46576040517f7fcdd1f400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b82848688171717600003610c5f57506000905080611038565b600080807f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47610caf60037f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47611a73565b7f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd478a8c0909905060007f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd478a7f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd478c8d0909905060007f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd478a7f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd478c8d090990507f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47807f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd478c860984087f2b149d40ceb8aaae81be18991be06ac3b5b4c5e559dbefa33267e6dc24a138e5089450610e707f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47807f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd478e870984087f2fcd3ac2a640a154eb23960892a85a68f031ca0c8344b23a577dcf1052b9e775087f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd479081900681030690565b9350505050600080610ef77f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd4780610ea957610ea9611a44565b7f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd478586097f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47878809086114b0565b9050610f687f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd477f183227397098d014dc2822db40c0ac2ecbc0b548b438e5469e10460b6c3e7ea47f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd478488080961153f565b15915050610f7783838361159b565b90935091508683148015610f8a57508186145b15610fb45780610f9b576000610f9e565b60025b60ff1660028a901b176000179450879350611034565b7f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd478084068103068714801561100e57507f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd4780830681030686145b15610b2d578061101f576000611022565b60025b60ff1660028a901b1760011794508793505b5050505b94509492505050565b6000808260000361105757506000928392509050565b600183811c9250808416147f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd4783106110bb576040517f7fcdd1f400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b61112e7f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd4760037f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47867f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd4788890909086114b0565b915080156109c2577f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47808306810306915050915091565b600080808085158015611176575084155b1561118c575060009250829150819050806114a7565b600286811c945085935060018088161490808816147f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47861015806111f057507f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd478510155b15611227576040517f7fcdd1f400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60007f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd4761127560037f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47611a73565b7f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47888a0909905060007f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47887f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd478a8b0909905060007f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47887f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd478a8b090990507f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47807f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd478a860984087f2b149d40ceb8aaae81be18991be06ac3b5b4c5e559dbefa33267e6dc24a138e50896506114367f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47807f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd478c870984087f2fcd3ac2a640a154eb23960892a85a68f031ca0c8344b23a577dcf1052b9e775087f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd479081900681030690565b955061144387878661159b565b909750955084156114a1577f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd4780880681030696507f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd4780870681030695505b50505050505b92959194509250565b60006114dc827f0c19139cb84c680a6e14116da060561765e05aa45a1c72a34f082305b61f3f526117f2565b9050817f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd478283091461153a576040517f7fcdd1f400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b919050565b60008061156c837f0c19139cb84c680a6e14116da060561765e05aa45a1c72a34f082305b61f3f526117f2565b9050827f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47828309149392505050565b600080806115f17f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47808788097f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47898a09086114b0565b90508315611622577f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47908190068103065b6116917f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd477f183227397098d014dc2822db40c0ac2ecbc0b548b438e5469e10460b6c3e7ea47f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47848a08096114b0565b92507f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd476116e17f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd4760028609611882565b860991507f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd476117587f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd478485097f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd479081900681030690565b7f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd4785860908861415806117b257507f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47808385096002098514155b156117e9576040517f7fcdd1f400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b50935093915050565b60008060405160208152602080820152602060408201528460608201528360808201527f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd4760a082015260208160c08360055afa90519250905080610b5f576040517f7fcdd1f400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60006118ae827f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd456117f2565b90507f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd4781830960011461153a576040517f7fcdd1f400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60405180608001604052806004906020820280368337509192915050565b6040518061030001604052806018906020820280368337509192915050565b60405180602001604052806001906020820280368337509192915050565b806101008101831015610b6157600080fd5b8060808101831015610b6157600080fd5b600080610180838503121561199f57600080fd5b6119a98484611968565b91506119b984610100850161197a565b90509250929050565b600061010082840312156119d557600080fd5b6119df8383611968565b9392505050565b60808101818360005b6004811015611a0e5781518352602092830192909101906001016119ef565b50505092915050565b6000806101008385031215611a2b57600080fd5b611a35848461197a565b91506119b9846080850161197a565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601260045260246000fd5b600082821015611aac577f4e487b7100000000000000000000000000000000000000000000000000000000600052601160045260246000fd5b50039056fea164736f6c634300080f000a000000000000000000000000000000000000000000000000000000000000001e "constructor(uint8 _treeDepth)" 30 -forge script scripts/devnet/DeployDevnet.s.sol:DeployDevnet --rpc-url $BUILDER_SOCKET --chain $CHAIN_ID --timeout 120 --slow --broadcast -forge script scripts/devnet/DeployFeeVaults.s.sol:DeployFeeVaults --rpc-url $BUILDER_SOCKET --chain $CHAIN_ID --timeout 120 --slow --broadcast >/dev/null 2>&1 || true +forge script scripts/devnet/DeployDevnet.s.sol:DeployDevnet --rpc-url $BUILDER_SOCKET --chain $CHAIN_ID --timeout 120 --slow --broadcast --skip-simulation +forge script scripts/devnet/DeployFeeVaults.s.sol:DeployFeeVaults --rpc-url $BUILDER_SOCKET --chain $CHAIN_ID --timeout 120 --slow --broadcast --skip-simulation >/dev/null 2>&1 || true diff --git a/pkg/contracts/src/dispute/ERC20StakingVault.sol b/pkg/contracts/src/dispute/ERC20StakingVault.sol new file mode 100644 index 000000000..35e593e56 --- /dev/null +++ b/pkg/contracts/src/dispute/ERC20StakingVault.sol @@ -0,0 +1,260 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.28; + +import {GameTypes} from "./lib/GameTypes.sol"; +import { + ChallengerBondAlreadyLocked, + ExactTransferRequired, + GameAlreadySettled, + GameBondAlreadyInitialized, + GameNotRegistered, + InsufficientBalance, + InvalidAccount, + InvalidAmount, + InvalidPayoutTotal, + InvalidVaultConfiguration, + InvalidWithdrawal, + NotProxyAdminOwner, + OwnerMismatch, + UnexpectedGameAddress, + WithdrawalDelayNotMet, + WithdrawalPaused +} from "./lib/Errors.sol"; +import {IMultiProofGame} from "./interfaces/IMultiProofGame.sol"; +import {IERC20StakingVault} from "./interfaces/IERC20StakingVault.sol"; + +import {Claim, GameType, Hash} from "@optimism-bedrock/src/dispute/lib/Types.sol"; +import {IDisputeGame} from "@optimism-bedrock/interfaces/dispute/IDisputeGame.sol"; +import {IDisputeGameFactory} from "@optimism-bedrock/interfaces/dispute/IDisputeGameFactory.sol"; +import {ISystemConfig} from "@optimism-bedrock/interfaces/L1/ISystemConfig.sol"; +import {IProxyAdmin} from "@optimism-bedrock/interfaces/universal/IProxyAdmin.sol"; +import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol"; +import {ERC1967Utils} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol"; +import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; +import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; +import {LibClone} from "@solady/utils/LibClone.sol"; + +/// @custom:proxied true +/// @title ERC20StakingVault +/// @author World Contributors +/// @notice A one-to-one ERC-20 ledger for WIP-1006 proposal and challenge bonds. +/// @custom:security-contact security@toolsforhumanity.com +contract ERC20StakingVault is Initializable, IERC20StakingVault { + using SafeERC20 for IERC20; + + /// @notice Semantic version. + string public constant version = "1.0.0"; + + /// @notice Delay required between requesting and executing an ERC-20 withdrawal. + uint256 internal immutable DELAY_SECONDS; + + /// @notice Canonical ERC-20 token backing the vault's internal balances. + IERC20 public token; + + /// @notice System configuration supplying the pause state for withdrawals. + ISystemConfig public systemConfig; + + /// @notice Canonical factory used to authenticate WIP-1006 dispute games. + IDisputeGameFactory public disputeGameFactory; + + /// @notice Reusable token credit available to fund bonds or request a withdrawal. + mapping(address account => uint256 amount) public availableBalance; + + /// @notice Pending delayed withdrawal request for each account. + mapping(address account => WithdrawalRequest request) public withdrawals; + + /// @notice Locked bond amounts and settlement state for each authenticated game. + mapping(address game => GameBond bond) public gameBonds; + + constructor(uint256 delaySeconds) { + DELAY_SECONDS = delaySeconds; + _disableInitializers(); + } + + /// @inheritdoc IERC20StakingVault + function initialize(IERC20 token_, ISystemConfig systemConfig_, IDisputeGameFactory disputeGameFactory_) + external + initializer + onlyProxyAdminOrOwner + { + if ( + address(token_) == address(0) || address(token_).code.length == 0 || address(systemConfig_) == address(0) + || address(systemConfig_).code.length == 0 || address(disputeGameFactory_) == address(0) + || address(disputeGameFactory_).code.length == 0 + ) { + revert InvalidVaultConfiguration(); + } + token = token_; + systemConfig = systemConfig_; + disputeGameFactory = disputeGameFactory_; + } + + /// @inheritdoc IERC20StakingVault + function delay() external view returns (uint256) { + return DELAY_SECONDS; + } + + /// @inheritdoc IERC20StakingVault + function proxyAdmin() public view returns (IProxyAdmin admin) { + address adminAddress = ERC1967Utils.getAdmin(); + if (adminAddress == address(0)) revert InvalidVaultConfiguration(); + return IProxyAdmin(adminAddress); + } + + /// @inheritdoc IERC20StakingVault + function proxyAdminOwner() public view returns (address) { + return proxyAdmin().owner(); + } + + /// @inheritdoc IERC20StakingVault + function deposit(address account, uint256 amount) external { + _deposit(account, amount); + } + + /// @inheritdoc IERC20StakingVault + function requestWithdrawal(uint256 amount) external { + if (amount == 0) revert InvalidWithdrawal(); + uint256 available = availableBalance[msg.sender]; + if (available < amount) revert InsufficientBalance(msg.sender, available, amount); + availableBalance[msg.sender] = available - amount; + + WithdrawalRequest storage request = withdrawals[msg.sender]; + request.amount += amount; + request.timestamp = block.timestamp; + emit WithdrawalRequested(msg.sender, request.amount, block.timestamp + DELAY_SECONDS); + } + + /// @inheritdoc IERC20StakingVault + function withdraw(uint256 amount) external { + if (amount == 0) revert InvalidWithdrawal(); + if (systemConfig.paused()) revert WithdrawalPaused(); + + WithdrawalRequest storage request = withdrawals[msg.sender]; + if (request.amount < amount || request.timestamp == 0) revert InvalidWithdrawal(); + uint256 availableAt = request.timestamp + DELAY_SECONDS; + if (block.timestamp < availableAt) revert WithdrawalDelayNotMet(availableAt); + + request.amount -= amount; + if (request.amount == 0) request.timestamp = 0; + token.safeTransfer(msg.sender, amount); + emit Withdrawn(msg.sender, amount); + } + + /// @inheritdoc IERC20StakingVault + function lockProposerBond() external ownersAligned { + IMultiProofGame game = IMultiProofGame(msg.sender); + if ( + GameType.unwrap(game.gameType()) != GameType.unwrap(GameTypes.MULTI_PROOF_GAME_TYPE) + || address(game.disputeGameFactory()) != address(disputeGameFactory) + || address(game.bondVault()) != address(this) + ) { + revert GameNotRegistered(msg.sender); + } + + // The factory registers a game only after `initialize` returns, so the factory mapping + // cannot authenticate this call yet. Instead recompute the deterministic clone address + // the factory derives for the current implementation and the caller's creation data; + // only a clone the factory itself deployed can occupy it. + (GameType gameType_, Claim rootClaim_, bytes memory extraData_) = game.gameData(); + Hash uuid = disputeGameFactory.getGameUUID(gameType_, rootClaim_, extraData_); + address implementation = address(disputeGameFactory.gameImpls(GameTypes.MULTI_PROOF_GAME_TYPE)); + address expectedGame = LibClone.predictDeterministicAddress( + implementation, + abi.encodePacked(game.gameCreator(), rootClaim_, game.l1Head(), extraData_), + Hash.unwrap(uuid), + address(disputeGameFactory) + ); + if (expectedGame != msg.sender) revert UnexpectedGameAddress(expectedGame, msg.sender); + if (gameBonds[msg.sender].proposerBond != 0) revert GameBondAlreadyInitialized(msg.sender); + + address proposer = game.gameCreator(); + uint256 amount = game.proposerBond(); + if (amount == 0) revert InvalidVaultConfiguration(); + _debitAvailable(proposer, amount); + gameBonds[msg.sender] = GameBond({proposerBond: amount, challengerBond: 0, settled: false}); + emit ProposerBondLocked(msg.sender, proposer, amount); + } + + /// @inheritdoc IERC20StakingVault + function lockChallengerBond() external ownersAligned { + IMultiProofGame game = _registeredGame(msg.sender); + GameBond storage bond = gameBonds[msg.sender]; + if (bond.proposerBond == 0) revert GameNotRegistered(msg.sender); + if (bond.challengerBond != 0 || bond.settled) revert ChallengerBondAlreadyLocked(msg.sender); + + address challenger = game.challenger(); + uint256 amount = game.challengerBond(); + if (challenger == address(0) || amount == 0) revert InvalidVaultConfiguration(); + _debitAvailable(challenger, amount); + bond.challengerBond = amount; + emit ChallengerBondLocked(msg.sender, challenger, amount); + } + + /// @inheritdoc IERC20StakingVault + function settle(Payout[] calldata payouts) external { + _registeredGame(msg.sender); + GameBond storage bond = gameBonds[msg.sender]; + if (bond.proposerBond == 0) revert GameNotRegistered(msg.sender); + if (bond.settled) revert GameAlreadySettled(msg.sender); + + uint256 payoutTotal; + for (uint256 i; i < payouts.length; i++) { + payoutTotal += payouts[i].amount; + } + + uint256 expected = bond.proposerBond + bond.challengerBond; + if (payoutTotal != expected) revert InvalidPayoutTotal(expected, payoutTotal); + + bond.settled = true; + for (uint256 i; i < payouts.length; i++) { + availableBalance[payouts[i].recipient] += payouts[i].amount; + } + emit GameSettled(msg.sender, payoutTotal); + } + + function _deposit(address account, uint256 amount) internal { + if (account == address(0)) revert InvalidAccount(); + if (amount == 0) revert InvalidAmount(); + + uint256 balanceBefore = token.balanceOf(address(this)); + token.safeTransferFrom(msg.sender, address(this), amount); + uint256 received = token.balanceOf(address(this)) - balanceBefore; + if (received != amount) revert ExactTransferRequired(amount, received); + + availableBalance[account] += amount; + emit Deposited(msg.sender, account, amount); + } + + function _registeredGame(address gameAddress) internal view returns (IMultiProofGame game) { + game = IMultiProofGame(gameAddress); + (GameType gameType_, Claim rootClaim_, bytes memory extraData_) = game.gameData(); + if (GameType.unwrap(gameType_) != GameType.unwrap(GameTypes.MULTI_PROOF_GAME_TYPE)) { + revert GameNotRegistered(gameAddress); + } + (IDisputeGame registered,) = disputeGameFactory.games(gameType_, rootClaim_, extraData_); + if (address(registered) != gameAddress || address(game.bondVault()) != address(this)) { + revert GameNotRegistered(gameAddress); + } + } + + // Bond locking lets factory-selected game code allocate participant balances, so the factory + // owner must be the same governance authority that controls this vault. + modifier ownersAligned() { + address factoryOwner = disputeGameFactory.owner(); + address vaultOwner = proxyAdminOwner(); + if (factoryOwner != vaultOwner) revert OwnerMismatch(factoryOwner, vaultOwner); + _; + } + + modifier onlyProxyAdminOrOwner() { + IProxyAdmin admin = proxyAdmin(); + if (msg.sender != address(admin) && msg.sender != admin.owner()) revert NotProxyAdminOwner(msg.sender); + _; + } + + function _debitAvailable(address account, uint256 amount) internal { + uint256 available = availableBalance[account]; + if (available < amount) revert InsufficientBalance(account, available, amount); + availableBalance[account] = available - amount; + } +} diff --git a/pkg/contracts/src/dispute/MultiProofGame.sol b/pkg/contracts/src/dispute/MultiProofGame.sol index 789ba74c3..003cda428 100644 --- a/pkg/contracts/src/dispute/MultiProofGame.sol +++ b/pkg/contracts/src/dispute/MultiProofGame.sol @@ -12,6 +12,7 @@ import { import {GameTypes} from "./lib/GameTypes.sol"; import {IMultiProofGame} from "./interfaces/IMultiProofGame.sol"; import {IWorldChainProofVerifier} from "./interfaces/IWorldChainProofVerifier.sol"; +import {IERC20StakingVault} from "./interfaces/IERC20StakingVault.sol"; import {Clone} from "@solady/utils/Clone.sol"; import { @@ -27,7 +28,6 @@ import { import { AlreadyInitialized, BadExtraData, - BondTransferFailed, ClaimAlreadyChallenged, ClaimAlreadyResolved, GameNotFinalized, @@ -38,14 +38,12 @@ import { InvalidBondDistributionMode, InvalidParentGame, InvalidProposalStatus, - NoCreditToClaim, ParentGameNotResolved, UnexpectedRootClaim } from "@optimism-bedrock/src/dispute/lib/Errors.sol"; import {IDisputeGame} from "@optimism-bedrock/interfaces/dispute/IDisputeGame.sol"; import {IDisputeGameFactory} from "@optimism-bedrock/interfaces/dispute/IDisputeGameFactory.sol"; import {IAnchorStateRegistry} from "@optimism-bedrock/interfaces/dispute/IAnchorStateRegistry.sol"; -import {IDelayedWETH} from "@optimism-bedrock/interfaces/dispute/IDelayedWETH.sol"; import {ISystemConfig} from "@optimism-bedrock/interfaces/L1/ISystemConfig.sol"; import {ISemver} from "@optimism-bedrock/interfaces/universal/ISemver.sol"; @@ -121,6 +119,7 @@ contract MultiProofGame is Clone, ISemver, IMultiProofGame { uint256 public immutable challengerBond; /// @notice Recipient of the share of forfeited proposer bonds not paid to a challenger. + /// @dev May be set to `0x000000000000000000000000000000000000dEaD` to make that share unspendable. address public immutable protocolFeeRecipient; /// @notice SP1 aggregation-program verification key used by the validity lane. @@ -143,8 +142,8 @@ contract MultiProofGame is Clone, ISemver, IMultiProofGame { /// @notice Registry providing the anchor root, blacklist, and finality airgap. IAnchorStateRegistry public immutable anchorStateRegistry; - /// @notice The DelayedWETH contract used for bond custody. - IDelayedWETH public immutable weth; + /// @notice ERC-20 vault used for bond custody and settlement. + IERC20StakingVault public immutable bondVault; /// @notice The starting timestamp of the game. Timestamp public createdAt; @@ -189,11 +188,12 @@ contract MultiProofGame is Clone, ISemver, IMultiProofGame { constructor(GameConfig memory config) { if ( config.blockInterval == 0 || config.challengePeriod == 0 || config.proofPeriod <= config.challengePeriod - || config.proposerBond == 0 || config.challengerBond == 0 || config.proofThreshold < 2 + || config.proposerBond == 0 || config.proposerBond > type(uint256).max / CHALLENGER_REWARD_BPS + || config.challengerBond == 0 || config.proofThreshold < 2 || config.proofThreshold > LibProof.PROOF_LANE_COUNT || config.protocolFeeRecipient == address(0) || config.aggregationVKey == bytes32(0) || config.rangeVKeyCommitment == bytes32(0) || config.teeImageId == bytes32(0) || address(config.anchorStateRegistry) == address(0) - || address(config.weth) == address(0) || address(config.validityProofVerifier) == address(0) + || address(config.bondVault) == address(0) || address(config.validityProofVerifier) == address(0) || address(config.teeVerifier) == address(0) || address(config.securityCouncil) == address(0) ) { revert InvalidActivationParameters(); @@ -207,7 +207,10 @@ contract MultiProofGame is Clone, ISemver, IMultiProofGame { if (address(factory) == address(0) || chainId == 0) { revert InvalidActivationParameters(); } - if (address(config.weth.systemConfig()) != address(systemConfig)) { + if ( + address(config.bondVault.systemConfig()) != address(systemConfig) + || address(config.bondVault.disputeGameFactory()) != address(factory) + ) { revert InconsistentSystemConfiguration(); } @@ -229,7 +232,7 @@ contract MultiProofGame is Clone, ISemver, IMultiProofGame { securityCouncil = config.securityCouncil; disputeGameFactory = factory; anchorStateRegistry = config.anchorStateRegistry; - weth = config.weth; + bondVault = config.bondVault; } //////////////////////////////////////////////////////////////// @@ -333,8 +336,8 @@ contract MultiProofGame is Clone, ISemver, IMultiProofGame { revert NotDisputeGameFactory(msg.sender); } - // Defense-in-depth against `setInitBond` drifting from the configured proposer bond. - if (msg.value != proposerBond) revert IncorrectBondAmount(); + // WIP-1006 uses ERC-20 tokens held by the vault; the stock factory bond must remain zero. + if (msg.value != 0) revert IncorrectBondAmount(); // Preserves the former propose-time registry pause gate. if (anchorStateRegistry.paused()) revert GamePaused(); @@ -367,25 +370,28 @@ contract MultiProofGame is Clone, ISemver, IMultiProofGame { } // Retries: attempt N is only proposable when attempt N-1 for the identical transition - // timed out on proofs or was created before WIP-1006 became respected. The latter - // prevents a pre-cutover game from permanently occupying the factory UUID. Inherited - // invalidations rebase onto a replacement parent and therefore restart at attempt zero. - // Duplicate attempts are impossible: the factory UUID covers (gameType, rootClaim, - // extraData). + // timed out on proofs (already settled, or locally doomed per `resolutionStatus`) or was + // created before WIP-1006 became respected. The latter prevents a pre-cutover game from + // permanently occupying the factory UUID. Inherited invalidations rebase onto a + // replacement parent and therefore restart at attempt zero. Duplicate attempts are + // impossible: the factory UUID covers (gameType, rootClaim, extraData). if (attempt_ > 0) { bytes memory previousExtraData = abi.encode(domainHash, l2SequenceNumber_, parentRef_, attempt_ - 1); + bytes32 previousUuid = keccak256(abi.encode(GameTypes.MULTI_PROOF_GAME_TYPE, rootClaim_, previousExtraData)); (IDisputeGame previous,) = disputeGameFactory.games(GameTypes.MULTI_PROOF_GAME_TYPE, rootClaim_, previousExtraData); + if (address(previous) == address(0)) revert GameNotRetryable(previousUuid); + + // Unrespected pre-cutover games may always be replaced. Respected ones only after a + // proof-timeout outcome (settled or parent-gated local doom). + (, GameStatus previousOutcome, InvalidationReason previousReason) = + IMultiProofGame(address(previous)).resolutionStatus(); if ( - address(previous) == address(0) - || (previous.wasRespectedGameTypeWhenCreated() - && (previous.status() != GameStatus.CHALLENGER_WINS - || IMultiProofGame(address(previous)).invalidationReason() - != InvalidationReason.PROOF_TIMEOUT)) + previous.wasRespectedGameTypeWhenCreated() + && (previousOutcome != GameStatus.CHALLENGER_WINS + || previousReason != InvalidationReason.PROOF_TIMEOUT) ) { - revert GameNotRetryable(keccak256( - abi.encode(GameTypes.MULTI_PROOF_GAME_TYPE, rootClaim_, previousExtraData) - )); + revert GameNotRetryable(previousUuid); } } @@ -397,7 +403,7 @@ contract MultiProofGame is Clone, ISemver, IMultiProofGame { claimData = ClaimData({ status: ProposalStatus.Unchallenged, challenger: address(0), - deadline: Timestamp.wrap(uint64(block.timestamp + challengePeriod.raw())), + deadline: _toTimestamp(block.timestamp + challengePeriod.raw()), proofBitmap: Bitmap.wrap(0), invalidationReason: InvalidationReason.NONE }); @@ -405,10 +411,13 @@ contract MultiProofGame is Clone, ISemver, IMultiProofGame { // Set the game as initialized. initialized = true; - _depositBond(gameCreator()); + // Lock the proposer bond from the creator's vault balance; the vault authenticates this + // clone against the factory's deterministic deployment address. + bondVault.lockProposerBond(); + _depositBond(gameCreator(), proposerBond); // Set the game's starting timestamp. - createdAt = Timestamp.wrap(uint64(block.timestamp)); + createdAt = _toTimestamp(block.timestamp); // Set whether the game type was respected when the game was created. wasRespectedGameTypeWhenCreated = @@ -416,11 +425,25 @@ contract MultiProofGame is Clone, ISemver, IMultiProofGame { } /// @notice Checks if the game is factory-registered, was respected when created, and has not - /// been invalidated by blacklisting, retirement, or a challenger win. + /// been invalidated by blacklisting, retirement, or a challenger win — including a + /// local proof-timeout doom from `resolutionStatus` before the game has settled. function _isValidGame(IDisputeGame game) internal view returns (bool) { - return anchorStateRegistry.isGameRegistered(game) && anchorStateRegistry.isGameRespected(game) - && !anchorStateRegistry.isGameBlacklisted(game) && !anchorStateRegistry.isGameRetired(game) - && (game.status() != GameStatus.CHALLENGER_WINS); + if ( + !anchorStateRegistry.isGameRegistered(game) || !anchorStateRegistry.isGameRespected(game) + || anchorStateRegistry.isGameBlacklisted(game) || anchorStateRegistry.isGameRetired(game) + ) { + return false; + } + // Parents of other game types, including an anchor inherited at cutover, only + // expose the standard dispute-game status getter. + if (game.gameType().raw() != GameTypes.MULTI_PROOF_GAME_TYPE.raw()) { + return game.status() != GameStatus.CHALLENGER_WINS; + } + // `status()` alone is insufficient: an unproven parent whose clock has expired stays + // `IN_PROGRESS` until its own parent resolves, but `resolutionStatus` already surfaces + // `CHALLENGER_WINS` / `PROOF_TIMEOUT` so keepers (and child creation) can stop on it. + (, GameStatus outcome,) = IMultiProofGame(address(game)).resolutionStatus(); + return outcome != GameStatus.CHALLENGER_WINS; } function _isValidParent(address parentRef_) internal view returns (bool) { @@ -430,10 +453,9 @@ contract MultiProofGame is Clone, ISemver, IMultiProofGame { return _isValidGame(IDisputeGame(parentRef_)); } - function _depositBond(address refundRecipient) internal { - refundModeCredit[refundRecipient] += msg.value; - totalBonds += msg.value; - weth.deposit{value: msg.value}(); + function _depositBond(address refundRecipient, uint256 amount) internal { + refundModeCredit[refundRecipient] += amount; + totalBonds += amount; } //////////////////////////////////////////////////////////////// @@ -441,7 +463,7 @@ contract MultiProofGame is Clone, ISemver, IMultiProofGame { //////////////////////////////////////////////////////////////// /// @notice Challenges the game. - function challenge() external payable returns (ProposalStatus) { + function challenge() external returns (ProposalStatus) { // INVARIANT: Cannot challenge if the game is already resolved. if (status != GameStatus.IN_PROGRESS) revert ClaimAlreadyResolved(); @@ -452,9 +474,6 @@ contract MultiProofGame is Clone, ISemver, IMultiProofGame { // INVARIANT: Can only challenge a game that has not been challenged yet. if (claimData.challenger != address(0)) revert ClaimAlreadyChallenged(); - // If the required bond is not met, revert. - if (msg.value != challengerBond) revert IncorrectBondAmount(); - // Update the challenger address. Any lanes accepted before the challenge keep counting // toward the threshold, but the status returns to `Challenged`. claimData.challenger = msg.sender; @@ -464,7 +483,8 @@ contract MultiProofGame is Clone, ISemver, IMultiProofGame { // at the challenge, so late challenges cannot extend the game. claimData.deadline = proofDeadline(); - _depositBond(msg.sender); + bondVault.lockChallengerBond(); + _depositBond(msg.sender, challengerBond); emit Challenged(msg.sender, claimData.deadline.raw()); @@ -596,7 +616,7 @@ contract MultiProofGame is Clone, ISemver, IMultiProofGame { // Mark the game as resolved. claimData.status = ProposalStatus.Resolved; - resolvedAt = Timestamp.wrap(uint64(block.timestamp)); + resolvedAt = _toTimestamp(block.timestamp); emit Resolved(status); @@ -623,7 +643,10 @@ contract MultiProofGame is Clone, ISemver, IMultiProofGame { } /// @inheritdoc IMultiProofGame - /// @dev View twin of `resolve()`: reports what a resolve call would do right now. + /// @dev Reports the eventual outcome. `resolvable` is true only when `resolve()` + /// would succeed. A locally doomed, unproven game surfaces `CHALLENGER_WINS` / + /// `PROOF_TIMEOUT` even while its parent is still open, so keepers can stop building + /// on it. Settlement still waits for the parent so bond credits stay correct. function resolutionStatus() external view returns (bool resolvable, GameStatus outcome, InvalidationReason reason) { if (status != GameStatus.IN_PROGRESS) { return (false, status, claimData.invalidationReason); @@ -631,70 +654,41 @@ contract MultiProofGame is Clone, ISemver, IMultiProofGame { (GameStatus parentStatus, bool parentBlacklisted) = _parentResolution(); if (parentBlacklisted || parentStatus == GameStatus.CHALLENGER_WINS) { + // Parent game is invalid, return `CHALLENGER_WINS` with `INVALID_PARENT`. return (true, GameStatus.CHALLENGER_WINS, InvalidationReason.INVALID_PARENT); } - if (parentStatus == GameStatus.IN_PROGRESS || !gameOver()) { - return (false, GameStatus.IN_PROGRESS, InvalidationReason.NONE); - } + bool parentResolved = parentStatus != GameStatus.IN_PROGRESS; bool proven = claimData.status == ProposalStatus.UnchallengedAndValidProofProvided || claimData.status == ProposalStatus.ChallengedAndValidProofProvided; - return proven - ? (true, GameStatus.DEFENDER_WINS, InvalidationReason.NONE) - : (true, GameStatus.CHALLENGER_WINS, InvalidationReason.PROOF_TIMEOUT); - } - /// @inheritdoc IMultiProofGame - /// @dev Two-phase: the first call unlocks in DelayedWETH, the second (after the WETH - /// delay) withdraws and transfers. - function claimCredit(address recipient) external { - // If closeGame() flips the distribution mode within this call and there is nothing to - // claim, return instead of reverting so the close is not rolled back. - bool gameWasOpen = bondDistributionMode == BondDistributionMode.UNDECIDED; - - // Close lazily so claiming does not depend on a separate keeper transaction. This is a - // no-op once the distribution mode has been fixed. - closeGame(); - - uint256 recipientCredit; - if (bondDistributionMode == BondDistributionMode.REFUND) { - recipientCredit = refundModeCredit[recipient]; - } else if (bondDistributionMode == BondDistributionMode.NORMAL) { - recipientCredit = normalModeCredit[recipient]; - } else { - revert InvalidBondDistributionMode(); + if (!gameOver()) { + // This game is not over yet, return `IN_PROGRESS`. + return (false, GameStatus.IN_PROGRESS, InvalidationReason.NONE); } - - // Zero the credit and unlock it in DelayedWETH. - if (recipientCredit > 0) { - refundModeCredit[recipient] = 0; - normalModeCredit[recipient] = 0; - weth.unlock(recipient, recipientCredit); - return; + // This game is over. + if (!proven) { + // This game is over but it doesn't have enough proofs. + // Return `CHALLENGER_WINS` as outcome. The `resolvable` instead depends on the + // parent game: you cannot resolve this game if parent is not resolved yet. + return (parentResolved, GameStatus.CHALLENGER_WINS, InvalidationReason.PROOF_TIMEOUT); } - - // Phase 2: finalize the pending DelayedWETH withdrawal. - (uint256 amount,) = weth.withdrawals(address(this), recipient); - if (amount == 0) { - if (gameWasOpen) return; - revert NoCreditToClaim(); + // This game is over and has enough proofs. + if (!parentResolved) { + // Parent game is not resolved yet, therefore return `IN_PROGRESS`. + return (false, GameStatus.IN_PROGRESS, InvalidationReason.NONE); } - - weth.withdraw(recipient, amount); - - // solady's CWIA proxy implements `receive()`, so the WETH98 2300-gas transfer above - // succeeds without a `receive()` on this implementation. - (bool success,) = recipient.call{value: amount}(hex""); - if (!success) revert BondTransferFailed(); + // This game is over, it has enough proofs and the parent is already resolved. + return (true, GameStatus.DEFENDER_WINS, InvalidationReason.NONE); } /// @inheritdoc IMultiProofGame /// @dev Locks in `REFUND` for improper games — blacklisted, retired, or otherwise - /// invalidated by the registry. Must not revert once closed, or `claimCredit` breaks. + /// invalidated by the registry. Repeated calls are harmless after settlement. function closeGame() public { if (bondDistributionMode == BondDistributionMode.REFUND || bondDistributionMode == BondDistributionMode.NORMAL) { - // Already closed; must not revert or `claimCredit` would break. + // Settlement is idempotent for permissionless keepers. return; } else if (bondDistributionMode != BondDistributionMode.UNDECIDED) { revert InvalidBondDistributionMode(); @@ -718,9 +712,49 @@ contract MultiProofGame is Clone, ISemver, IMultiProofGame { bondDistributionMode = anchorStateRegistry.isGameProper(self) ? BondDistributionMode.NORMAL : BondDistributionMode.REFUND; + bondVault.settle(_settlementCredits()); + emit GameClosed(bondDistributionMode); } + function _settlementCandidates() internal view returns (address[] memory candidates) { + // Possible recipients are the proposer, challenger, protocol, and one recipient per proof lane. + candidates = new address[](3 + LibProof.PROOF_LANE_COUNT); + candidates[0] = gameCreator(); + candidates[1] = claimData.challenger; + candidates[2] = protocolFeeRecipient; + for (uint8 laneId; laneId < LibProof.PROOF_LANE_COUNT; laneId++) { + candidates[3 + laneId] = laneRecipient[laneId]; + } + } + + function _settlementCredits() internal view returns (IERC20StakingVault.Payout[] memory payouts) { + address[] memory candidates = _settlementCandidates(); + payouts = new IERC20StakingVault.Payout[](candidates.length); + uint256 payoutCount; + // Credits are aggregated by address, but the same address may occupy multiple roles. + // Emit each credited candidate once so its complete mapped credit is settled exactly once. + for (uint256 i; i < candidates.length; i++) { + address candidate = candidates[i]; + bool duplicate; + for (uint256 j; j < payoutCount; j++) { + if (payouts[j].recipient == candidate) { + duplicate = true; + break; + } + } + if (duplicate) continue; + + uint256 amount = bondDistributionMode == BondDistributionMode.REFUND + ? refundModeCredit[candidate] + : normalModeCredit[candidate]; + if (amount == 0) continue; + payouts[payoutCount++] = IERC20StakingVault.Payout({recipient: candidate, amount: amount}); + } + + // Unused entries remain zero-value payouts, which do not affect vault accounting. + } + //////////////////////////////////////////////////////////////// // MISC EXTERNAL // //////////////////////////////////////////////////////////////// @@ -728,17 +762,7 @@ contract MultiProofGame is Clone, ISemver, IMultiProofGame { /// @notice Determines if the game is finished. /// @return gameOver_ True if the active deadline has passed or the threshold is reached. function gameOver() public view returns (bool gameOver_) { - gameOver_ = - claimData.deadline.raw() <= uint64(block.timestamp) || claimData.proofBitmap.hasThreshold(PROOF_THRESHOLD); - } - - /// @inheritdoc IMultiProofGame - function credit(address recipient) external view returns (uint256 credit_) { - if (bondDistributionMode == BondDistributionMode.REFUND) { - credit_ = refundModeCredit[recipient]; - } else { - credit_ = normalModeCredit[recipient]; - } + gameOver_ = claimData.deadline.raw() <= block.timestamp || claimData.proofBitmap.hasThreshold(PROOF_THRESHOLD); } /// @inheritdoc IMultiProofGame @@ -797,12 +821,19 @@ contract MultiProofGame is Clone, ISemver, IMultiProofGame { /// @inheritdoc IMultiProofGame function challengeDeadline() public view returns (Timestamp) { - return Timestamp.wrap(createdAt.raw() + challengePeriod.raw()); + return _toTimestamp(uint256(createdAt.raw()) + challengePeriod.raw()); } /// @inheritdoc IMultiProofGame function proofDeadline() public view returns (Timestamp) { - return Timestamp.wrap(createdAt.raw() + proofPeriod.raw()); + return _toTimestamp(uint256(createdAt.raw()) + proofPeriod.raw()); + } + + function _toTimestamp(uint256 value) internal pure returns (Timestamp) { + if (value > type(uint64).max) revert TimestampOutOfBounds(value); + // The bound above proves this narrowing conversion is lossless. + // forge-lint: disable-next-line(unsafe-typecast) + return Timestamp.wrap(uint64(value)); } /// @dev Selects the verifier and game-pinned statement for `lane`. The generic public-values diff --git a/pkg/contracts/src/dispute/interfaces/IERC20StakingVault.sol b/pkg/contracts/src/dispute/interfaces/IERC20StakingVault.sol new file mode 100644 index 000000000..fec0b1612 --- /dev/null +++ b/pkg/contracts/src/dispute/interfaces/IERC20StakingVault.sol @@ -0,0 +1,124 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.28; + +import {IDisputeGameFactory} from "@optimism-bedrock/interfaces/dispute/IDisputeGameFactory.sol"; +import {ISystemConfig} from "@optimism-bedrock/interfaces/L1/ISystemConfig.sol"; +import {IProxyAdmin} from "@optimism-bedrock/interfaces/universal/IProxyAdmin.sol"; +import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; + +/// @title IERC20StakingVault +/// @notice Custodies the ERC-20 token used by WIP-1006 proposers, challengers, and reward recipients. +interface IERC20StakingVault { + /// @notice The bonds a registered game custodies and whether its pot has been distributed. + /// @param proposerBond The proposer bond locked when the game was created; non-zero marks the + /// game as registered. + /// @param challengerBond The challenger bond, non-zero once a challenge has been locked. + /// @param settled Whether the game's full pot has already been settled. + struct GameBond { + uint256 proposerBond; + uint256 challengerBond; + bool settled; + } + + /// @notice An account's pending external withdrawal. + /// @param amount The total ERC-20 token queued for withdrawal. + /// @param timestamp The latest request time; the delay is measured from here, so a new + /// request restarts the wait for the whole pending amount. + struct WithdrawalRequest { + uint256 amount; + uint256 timestamp; + } + + /// @notice A single credit within a game settlement. + /// @param recipient The account whose available balance is credited. + /// @param amount The ERC-20 token credited to the recipient. + struct Payout { + address recipient; + uint256 amount; + } + + /// @notice Emitted when ERC-20 token is deposited into an account's available balance. + /// @param depositor The account that supplied the ERC-20 token. + /// @param account The account credited with the balance. + /// @param amount The deposited ERC-20 token. + event Deposited(address indexed depositor, address indexed account, uint256 amount); + + /// @notice Emitted when a game's proposer bond is locked from its creator's balance. + /// @param game The game the bond is held against. + /// @param proposer The account whose balance backed the bond. + /// @param amount The locked proposer bond. + event ProposerBondLocked(address indexed game, address indexed proposer, uint256 amount); + + /// @notice Emitted when a game's challenger bond is locked from the challenger's balance. + /// @param game The game the bond is held against. + /// @param challenger The account whose balance backed the bond. + /// @param amount The locked challenger bond. + event ChallengerBondLocked(address indexed game, address indexed challenger, uint256 amount); + + /// @notice Emitted when a game's pot is settled and distributed to payout recipients. + /// @param game The settled game. + /// @param amount The total pot distributed. + event GameSettled(address indexed game, uint256 amount); + + /// @notice Emitted when an account moves available ERC-20 token into a pending withdrawal. + /// @param account The requesting account. + /// @param amount The total pending withdrawal after the request. + /// @param availableAt The timestamp at which the pending amount becomes claimable. + event WithdrawalRequested(address indexed account, uint256 amount, uint256 availableAt); + + /// @notice Emitted when an account claims a matured withdrawal. + /// @param account The withdrawing account. + /// @param amount The ERC-20 token transferred out. + event Withdrawn(address indexed account, uint256 amount); + + /// @notice Initializes the proxy with its fixed external dependencies. + function initialize(IERC20 token, ISystemConfig systemConfig, IDisputeGameFactory disputeGameFactory) external; + + /// @notice Canonical ERC-20 token held by the vault. + function token() external view returns (IERC20); + + /// @notice System configuration supplying the shared pause state. + function systemConfig() external view returns (ISystemConfig); + + /// @notice Canonical factory allowed to create and register WIP-1006 games. + function disputeGameFactory() external view returns (IDisputeGameFactory); + + /// @notice Delay between requesting and executing an external ERC-20 token withdrawal. + function delay() external view returns (uint256); + + /// @notice Deposited or settled ERC-20 token available to fund bonds or request for withdrawal. + function availableBalance(address account) external view returns (uint256); + + /// @notice Pending external withdrawal amount and the timestamp of its latest request. + function withdrawals(address account) external view returns (uint256 amount, uint256 timestamp); + + /// @notice Bond amounts assigned to a game and whether its complete pot was settled. + function gameBonds(address game) external view returns (uint256 proposerBond, uint256 challengerBond, bool settled); + + /// @notice ProxyAdmin stored in the OP Proxy's ERC-1967 admin slot. + function proxyAdmin() external view returns (IProxyAdmin); + + /// @notice Owner of the vault's ProxyAdmin. + function proxyAdminOwner() external view returns (address); + + /// @notice Deposits the caller's ERC-20 token into an account's available balance. + function deposit(address account, uint256 amount) external; + + /// @notice Moves available ERC-20 token into a pending withdrawal and resets its full delay. + function requestWithdrawal(uint256 amount) external; + + /// @notice Transfers matured pending ERC-20 token to the caller while the system is unpaused. + function withdraw(uint256 amount) external; + + /// @notice Locks the calling game's proposer bond from its creator's available balance. + /// @dev Called during `initialize`, before the factory registers the game, so the caller is + /// authenticated as the deterministic clone the factory deploys for its creation data. + function lockProposerBond() external; + + /// @notice Locks the calling registered game's single challenger bond from the challenger's + /// available balance. + function lockChallengerBond() external; + + /// @notice Credits a registered game's complete finalized pot exactly once. + function settle(Payout[] calldata payouts) external; +} diff --git a/pkg/contracts/src/dispute/interfaces/IMultiProofGame.sol b/pkg/contracts/src/dispute/interfaces/IMultiProofGame.sol index df2352917..36407a052 100644 --- a/pkg/contracts/src/dispute/interfaces/IMultiProofGame.sol +++ b/pkg/contracts/src/dispute/interfaces/IMultiProofGame.sol @@ -3,12 +3,12 @@ pragma solidity 0.8.28; import {LibProof, InvalidationReason, Bitmap, ProofLane} from "../lib/LibProof.sol"; import {IWorldChainProofVerifier} from "./IWorldChainProofVerifier.sol"; +import {IERC20StakingVault} from "./IERC20StakingVault.sol"; import {BondDistributionMode, Duration, GameStatus, Hash, Timestamp} from "@optimism-bedrock/src/dispute/lib/Types.sol"; import {IDisputeGame} from "@optimism-bedrock/interfaces/dispute/IDisputeGame.sol"; import {IDisputeGameFactory} from "@optimism-bedrock/interfaces/dispute/IDisputeGameFactory.sol"; import {IAnchorStateRegistry} from "@optimism-bedrock/interfaces/dispute/IAnchorStateRegistry.sol"; -import {IDelayedWETH} from "@optimism-bedrock/interfaces/dispute/IDelayedWETH.sol"; /// @title IMultiProofGame /// @author World Contributors @@ -64,7 +64,7 @@ interface IMultiProofGame is IDisputeGame { IWorldChainProofVerifier teeVerifier; IWorldChainProofVerifier securityCouncil; IAnchorStateRegistry anchorStateRegistry; - IDelayedWETH weth; + IERC20StakingVault bondVault; } //////////////////////////////////////////////////////////////// @@ -79,6 +79,7 @@ interface IMultiProofGame is IDisputeGame { error InvalidProof(ProofLane lane, bytes32 rootId); error InvalidDomainHash(bytes32 expected, bytes32 actual); error InconsistentSystemConfiguration(); + error TimestampOutOfBounds(uint256 value); /// @notice Thrown when a lane that already counts toward the threshold is resubmitted. error DuplicateProofLane(ProofLane lane, bytes32 rootId, Bitmap proofBitmap); @@ -159,8 +160,8 @@ interface IMultiProofGame is IDisputeGame { /// @notice Registry providing the anchor root, blacklist, and finality airgap. function anchorStateRegistry() external view returns (IAnchorStateRegistry); - /// @notice Bond custody contract. - function weth() external view returns (IDelayedWETH); + /// @notice ERC-20 bond custody and settlement contract. + function bondVault() external view returns (IERC20StakingVault); //////////////////////////////////////////////////////////////// // Proposal context // @@ -173,7 +174,8 @@ interface IMultiProofGame is IDisputeGame { function proposalDomainHash() external view returns (bytes32); /// @notice Retry nonce for this transition. Attempt N requires attempt N-1 to have timed - /// out on proofs or to have been created before this game type became respected. + /// out on proofs (settled or locally doomed) or to have been created before this + /// game type became respected. function attempt() external view returns (uint256); /// @notice Parent game, or the anchor registry when no compatible anchor game exists. @@ -229,16 +231,18 @@ interface IMultiProofGame is IDisputeGame { /// passed or the proof threshold has been reached. function gameOver() external view returns (bool); - /// @notice Returns whether this game can resolve now and the outcome a resolve call would - /// produce; `outcome` is `IN_PROGRESS` while the game cannot resolve. + /// @notice Returns whether this game can resolve now and its eventual outcome. + /// @dev `resolvable` is true only when `resolve()` would succeed. `outcome` may already be + /// terminal (e.g. a locally doomed unproven game) while `resolvable` is still false + /// because the parent has not resolved yet. function resolutionStatus() external view returns (bool resolvable, GameStatus outcome, InvalidationReason reason); //////////////////////////////////////////////////////////////// // Challenge and proofs // //////////////////////////////////////////////////////////////// - /// @notice Disputes a proven proposal during the open challenge window for exactly `challengerBond`. - function challenge() external payable returns (ProposalStatus); + /// @notice Disputes a proposal, locking `challengerBond` from the caller's available vault balance. + function challenge() external returns (ProposalStatus); /// @notice Submits a compact proof payload. Before a challenge, any accepted lane satisfies /// the initial proof requirement; after a challenge, distinct lanes count toward the @@ -256,7 +260,7 @@ interface IMultiProofGame is IDisputeGame { /// @notice Distribution mode locked in by `closeGame`. function bondDistributionMode() external view returns (BondDistributionMode); - /// @notice Total bonds custodied by this game. + /// @notice Total ERC-20 bonds assigned to this game's vault pot. function totalBonds() external view returns (uint256); /// @notice Credit owed to `recipient` when the game closes in `NORMAL` mode. @@ -264,11 +268,4 @@ interface IMultiProofGame is IDisputeGame { /// @notice Credit owed to `recipient` when the game closes in `REFUND` mode. function refundModeCredit(address recipient) external view returns (uint256 amount); - - /// @notice Returns the credit `recipient` can claim from this game. - function credit(address recipient) external view returns (uint256); - - /// @notice Permissionlessly claims `recipient`'s credit via the two-phase DelayedWETH flow; - /// the caller cannot redirect funds away from `recipient`. - function claimCredit(address recipient) external; } diff --git a/pkg/contracts/src/dispute/lib/Errors.sol b/pkg/contracts/src/dispute/lib/Errors.sol new file mode 100644 index 000000000..c9cc0fa34 --- /dev/null +++ b/pkg/contracts/src/dispute/lib/Errors.sol @@ -0,0 +1,73 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.28; + +//////////////////////////////////////////////////////////////// +// `ERC20StakingVault` Errors // +//////////////////////////////////////////////////////////////// + +/// @notice Thrown when a game's single challenger bond has already been locked. +/// @param game The address of the game whose challenger bond is already locked. +error ChallengerBondAlreadyLocked(address game); + +/// @notice Thrown when a deposit does not credit the vault by exactly the stated amount, +/// guarding against fee-on-transfer or rebasing token behavior. +/// @param expected The amount the caller asked to deposit. +/// @param actual The balance increase the vault actually observed. +error ExactTransferRequired(uint256 expected, uint256 actual); + +/// @notice Thrown when a game's pot has already been settled. +/// @param game The address of the already-settled game. +error GameAlreadySettled(address game); + +/// @notice Thrown when a game's bond record has already been initialized. +/// @param game The address of the game whose bond is already recorded. +error GameBondAlreadyInitialized(address game); + +/// @notice Thrown when the caller is not a MultiProofGame registered with the factory and bound +/// to this vault. +/// @param game The address that failed the registration check. +error GameNotRegistered(address game); + +/// @notice Thrown when an account's available balance cannot cover a debit. +/// @param account The account being debited. +/// @param available The account's available balance. +/// @param required The amount the operation required. +error InsufficientBalance(address account, uint256 available, uint256 required); + +/// @notice Thrown when settlement payouts do not sum to the game's full pot. +/// @param expected The pot to distribute (proposer bond plus challenger bond). +/// @param actual The sum of the supplied payouts. +error InvalidPayoutTotal(uint256 expected, uint256 actual); + +/// @notice Thrown when a deposit targets the zero address. +error InvalidAccount(); + +error InvalidAmount(); + +/// @notice Thrown when a required dependency address is unset, has no code, or is mismatched +/// relative to the vault's expected wiring. +error InvalidVaultConfiguration(); + +error InvalidWithdrawal(); + +/// @notice Thrown when the caller is neither the ERC-1967 ProxyAdmin nor its owner. +/// @param caller The unauthorized caller. +error NotProxyAdminOwner(address caller); + +/// @notice Thrown when the dispute game factory owner and the vault's ProxyAdmin owner diverge, +/// which would split the authority the bond-locking flow relies on. +/// @param disputeGameFactoryOwner The current factory owner. +/// @param proxyAdminOwner The current ProxyAdmin owner. +error OwnerMismatch(address disputeGameFactoryOwner, address proxyAdminOwner); + +/// @notice Thrown when a locking game's address does not match the deterministic clone address +/// the factory derives for its creation data. +/// @param expected The predicted deterministic clone address. +/// @param actual The address that actually called in. +error UnexpectedGameAddress(address expected, address actual); + +/// @notice Thrown when a matured withdrawal is claimed before its delay has elapsed. +/// @param availableAt The timestamp at which the withdrawal becomes claimable. +error WithdrawalDelayNotMet(uint256 availableAt); + +error WithdrawalPaused(); diff --git a/pkg/contracts/src/dispute/nitro/NitroAttestationVerifier.sol b/pkg/contracts/src/dispute/nitro/NitroAttestationVerifier.sol index c77e66345..46fcb7e36 100644 --- a/pkg/contracts/src/dispute/nitro/NitroAttestationVerifier.sol +++ b/pkg/contracts/src/dispute/nitro/NitroAttestationVerifier.sol @@ -39,6 +39,9 @@ contract NitroAttestationVerifier is NitroValidator, INitroAttestationVerifier, /// required). error InsufficientPcrs(uint256 found); + /// @notice A required PCR slot is absent from the sparse PCR bank. + error MissingPcr(uint256 index); + /// @notice The PCR triple extracted from the document is not currently /// approved by the owner. error PCRSetNotApproved(bytes32 pcr0, bytes32 pcr1, bytes32 pcr2); @@ -217,6 +220,9 @@ contract NitroAttestationVerifier is NitroValidator, INitroAttestationVerifier, // 3. Extract PCR0/1/2 digests from the document. if (ptrs.pcrs.length < 3) revert InsufficientPcrs(ptrs.pcrs.length); + for (uint256 i; i < 3; i++) { + if (ptrs.pcrs[i].isNull()) revert MissingPcr(i); + } pcr0 = _hashPcr(attestationTbs, ptrs.pcrs[0]); pcr1 = _hashPcr(attestationTbs, ptrs.pcrs[1]); pcr2 = _hashPcr(attestationTbs, ptrs.pcrs[2]); diff --git a/pkg/contracts/test/dispute/ActivateProofSystem.t.sol b/pkg/contracts/test/dispute/ActivateProofSystem.t.sol index 07846a2a3..3e8e01bb8 100644 --- a/pkg/contracts/test/dispute/ActivateProofSystem.t.sol +++ b/pkg/contracts/test/dispute/ActivateProofSystem.t.sol @@ -6,9 +6,14 @@ import {MultiProofGame} from "../../src/dispute/MultiProofGame.sol"; import {IMultiProofGame} from "../../src/dispute/interfaces/IMultiProofGame.sol"; import {OPStackFixtures} from "./OPStackFixtures.sol"; +import {IDisputeGame} from "@optimism-bedrock/interfaces/dispute/IDisputeGame.sol"; import {ISystemConfig} from "@optimism-bedrock/interfaces/L1/ISystemConfig.sol"; contract ActivateProofSystemHarness is ActivateProofSystem { + function _safeMode() internal pure override returns (bool) { + return false; + } + function validate(Config memory config, IMultiProofGame implementation) external view { _validate(config, implementation); } @@ -16,12 +21,15 @@ contract ActivateProofSystemHarness is ActivateProofSystem { contract ActivateProofSystemTest is OPStackFixtures { uint256 internal constant GUARDIAN_KEY = 0xA11CE; + uint256 internal constant DGF_OWNER_KEY = 0xB0B; ActivateProofSystemHarness internal activation; function setUp() public override { super.setUp(); systemConfig.setGuardian(vm.addr(GUARDIAN_KEY)); + dgf.transferOwnership(vm.addr(DGF_OWNER_KEY)); + proxyAdmin.transferOwnership(vm.addr(DGF_OWNER_KEY)); activation = new ActivateProofSystemHarness(); } @@ -39,6 +47,18 @@ contract ActivateProofSystemTest is OPStackFixtures { activation.validate(_activationConfig(true), IMultiProofGame(address(gameImpl))); } + function test_validate_acceptsBlacklistedAnchor() public { + MultiProofGame game = _proposeAtAnchor(); + _resolveUnchallenged(game); + _passAirgap(game); + asr.setAnchorState(game); + + vm.prank(vm.addr(GUARDIAN_KEY)); + asr.blacklistDisputeGame(IDisputeGame(address(game))); + + activation.validate(_activationConfig(false), IMultiProofGame(address(gameImpl))); + } + function test_validate_rejectsRetiredAnchor() public { MultiProofGame game = _proposeAtAnchor(); _resolveUnchallenged(game); @@ -52,12 +72,51 @@ contract ActivateProofSystemTest is OPStackFixtures { activation.validate(_activationConfig(false), IMultiProofGame(address(gameImpl))); } + function test_validate_rejectsDivergedFactoryAndVaultOwners() public { + vm.prank(vm.addr(DGF_OWNER_KEY)); + proxyAdmin.transferOwnership(makeAddr("new-proxy-admin-owner")); + + vm.expectRevert("ActivateProofSystem: DGF and ProxyAdmin owners must match"); + activation.validate(_activationConfig(false), IMultiProofGame(address(gameImpl))); + } + + function test_validate_rejectsDuplicateProofLaneVerifiers() public { + IMultiProofGame.GameConfig memory gameConfig = _gameConfig(); + gameConfig.teeVerifier = gameConfig.validityProofVerifier; + MultiProofGame implementation = new MultiProofGame(gameConfig); + + vm.expectRevert("ActivateProofSystem: proof lane verifiers must be distinct"); + activation.validate(_activationConfig(false), IMultiProofGame(address(implementation))); + } + + function test_run_registersValidatedImplementation() public { + MultiProofGame implementation = new MultiProofGame(_gameConfig()); + vm.setEnv("DGF_OWNER_KEY", vm.toString(DGF_OWNER_KEY)); + vm.setEnv("DISPUTE_GAME_FACTORY", vm.toString(address(dgf))); + vm.setEnv("ANCHOR_STATE_REGISTRY", vm.toString(address(asr))); + vm.setEnv("SYSTEM_CONFIG", vm.toString(address(systemConfig))); + vm.setEnv("OP_CHAIN_PROXY_ADMIN", vm.toString(address(proxyAdmin))); + vm.setEnv("BOND_TOKEN", vm.toString(address(bondToken))); + vm.setEnv("GAME_IMPLEMENTATION", vm.toString(address(implementation))); + + IMultiProofGame activated = activation.run(); + + assertEq(address(activated), address(implementation)); + assertEq(address(dgf.gameImpls(WC_GAME_TYPE)), address(implementation)); + assertEq(dgf.initBonds(WC_GAME_TYPE), 0); + assertEq(dgf.gameArgs(WC_GAME_TYPE), hex""); + } + function _activationConfig(bool requireFreshAnchor) internal view returns (ActivateProofSystem.Config memory) { return ActivateProofSystem.Config({ guardianKey: GUARDIAN_KEY, + dgfOwnerKey: DGF_OWNER_KEY, disputeGameFactory: dgf, anchorStateRegistry: asr, systemConfig: ISystemConfig(address(systemConfig)), + proxyAdmin: proxyAdmin, + bondToken: bondToken, + gameImplementation: IMultiProofGame(address(gameImpl)), requireFreshAnchor: requireFreshAnchor }); } diff --git a/pkg/contracts/test/dispute/ERC20StakingVault.t.sol b/pkg/contracts/test/dispute/ERC20StakingVault.t.sol new file mode 100644 index 000000000..05bcfd14d --- /dev/null +++ b/pkg/contracts/test/dispute/ERC20StakingVault.t.sol @@ -0,0 +1,349 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.28; + +import {OPStackFixtures} from "./OPStackFixtures.sol"; +import {MultiProofGame} from "../../src/dispute/MultiProofGame.sol"; +import {ERC20StakingVault} from "../../src/dispute/ERC20StakingVault.sol"; +import {IERC20StakingVault} from "../../src/dispute/interfaces/IERC20StakingVault.sol"; +import { + GameAlreadySettled, + GameNotRegistered, + InsufficientBalance, + InvalidAccount, + InvalidAmount, + InvalidPayoutTotal, + NotProxyAdminOwner, + OwnerMismatch, + WithdrawalDelayNotMet, + WithdrawalPaused +} from "../../src/dispute/lib/Errors.sol"; +import {IDisputeGameFactory} from "@optimism-bedrock/interfaces/dispute/IDisputeGameFactory.sol"; +import {GameTypes} from "../../src/dispute/lib/GameTypes.sol"; + +import {Claim, GameType, Hash} from "@optimism-bedrock/src/dispute/lib/Types.sol"; +import {IncorrectBondAmount} from "@optimism-bedrock/src/dispute/lib/Errors.sol"; +import {IDisputeGame} from "@optimism-bedrock/interfaces/dispute/IDisputeGame.sol"; +import {ISystemConfig} from "@optimism-bedrock/interfaces/L1/ISystemConfig.sol"; + +contract UnregisteredGameHarness { + function gameData() external pure returns (GameType, Claim, bytes memory) { + return (GameTypes.MULTI_PROOF_GAME_TYPE, Claim.wrap(bytes32(uint256(1))), hex""); + } +} + +/// @dev Mimics a mid-creation game's surface but was not deployed by the factory, so it cannot +/// occupy the deterministic clone address the vault recomputes. +contract ImpersonatingGameHarness { + IDisputeGameFactory internal immutable FACTORY; + IERC20StakingVault internal immutable VAULT; + address internal immutable VICTIM; + + constructor(IDisputeGameFactory factory, IERC20StakingVault vault, address victim) { + FACTORY = factory; + VAULT = vault; + VICTIM = victim; + } + + function gameType() external pure returns (GameType) { + return GameTypes.MULTI_PROOF_GAME_TYPE; + } + + function disputeGameFactory() external view returns (IDisputeGameFactory) { + return FACTORY; + } + + function bondVault() external view returns (IERC20StakingVault) { + return VAULT; + } + + function gameData() external pure returns (GameType, Claim, bytes memory) { + return (GameTypes.MULTI_PROOF_GAME_TYPE, Claim.wrap(bytes32(uint256(1))), hex""); + } + + function gameCreator() external view returns (address) { + return VICTIM; + } + + function l1Head() external pure returns (Hash) { + return Hash.wrap(bytes32(0)); + } + + function proposerBond() external pure returns (uint256) { + return 1e18; + } + + function lock() external { + VAULT.lockProposerBond(); + } +} + +contract ERC20StakingVaultAccountingTest is OPStackFixtures { + function test_ProxyAdminIntrospectionMatchesOPProxy() public view { + assertEq(address(bondVault.proxyAdmin()), address(proxyAdmin)); + assertEq(bondVault.proxyAdminOwner(), address(this)); + } + + function test_Initialize_RejectsUnauthorizedCaller() public { + ERC20StakingVault implementation = new ERC20StakingVault(ERC20_WITHDRAWAL_DELAY_SECONDS); + IERC20StakingVault vault = + IERC20StakingVault(deployCode("opstack/out/Proxy.sol/Proxy.json", abi.encode(address(proxyAdmin)))); + proxyAdmin.upgrade(payable(address(vault)), address(implementation)); + + address unauthorized = makeAddr("unauthorized"); + vm.prank(unauthorized); + vm.expectRevert(abi.encodeWithSelector(NotProxyAdminOwner.selector, unauthorized)); + vault.initialize(bondToken, ISystemConfig(address(systemConfig)), dgf); + } + + function test_DepositCreditsSelectedAvailableBalances() public { + address funder = makeAddr("funder"); + address beneficiary = makeAddr("beneficiary"); + uint256 amount = 3 * TOKEN_UNIT; + bondToken.mint(funder, amount); + + vm.prank(funder); + bondToken.approve(address(bondVault), amount); + vm.prank(funder); + bondVault.deposit(funder, TOKEN_UNIT); + vm.prank(funder); + bondVault.deposit(beneficiary, 2 * TOKEN_UNIT); + + assertEq(bondVault.availableBalance(funder), TOKEN_UNIT); + assertEq(bondVault.availableBalance(beneficiary), 2 * TOKEN_UNIT); + assertEq(bondToken.allowance(funder, address(bondVault)), 0); + assertEq(bondToken.balanceOf(funder), 0); + assertEq(bondToken.balanceOf(address(bondVault)), 203 * TOKEN_UNIT); + } + + function test_DepositRejectsZeroAccount() public { + vm.prank(proposer); + vm.expectRevert(InvalidAccount.selector); + bondVault.deposit(address(0), TOKEN_UNIT); + } + + function test_DepositRejectsZeroAmount() public { + vm.prank(proposer); + vm.expectRevert(InvalidAmount.selector); + bondVault.deposit(proposer, 0); + } + + function test_PauseAllowsDepositsAndWithdrawalRequests() public { + address funder = makeAddr("paused-funder"); + address beneficiary = makeAddr("paused-beneficiary"); + bondToken.mint(funder, TOKEN_UNIT); + vm.prank(funder); + bondToken.approve(address(bondVault), TOKEN_UNIT); + systemConfig.setPaused(true); + + vm.prank(funder); + bondVault.deposit(beneficiary, TOKEN_UNIT); + vm.prank(proposer); + bondVault.requestWithdrawal(TOKEN_UNIT); + + assertEq(bondVault.availableBalance(beneficiary), TOKEN_UNIT); + assertEq(bondVault.availableBalance(proposer), 99 * TOKEN_UNIT); + (uint256 pending,) = bondVault.withdrawals(proposer); + assertEq(pending, TOKEN_UNIT); + } + + function test_Create_LocksProposerBondFromAvailableBalance() public { + MultiProofGame game = _proposeAtAnchor(); + + assertEq(game.gameCreator(), proposer); + assertEq(bondVault.availableBalance(proposer), 99 * TOKEN_UNIT); + assertEq(bondToken.balanceOf(proposer), 0); + assertEq(bondToken.allowance(proposer, address(bondVault)), 0); + assertEq(bondToken.balanceOf(address(bondVault)), 200 * TOKEN_UNIT); + + (uint256 proposerBond_, uint256 challengerBond_, bool settled_) = bondVault.gameBonds(address(game)); + assertEq(proposerBond_, PROPOSER_BOND); + assertEq(challengerBond_, 0); + assertFalse(settled_); + } + + function test_Create_RevertsWithoutAvailableBalance() public { + address unfunded = makeAddr("unfunded-proposer"); + bondToken.mint(unfunded, PROPOSER_BOND); + vm.prank(unfunded); + bondToken.approve(address(bondVault), PROPOSER_BOND); + + uint256 target = STARTING_ANCHOR_BLOCK + BLOCK_INTERVAL; + Claim claim = Claim.wrap(_rootClaimFor(target)); + bytes memory extraData = _extraData(target, type(uint256).max, 0); + + vm.prank(unfunded); + vm.expectRevert(abi.encodeWithSelector(InsufficientBalance.selector, unfunded, 0, PROPOSER_BOND)); + dgf.create(WC_GAME_TYPE, claim, extraData); + } + + function test_Create_RejectsNonzeroFactoryEthBond() public { + dgf.setInitBond(WC_GAME_TYPE, 1); + uint256 target = STARTING_ANCHOR_BLOCK + BLOCK_INTERVAL; + Claim claim = Claim.wrap(_rootClaimFor(target)); + bytes memory extraData = _extraData(target, type(uint256).max, 0); + + vm.deal(proposer, 1); + vm.prank(proposer); + vm.expectRevert(IncorrectBondAmount.selector); + dgf.create{value: 1}(WC_GAME_TYPE, claim, extraData); + } + + function test_Create_RejectsDivergedFactoryAndVaultOwners() public { + address newFactoryOwner = makeAddr("new-factory-owner"); + dgf.transferOwnership(newFactoryOwner); + + uint256 target = STARTING_ANCHOR_BLOCK + BLOCK_INTERVAL; + Claim claim = Claim.wrap(_rootClaimFor(target)); + bytes memory extraData = _extraData(target, type(uint256).max, 0); + + vm.prank(proposer); + vm.expectRevert(abi.encodeWithSelector(OwnerMismatch.selector, newFactoryOwner, address(this))); + dgf.create(WC_GAME_TYPE, claim, extraData); + } + + function test_LockProposerBond_RejectsNonFactoryClone() public { + ImpersonatingGameHarness impersonator = new ImpersonatingGameHarness(dgf, bondVault, proposer); + + vm.expectRevert(); + impersonator.lock(); + assertEq(bondVault.availableBalance(proposer), 100 * TOKEN_UNIT); + } + + function test_LockChallengerBond_RejectsUnregisteredGame() public { + UnregisteredGameHarness game = new UnregisteredGameHarness(); + + vm.prank(address(game)); + vm.expectRevert(abi.encodeWithSelector(GameNotRegistered.selector, address(game))); + bondVault.lockChallengerBond(); + } + + function test_Settlement_DelayedWithdrawalTransfersBondToken() public { + MultiProofGame game = _proposeAtAnchor(); + _resolveUnchallenged(game); + _passAirgap(game); + game.closeGame(); + + assertEq(bondVault.availableBalance(proposer), 100 * TOKEN_UNIT); + + vm.prank(proposer); + bondVault.requestWithdrawal(PROPOSER_BOND); + assertEq(bondVault.availableBalance(proposer), 99 * TOKEN_UNIT); + + vm.warp(block.timestamp + ERC20_WITHDRAWAL_DELAY_SECONDS); + vm.prank(proposer); + bondVault.withdraw(PROPOSER_BOND); + + assertEq(bondToken.balanceOf(proposer), PROPOSER_BOND); + assertEq(bondVault.availableBalance(proposer), 99 * TOKEN_UNIT); + assertEq(bondToken.balanceOf(address(bondVault)), 199 * TOKEN_UNIT); + } + + function test_WithdrawalRequestResetsDelayAndPauseOnlyBlocksTransfer() public { + MultiProofGame game = _proposeAtAnchor(); + _resolveUnchallenged(game); + _passAirgap(game); + game.closeGame(); + + vm.prank(proposer); + bondVault.requestWithdrawal(PROPOSER_BOND / 2); + vm.warp(block.timestamp + ERC20_WITHDRAWAL_DELAY_SECONDS - 1); + + vm.prank(proposer); + bondVault.requestWithdrawal(PROPOSER_BOND / 4); + (, uint256 resetAt) = bondVault.withdrawals(proposer); + vm.warp(block.timestamp + 1); + vm.prank(proposer); + vm.expectRevert( + abi.encodeWithSelector(WithdrawalDelayNotMet.selector, resetAt + ERC20_WITHDRAWAL_DELAY_SECONDS) + ); + bondVault.withdraw(PROPOSER_BOND / 4); + + vm.warp(block.timestamp + ERC20_WITHDRAWAL_DELAY_SECONDS - 1); + systemConfig.setPaused(true); + vm.prank(proposer); + vm.expectRevert(WithdrawalPaused.selector); + bondVault.withdraw(PROPOSER_BOND / 4); + + systemConfig.setPaused(false); + vm.prank(proposer); + bondVault.withdraw(PROPOSER_BOND / 4); + (uint256 pending,) = bondVault.withdrawals(proposer); + assertEq(pending, PROPOSER_BOND / 2); + } + + function test_RegisteredOldImplementationCanSettleAfterReplacement() public { + MultiProofGame game = _proposeAtAnchor(); + MultiProofGame replacement = new MultiProofGame(_gameConfig()); + dgf.setImplementation(WC_GAME_TYPE, IDisputeGame(address(replacement)), hex""); + + _resolveUnchallenged(game); + _passAirgap(game); + game.closeGame(); + + (,, bool settled) = bondVault.gameBonds(address(game)); + assertTrue(settled); + assertEq(bondVault.availableBalance(proposer), 100 * TOKEN_UNIT); + } + + function test_SettledBondIsImmediatelyReusableForNextProposal() public { + MultiProofGame first = _proposeAtAnchor(); + _resolveUnchallenged(first); + _passAirgap(first); + first.closeGame(); + + MultiProofGame second = _proposeChild(0); + + assertEq(bondVault.availableBalance(proposer), 99 * TOKEN_UNIT); + assertEq(bondToken.balanceOf(proposer), 0); + assertEq(bondToken.allowance(proposer, address(bondVault)), 0); + (uint256 proposerBond_,,) = bondVault.gameBonds(address(second)); + assertEq(proposerBond_, PROPOSER_BOND); + } + + function test_OverlappingParticipantRolesSettleOnce() public { + MultiProofGame game = _proposeAtAnchor(); + vm.prank(proposer); + game.challenge(); + bytes memory proof = abi.encodePacked(game.rootId()); + game.submitProofLane(_compact(0, proposer, proof)); + game.submitProofLane(_compact(1, proposer, proof)); + game.resolve(); + + _passAirgap(game); + game.closeGame(); + + assertEq(bondVault.availableBalance(proposer), 100 * TOKEN_UNIT); + } + + function test_Settle_RejectsUnregisteredGame() public { + UnregisteredGameHarness game = new UnregisteredGameHarness(); + IERC20StakingVault.Payout[] memory payouts = new IERC20StakingVault.Payout[](0); + + vm.prank(address(game)); + vm.expectRevert(abi.encodeWithSelector(GameNotRegistered.selector, address(game))); + bondVault.settle(payouts); + } + + function test_Settle_RejectsInvalidPayoutTotal() public { + MultiProofGame game = _proposeAtAnchor(); + IERC20StakingVault.Payout[] memory payouts = new IERC20StakingVault.Payout[](1); + payouts[0] = IERC20StakingVault.Payout({recipient: proposer, amount: PROPOSER_BOND - 1}); + + vm.prank(address(game)); + vm.expectRevert(abi.encodeWithSelector(InvalidPayoutTotal.selector, PROPOSER_BOND, PROPOSER_BOND - 1)); + bondVault.settle(payouts); + } + + function test_Settle_RejectsSecondSettlement() public { + MultiProofGame game = _proposeAtAnchor(); + IERC20StakingVault.Payout[] memory payouts = new IERC20StakingVault.Payout[](1); + payouts[0] = IERC20StakingVault.Payout({recipient: proposer, amount: PROPOSER_BOND}); + + vm.prank(address(game)); + bondVault.settle(payouts); + + vm.prank(address(game)); + vm.expectRevert(abi.encodeWithSelector(GameAlreadySettled.selector, address(game))); + bondVault.settle(payouts); + } +} diff --git a/pkg/contracts/test/dispute/FundProofBondAccounts.t.sol b/pkg/contracts/test/dispute/FundProofBondAccounts.t.sol new file mode 100644 index 000000000..4f96740dc --- /dev/null +++ b/pkg/contracts/test/dispute/FundProofBondAccounts.t.sol @@ -0,0 +1,119 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.28; + +import {FundProofBondAccounts} from "../../scripts/devnet/FundProofBondAccounts.s.sol"; +import {IERC20StakingVault} from "../../src/dispute/interfaces/IERC20StakingVault.sol"; +import {OPStackFixtures} from "./OPStackFixtures.sol"; +import {MockBondToken} from "../mocks/MockBondToken.sol"; + +contract FundProofBondAccountsHarness is FundProofBondAccounts { + function validate(address[] memory accounts, uint256 target) external pure { + _validate(accounts, target); + } + + function fund(MockBondToken token, IERC20StakingVault vault, address[] memory accounts, uint256 target) external { + _validate(accounts, target); + _fundAccounts(token, vault, address(this), accounts, target); + } +} + +contract FundProofBondAccountsTest is OPStackFixtures { + uint256 internal constant FUNDING_KEY = 0xF00D; + uint256 internal constant TARGET = 10_000e18; + + FundProofBondAccountsHarness internal funding; + address internal first = makeAddr("first-bond-account"); + address internal second = makeAddr("second-bond-account"); + + function setUp() public override { + super.setUp(); + funding = new FundProofBondAccountsHarness(); + } + + function test_run_topsEachAccountUpToTarget() public { + uint256 existing = 2_000e18; + bondToken.mint(address(this), existing); + bondToken.approve(address(bondVault), existing); + bondVault.deposit(first, existing); + _setAccounts(first, second); + vm.setEnv("PRIVATE_KEY", vm.toString(FUNDING_KEY)); + vm.setEnv("ERC20_STAKING_VAULT", vm.toString(address(bondVault))); + vm.setEnv("VAULT_BALANCE_TARGET", vm.toString(TARGET)); + + uint256 supplyBefore = bondToken.totalSupply(); + funding.run(); + + assertEq(bondVault.availableBalance(first), TARGET); + assertEq(bondVault.availableBalance(second), TARGET); + assertEq(bondToken.totalSupply() - supplyBefore, TARGET * 2 - existing); + assertEq(bondToken.balanceOf(vm.addr(FUNDING_KEY)), 0); + assertEq(bondToken.allowance(vm.addr(FUNDING_KEY), address(bondVault)), 0); + } + + function test_fund_isIdempotent() public { + address[] memory accounts = _accounts(first, second); + funding.fund(bondToken, bondVault, accounts, TARGET); + uint256 supplyAfterFirstRun = bondToken.totalSupply(); + uint256 vaultBalanceAfterFirstRun = bondToken.balanceOf(address(bondVault)); + + funding.fund(bondToken, bondVault, accounts, TARGET); + + assertEq(bondToken.totalSupply(), supplyAfterFirstRun); + assertEq(bondToken.balanceOf(address(bondVault)), vaultBalanceAfterFirstRun); + assertEq(bondVault.availableBalance(first), TARGET); + assertEq(bondVault.availableBalance(second), TARGET); + } + + function test_fund_targetsAvailableBalanceWithoutCountingLockedBonds() public { + _proposeAtAnchor(); + address[] memory accounts = new address[](1); + accounts[0] = proposer; + + funding.fund(bondToken, bondVault, accounts, TARGET); + + assertEq(bondVault.availableBalance(proposer), TARGET); + assertEq(bondToken.balanceOf(address(bondVault)), TARGET + PROPOSER_BOND + 100 * TOKEN_UNIT); + } + + function test_fund_ignoresDuplicateAccountsAfterFirstTopUp() public { + address[] memory accounts = _accounts(first, first); + uint256 supplyBefore = bondToken.totalSupply(); + + funding.fund(bondToken, bondVault, accounts, TARGET); + + assertEq(bondVault.availableBalance(first), TARGET); + assertEq(bondToken.totalSupply() - supplyBefore, TARGET); + } + + function test_validate_rejectsZeroAccount() public { + address[] memory accounts = new address[](2); + accounts[0] = first; + + vm.expectRevert("FundProofBondAccounts: account missing"); + funding.validate(accounts, TARGET); + } + + function test_validate_rejectsEmptyAccounts() public { + address[] memory accounts = new address[](0); + + vm.expectRevert("FundProofBondAccounts: accounts missing"); + funding.validate(accounts, TARGET); + } + + function test_validate_rejectsZeroTarget() public { + address[] memory accounts = _accounts(first, second); + + vm.expectRevert("FundProofBondAccounts: target missing"); + funding.validate(accounts, 0); + } + + function _setAccounts(address account0, address account1) internal { + vm.setEnv("BOND_ACCOUNTS", string.concat(vm.toString(account0), ",", vm.toString(account1))); + } + + function _accounts(address account0, address account1) internal pure returns (address[] memory accounts) { + accounts = new address[](2); + accounts[0] = account0; + accounts[1] = account1; + } +} diff --git a/pkg/contracts/test/dispute/Governance.t.sol b/pkg/contracts/test/dispute/Governance.t.sol new file mode 100644 index 000000000..d47519043 --- /dev/null +++ b/pkg/contracts/test/dispute/Governance.t.sol @@ -0,0 +1,484 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.28; + +import {Governance, CheckGovernance} from "../../scripts/devnet/Governance.s.sol"; +import {DeployCouncilSafe} from "../../scripts/devnet/DeployCouncilSafe.s.sol"; +import {DeployProofSystem} from "../../scripts/devnet/DeployProofSystem.s.sol"; +import {ActivateProofSystem} from "../../scripts/devnet/ActivateProofSystem.s.sol"; +import {SubmitSecurityCouncilProof} from "../../scripts/devnet/SubmitSecurityCouncilProof.s.sol"; +import {OPStackFixtures} from "./OPStackFixtures.sol"; +import {MultiProofGame} from "../../src/dispute/MultiProofGame.sol"; +import {IMultiProofGame} from "../../src/dispute/interfaces/IMultiProofGame.sol"; +import {SecurityCouncilVerifier} from "../../src/dispute/council/SecurityCouncilVerifier.sol"; +import {ISystemConfig} from "@optimism-bedrock/interfaces/L1/ISystemConfig.sol"; +import {IDisputeGame} from "@optimism-bedrock/interfaces/dispute/IDisputeGame.sol"; +import {Bitmap} from "../../src/dispute/lib/LibProof.sol"; +import {GameType} from "@optimism-bedrock/src/dispute/lib/Types.sol"; +import {Safe} from "@safe-global/safe-contracts/contracts/Safe.sol"; +import {Enum} from "@safe-global/safe-contracts/contracts/common/Enum.sol"; + +abstract contract TestGovernanceConfig is Governance { + bool internal safeMode; + address internal safeAddress; + uint256 internal firstKey = 0xA11CE; + uint256 internal secondKey = 0xB0B; + string internal safeTxOut; + + function configure(bool mode, address account, uint256 first, uint256 second) public { + safeMode = mode; + safeAddress = account; + firstKey = first; + secondKey = second; + } + + function setSafeTxOut(string memory path) public { + safeTxOut = path; + } + + // Process-wide environment mutations race between parallel Forge tests. + function _safeTxOut() internal view virtual override returns (string memory) { + return safeTxOut; + } + + function _safeMode() internal view virtual override returns (bool) { + return safeMode; + } + + function _safeAddress() internal view virtual override returns (address) { + return safeAddress; + } + + function _signerKeys() internal view virtual override returns (uint256, uint256) { + return (firstKey, secondKey); + } + + function _relayerKey() internal pure virtual override returns (uint256) { + return 0xCAFE; + } +} + +contract CouncilDeploymentHarness is DeployCouncilSafe, TestGovernanceConfig { + function _safeTxOut() internal view override(Governance, TestGovernanceConfig) returns (string memory) { + return safeTxOut; + } + + function _safeMode() internal view override(Governance, TestGovernanceConfig) returns (bool) { + return safeMode; + } + + function _safeAddress() internal view override(Governance, TestGovernanceConfig) returns (address) { + return safeAddress; + } + + function _signerKeys() internal view override(Governance, TestGovernanceConfig) returns (uint256, uint256) { + return (firstKey, secondKey); + } + + function _relayerKey() internal pure override(Governance, TestGovernanceConfig) returns (uint256) { + return 0xCAFE; + } +} + +contract CouncilSubmissionHarness is SubmitSecurityCouncilProof, TestGovernanceConfig { + function _safeTxOut() internal view override(Governance, TestGovernanceConfig) returns (string memory) { + return safeTxOut; + } + + function _safeMode() internal view override(Governance, TestGovernanceConfig) returns (bool) { + return safeMode; + } + + function _safeAddress() internal view override(Governance, TestGovernanceConfig) returns (address) { + return safeAddress; + } + + function _signerKeys() internal view override(Governance, TestGovernanceConfig) returns (uint256, uint256) { + return (firstKey, secondKey); + } + + function _relayerKey() internal pure override(Governance, TestGovernanceConfig) returns (uint256) { + return 0xCAFE; + } +} + +contract SafeDeploymentHarness is DeployProofSystem, TestGovernanceConfig { + function _safeTxOut() internal view override(Governance, TestGovernanceConfig) returns (string memory) { + return safeTxOut; + } + + function _safeMode() internal view override(Governance, TestGovernanceConfig) returns (bool) { + return safeMode; + } + + function _safeAddress() internal view override(Governance, TestGovernanceConfig) returns (address) { + return safeAddress; + } + + function _signerKeys() internal view override(Governance, TestGovernanceConfig) returns (uint256, uint256) { + return (firstKey, secondKey); + } + + function _relayerKey() internal pure override(Governance, TestGovernanceConfig) returns (uint256) { + return 0xCAFE; + } + + Config internal config; + + function setConfig(Config memory value) external { + config = value; + } + + function _readConfig() internal view virtual override returns (Config memory) { + return config; + } +} + +contract SafeActivationHarness is ActivateProofSystem, TestGovernanceConfig { + function _safeTxOut() internal view override(Governance, TestGovernanceConfig) returns (string memory) { + return safeTxOut; + } + + function _safeMode() internal view override(Governance, TestGovernanceConfig) returns (bool) { + return safeMode; + } + + function _safeAddress() internal view override(Governance, TestGovernanceConfig) returns (address) { + return safeAddress; + } + + function _signerKeys() internal view override(Governance, TestGovernanceConfig) returns (uint256, uint256) { + return (firstKey, secondKey); + } + + function _relayerKey() internal pure override(Governance, TestGovernanceConfig) returns (uint256) { + return 0xCAFE; + } + + Config internal config; + + function setConfig(Config memory value) external { + config = value; + } + + function _readConfig() internal view virtual override returns (Config memory) { + return config; + } +} + +contract GovernanceHarness is TestGovernanceConfig { + function execute(uint256 key, address target, bytes calldata data) external { + _executeGovernance(key, target, data); + } + + function signatures(bytes32 digest) external view returns (bytes memory) { + return _safeSignatures(digest); + } + + function fail() external pure { + revert("deliberate failure"); + } +} + +contract GovernanceTest is OPStackFixtures { + uint256 internal constant FIRST_KEY = 0xA11CE; + uint256 internal constant SECOND_KEY = 0xB0B; + uint256 internal constant RELAYER_KEY = 0xCAFE; + GovernanceHarness internal executor; + Safe internal safe; + SecurityCouncilVerifier internal council; + + function setUp() public override { + super.setUp(); + executor = new GovernanceHarness(); + vm.setEnv("COUNCIL_SIGNATURES", ""); + vm.setEnv("PRIVATE_KEY", vm.toString(RELAYER_KEY)); + vm.setEnv("COUNCIL_DEPLOYMENT_OUT", ""); + CouncilDeploymentHarness deployer = new CouncilDeploymentHarness(); + deployer.configure(true, address(0), FIRST_KEY, SECOND_KEY); + DeployCouncilSafe.Deployment memory deployed = deployer.run(); + safe = deployed.councilSafe; + council = deployed.verifier; + executor.configure(true, address(safe), FIRST_KEY, SECOND_KEY); + dgf.transferOwnership(address(safe)); + proxyAdmin.transferOwnership(address(safe)); + systemConfig.setGuardian(address(safe)); + } + + function test_safeSignsInOwnerOrderAndExecutes() public { + executor.execute( + 0, address(dgf), abi.encodeWithSignature("setInitBond(uint32,uint256)", uint32(1), uint256(42)) + ); + assertEq(dgf.initBonds(GameType.wrap(1)), 42); + assertEq(safe.nonce(), 1); + } + + function test_safeExecutesWithReversedSignerConfiguration() public { + executor.configure(true, address(safe), SECOND_KEY, FIRST_KEY); + executor.execute( + 0, address(dgf), abi.encodeWithSignature("setInitBond(uint32,uint256)", uint32(1), uint256(42)) + ); + assertEq(dgf.initBonds(GameType.wrap(1)), 42); + } + + function test_environmentSafeConfigurationAndCouncilCheck() public { + vm.setEnv("GOVERNANCE_MODE", "safe"); + vm.setEnv("GOVERNANCE_SAFE", vm.toString(address(safe))); + vm.setEnv("GOVERNANCE_SIGNER_1_PRIVATE_KEY", ""); + vm.setEnv("GOVERNANCE_SIGNER_2_PRIVATE_KEY", ""); + vm.setEnv("SECURITY_COUNCIL_VERIFIER", vm.toString(address(council))); + CheckGovernance checker = new CheckGovernance(); + checker.run(); + vm.setEnv("GOVERNANCE_MODE", "invalid"); + vm.expectRevert("Governance: invalid mode"); + checker.run(); + vm.setEnv("GOVERNANCE_MODE", "eoa"); + } + + function test_preparesSafeCallsWithoutKeysOrExecution() public { + executor.setSafeTxOut("cache/governance-test.safe.json"); + executor.configure(true, address(safe), 0, 0); + bytes memory data = abi.encodeWithSignature("setInitBond(uint32,uint256)", uint32(1), uint256(42)); + uint256 beforeBond = dgf.initBonds(GameType.wrap(1)); + executor.execute(0, address(dgf), data); + executor.execute(0, address(dgf), data); + string memory json = vm.readFile("cache/governance-test.safe.json"); + assertEq(vm.parseJsonString(json, ".chainId"), vm.toString(block.chainid)); + assertEq(vm.parseJsonAddress(json, ".meta.createdFromSafeAddress"), address(safe)); + assertEq(vm.parseJsonAddress(json, ".transactions[0].to"), address(dgf)); + assertEq(vm.parseJsonBytes(json, ".transactions[1].data"), data); + assertEq(dgf.initBonds(GameType.wrap(1)), beforeBond); + assertEq(safe.nonce(), 0); + executor.setSafeTxOut(""); + } + + function test_reusesCouncilSafeWithoutSignerKeys() public { + CouncilDeploymentHarness deployer = new CouncilDeploymentHarness(); + deployer.configure(true, address(safe), 0, 0); + DeployCouncilSafe.Deployment memory deployed = deployer.run(); + assertEq(address(deployed.councilSafe), address(safe)); + assertEq(deployed.verifier.council(), address(safe)); + assertEq(safe.nonce(), 0); + } + + function test_safeVaultAndActivationApprovalCheckpoints() public { + vm.prank(address(safe)); + dgf.setImplementation(WC_GAME_TYPE, IDisputeGame(address(0))); + vm.prank(address(safe)); + asr.setRespectedGameType(GameType.wrap(1)); + SafeDeploymentHarness deployer = new SafeDeploymentHarness(); + deployer.configure(true, address(safe), 0, 0); + DeployProofSystem.Config memory config = _deploymentConfig(); + deployer.setConfig(config); + deployer.setSafeTxOut("cache/vault-test.safe.json"); + DeployProofSystem.Deployment memory deployed = deployer.run(); + assertEq(address(deployed.gameImpl), address(0)); + assertEq(safe.nonce(), 0); + string memory vaultJson = vm.readFile("cache/vault-test.safe.json"); + deployer.setSafeTxOut(""); + executor.execute( + 0, + vm.parseJsonAddress(vaultJson, ".transactions[0].to"), + vm.parseJsonBytes(vaultJson, ".transactions[0].data") + ); + config.existingBondVault = deployed.bondVault; + deployer.setConfig(config); + deployed = deployer.run(); + assertEq(address(deployed.bondVault.token()), address(bondToken)); + SafeActivationHarness activation = new SafeActivationHarness(); + activation.configure(true, address(safe), 0, 0); + activation.setConfig( + ActivateProofSystem.Config({ + guardianKey: 0, + dgfOwnerKey: 0, + disputeGameFactory: dgf, + anchorStateRegistry: asr, + systemConfig: ISystemConfig(address(systemConfig)), + proxyAdmin: proxyAdmin, + bondToken: bondToken, + gameImplementation: IMultiProofGame(address(deployed.gameImpl)), + requireFreshAnchor: true + }) + ); + activation.setSafeTxOut("cache/activation-test.safe.json"); + activation.run(); + assertEq(address(dgf.gameImpls(WC_GAME_TYPE)), address(0)); + assertEq(asr.respectedGameType().raw(), 1); + assertEq(safe.nonce(), 1); + string memory activationJson = vm.readFile("cache/activation-test.safe.json"); + activation.setSafeTxOut(""); + for (uint256 i; i < 3; i++) { + string memory prefix = string.concat(".transactions[", vm.toString(i), "]"); + executor.execute( + 0, + vm.parseJsonAddress(activationJson, string.concat(prefix, ".to")), + vm.parseJsonBytes(activationJson, string.concat(prefix, ".data")) + ); + } + assertEq(address(dgf.gameImpls(WC_GAME_TYPE)), address(deployed.gameImpl)); + assertEq(asr.respectedGameType().raw(), 1006); + assertEq(safe.nonce(), 4); + } + + function test_safeRejectsDuplicateSigners() public { + executor.configure(true, address(safe), FIRST_KEY, FIRST_KEY); + vm.expectRevert("Governance: two distinct keys required"); + executor.execute(0, address(dgf), hex"1234"); + } + + function test_safeRejectsNonOwnerSigner() public { + executor.configure(true, address(safe), FIRST_KEY, RELAYER_KEY); + vm.expectRevert("Governance: signer mismatch"); + executor.execute(0, address(dgf), hex"1234"); + } + + function test_safeRejectsThresholdChange() public { + vm.prank(address(safe)); + safe.changeThreshold(1); + vm.expectRevert("Governance: expected 2-of-2 Safe"); + executor.execute(0, address(dgf), hex"1234"); + } + + function test_safeRejectsModules() public { + vm.prank(address(safe)); + safe.enableModule(vm.addr(RELAYER_KEY)); + vm.expectRevert("Governance: modules bypass threshold"); + executor.execute(0, address(dgf), hex"1234"); + } + + function test_safeRejectsSingleSignature() public { + bytes memory data = abi.encodeWithSignature("setInitBond(uint32,uint256)", uint32(1), uint256(42)); + bytes32 digest = + safe.getTransactionHash(address(dgf), 0, data, Enum.Operation.Call, 0, 0, 0, address(0), address(0), 0); + (uint8 v, bytes32 r, bytes32 s) = vm.sign(FIRST_KEY, digest); + vm.expectRevert("GS020"); + safe.execTransaction( + address(dgf), + 0, + data, + Enum.Operation.Call, + 0, + 0, + 0, + address(0), + payable(address(0)), + abi.encodePacked(r, s, v) + ); + } + + function test_safeRejectsDirectDeployerAdministration() public { + vm.prank(vm.addr(RELAYER_KEY)); + vm.expectRevert("Ownable: caller is not the owner"); + dgf.setInitBond(WC_GAME_TYPE, 42); + } + + function test_safePropagatesExecutionFailure() public { + vm.expectRevert("GS013"); + executor.execute(0, address(executor), abi.encodeCall(GovernanceHarness.fail, ())); + assertEq(safe.nonce(), 0); + } + + function test_eoaExecutionAndCouncilDefault() public { + vm.setEnv("COUNCIL_OWNERS", vm.toString(vm.addr(FIRST_KEY))); + vm.setEnv("COUNCIL_THRESHOLD", "1"); + executor.configure(false, address(0), FIRST_KEY, SECOND_KEY); + DeployCouncilSafe.Deployment memory deployed = new CouncilDeploymentHarness().run(); + assertEq(deployed.councilSafe.getThreshold(), 1); + assertEq(deployed.councilSafe.getOwners().length, 1); + vm.prank(address(safe)); + dgf.transferOwnership(vm.addr(FIRST_KEY)); + executor.execute( + FIRST_KEY, address(dgf), abi.encodeWithSignature("setInitBond(uint32,uint256)", uint32(1), uint256(42)) + ); + assertEq(dgf.initBonds(GameType.wrap(1)), 42); + } + + function test_eoaPropagatesExecutionFailure() public { + executor.configure(false, address(0), FIRST_KEY, SECOND_KEY); + vm.expectRevert("deliberate failure"); + executor.execute(FIRST_KEY, address(executor), abi.encodeCall(GovernanceHarness.fail, ())); + } + + function test_safeDeploysVaultAndActivates() public { + // Clearing the fixture implementation makes this a first-vault deployment. + vm.prank(address(safe)); + dgf.setImplementation(WC_GAME_TYPE, IDisputeGame(address(0))); + SafeDeploymentHarness deployer = new SafeDeploymentHarness(); + deployer.configure(true, address(safe), FIRST_KEY, SECOND_KEY); + deployer.setConfig(_deploymentConfig()); + DeployProofSystem.Deployment memory deployed = deployer.run(); + assertEq(address(deployed.bondVault.proxyAdmin()), address(proxyAdmin)); + assertEq(address(deployed.bondVault.disputeGameFactory()), address(dgf)); + assertEq(address(deployed.bondVault.systemConfig()), address(systemConfig)); + assertEq(address(deployed.bondVault.token()), address(bondToken)); + vm.prank(address(safe)); + asr.setRespectedGameType(GameType.wrap(1)); + uint64 retirement = asr.retirementTimestamp(); + SafeActivationHarness activation = new SafeActivationHarness(); + activation.configure(true, address(safe), FIRST_KEY, SECOND_KEY); + activation.setConfig( + ActivateProofSystem.Config({ + guardianKey: 0, + dgfOwnerKey: 0, + disputeGameFactory: dgf, + anchorStateRegistry: asr, + systemConfig: ISystemConfig(address(systemConfig)), + proxyAdmin: proxyAdmin, + bondToken: bondToken, + gameImplementation: IMultiProofGame(address(deployed.gameImpl)), + requireFreshAnchor: true + }) + ); + activation.run(); + assertEq(address(dgf.gameImpls(WC_GAME_TYPE)), address(deployed.gameImpl)); + assertEq(dgf.initBonds(WC_GAME_TYPE), 0); + assertEq(asr.respectedGameType().raw(), WC_GAME_TYPE.raw()); + assertEq(asr.retirementTimestamp(), retirement); + assertEq(safe.nonce(), 4); + } + + function test_sharedSafeSubmitsCouncilProof() public { + IMultiProofGame.GameConfig memory config = _gameConfig(); + config.securityCouncil = council; + gameImpl = new MultiProofGame(config); + vm.prank(address(safe)); + dgf.setImplementation(WC_GAME_TYPE, gameImpl); + MultiProofGame game = _proposeAtAnchor(); + vm.setEnv("GAME_ADDRESS", vm.toString(address(game))); + CouncilSubmissionHarness submission = new CouncilSubmissionHarness(); + submission.configure(true, address(safe), FIRST_KEY, SECOND_KEY); + bytes32 messageHash = council.attestationDigest(game.rootId()); + (bool success, bytes memory result) = + address(safe).staticcall(abi.encodeWithSignature("getMessageHash(bytes)", abi.encode(messageHash))); + assertTrue(success); + vm.setEnv("COUNCIL_SIGNATURES", vm.toString(executor.signatures(abi.decode(result, (bytes32))))); + submission.configure(true, address(safe), 0, 0); + submission.run(); + assertEq(Bitmap.unwrap(game.proofBitmap()), 4); + vm.setEnv("COUNCIL_SIGNATURES", ""); + } + + function _deploymentConfig() internal view returns (DeployProofSystem.Config memory config) { + config.privateKey = RELAYER_KEY; + config.l2ChainId = CHAIN_ID; + config.rollupConfigHash = ROLLUP_CONFIG_HASH; + config.blockInterval = BLOCK_INTERVAL; + config.challengePeriod = CHALLENGE_PERIOD; + config.proofPeriod = PROOF_PERIOD; + config.proposerBond = PROPOSER_BOND; + config.challengerBond = CHALLENGER_BOND; + config.proofThreshold = PROOF_THRESHOLD; + config.protocolFeeRecipient = protocolFeeRecipient; + config.aggregationVKey = AGGREGATION_VKEY; + config.rangeVKeyCommitment = RANGE_VKEY_COMMITMENT; + config.teeImageId = TEE_IMAGE_ID; + config.validityProofVerifier = validityVerifier; + config.teeVerifier = teeVerifier; + config.securityCouncil = council; + config.disputeGameFactory = dgf; + config.anchorStateRegistry = asr; + config.systemConfig = ISystemConfig(address(systemConfig)); + config.proxyAdmin = proxyAdmin; + config.bondToken = bondToken; + config.erc20WithdrawalDelay = ERC20_WITHDRAWAL_DELAY_SECONDS; + } +} diff --git a/pkg/contracts/test/dispute/MultiProofGame.t.sol b/pkg/contracts/test/dispute/MultiProofGame.t.sol index 3f9fe8bf6..2135fe486 100644 --- a/pkg/contracts/test/dispute/MultiProofGame.t.sol +++ b/pkg/contracts/test/dispute/MultiProofGame.t.sol @@ -4,6 +4,7 @@ pragma solidity 0.8.28; import {OPStackFixtures} from "./OPStackFixtures.sol"; import {MultiProofGame} from "../../src/dispute/MultiProofGame.sol"; import {IMultiProofGame} from "../../src/dispute/interfaces/IMultiProofGame.sol"; +import {OwnerMismatch} from "../../src/dispute/lib/Errors.sol"; import {LibProof, InvalidationReason, ProofLane, TransitionPublicValues} from "../../src/dispute/lib/LibProof.sol"; import { @@ -21,7 +22,6 @@ import { GameNotOver, GameOver, GamePaused, - IncorrectBondAmount, InvalidParentGame, ParentGameNotResolved } from "@optimism-bedrock/src/dispute/lib/Errors.sol"; @@ -48,60 +48,61 @@ contract MultiProofGameTest is OPStackFixtures { (IDisputeGame registered,) = dgf.games(gameType_, rootClaim_, extraData_); assertEq(address(registered), address(game)); assertTrue(asr.isGameRegistered(IDisputeGame(address(game)))); - assertEq(weth.balanceOf(address(game)), PROPOSER_BOND); + (uint256 proposerBond_, uint256 challengerBond_, bool settled_) = bondVault.gameBonds(address(game)); + assertEq(proposerBond_, PROPOSER_BOND); + assertEq(challengerBond_, 0); + assertFalse(settled_); assertEq(game.proofBitmap().raw(), 0); } function test_Create_RejectsMalformedExtraData() public { uint256 target = STARTING_ANCHOR_BLOCK + BLOCK_INTERVAL; + Claim claim = Claim.wrap(_rootClaimFor(target)); + bytes memory shortExtraData = abi.encode(target, address(asr)); vm.prank(proposer); vm.expectRevert(BadExtraData.selector); - dgf.create{value: PROPOSER_BOND}( - WC_GAME_TYPE, Claim.wrap(_rootClaimFor(target)), abi.encode(target, address(asr)) - ); + dgf.create(WC_GAME_TYPE, claim, shortExtraData); uint256 malformedParent = uint256(uint160(address(asr))) | (uint256(1) << 160); bytes memory extraData = abi.encode(_domainHash(), target, malformedParent, uint256(0)); vm.prank(proposer); vm.expectRevert(BadExtraData.selector); - dgf.create{value: PROPOSER_BOND}(WC_GAME_TYPE, Claim.wrap(_rootClaimFor(target)), extraData); + dgf.create(WC_GAME_TYPE, claim, extraData); } function test_Create_RejectsWrongDomainAndBlockInterval() public { uint256 target = STARTING_ANCHOR_BLOCK + BLOCK_INTERVAL; bytes32 wrongDomain = keccak256("wrong-domain"); + Claim claim = Claim.wrap(_rootClaimFor(target)); + bytes memory wrongDomainExtraData = abi.encode(wrongDomain, target, address(asr), uint256(0)); vm.prank(proposer); vm.expectRevert( abi.encodeWithSelector(IMultiProofGame.InvalidDomainHash.selector, gameImpl.domainHash(), wrongDomain) ); - dgf.create{value: PROPOSER_BOND}( - WC_GAME_TYPE, Claim.wrap(_rootClaimFor(target)), abi.encode(wrongDomain, target, address(asr), uint256(0)) - ); + dgf.create(WC_GAME_TYPE, claim, wrongDomainExtraData); uint256[4] memory wrongTargets = [STARTING_ANCHOR_BLOCK, STARTING_ANCHOR_BLOCK - 1, STARTING_ANCHOR_BLOCK + 1, target + 1]; for (uint256 i = 0; i < wrongTargets.length; i++) { + Claim wrongClaim = Claim.wrap(_rootClaimFor(wrongTargets[i])); + bytes memory wrongExtraData = _extraData(wrongTargets[i], type(uint256).max, 0); vm.prank(proposer); vm.expectRevert( abi.encodeWithSelector(IMultiProofGame.InvalidL2BlockNumber.selector, target, wrongTargets[i]) ); - dgf.create{value: PROPOSER_BOND}( - WC_GAME_TYPE, - Claim.wrap(_rootClaimFor(wrongTargets[i])), - _extraData(wrongTargets[i], type(uint256).max, 0) - ); + dgf.create(WC_GAME_TYPE, wrongClaim, wrongExtraData); } } function test_Create_RejectsUnregisteredAndBlacklistedParents() public { uint256 target = STARTING_ANCHOR_BLOCK + BLOCK_INTERVAL; + Claim claim = Claim.wrap(_rootClaimFor(target)); + bytes memory unknownParentExtraData = _extraDataForParent(target, makeAddr("unknown-parent"), 0); vm.prank(proposer); vm.expectRevert(); - dgf.create{value: PROPOSER_BOND}( - WC_GAME_TYPE, Claim.wrap(_rootClaimFor(target)), _extraDataForParent(target, makeAddr("unknown-parent"), 0) - ); + dgf.create(WC_GAME_TYPE, claim, unknownParentExtraData); MultiProofGame parent = _proposeAtAnchor(); vm.prank(guardian); @@ -109,28 +110,10 @@ contract MultiProofGameTest is OPStackFixtures { uint256 childTarget = parent.l2SequenceNumber() + BLOCK_INTERVAL; bytes memory childExtraData = _extraData(childTarget, 0, 0); + Claim childClaim = Claim.wrap(_rootClaimFor(childTarget)); vm.prank(proposer); vm.expectRevert(InvalidParentGame.selector); - dgf.create{value: PROPOSER_BOND}(WC_GAME_TYPE, Claim.wrap(_rootClaimFor(childTarget)), childExtraData); - } - - function test_Create_RejectsParentFromAnotherGameType() public { - GameType otherType = GameType.wrap(43); - MultiProofGame otherImpl = new MultiProofGame(_gameConfig()); - dgf.setImplementation(otherType, IDisputeGame(address(otherImpl)), hex""); - dgf.setInitBond(otherType, PROPOSER_BOND); - - uint256 target = STARTING_ANCHOR_BLOCK + BLOCK_INTERVAL; - vm.prank(proposer); - dgf.create{value: PROPOSER_BOND}( - otherType, Claim.wrap(_rootClaimFor(target)), _extraData(target, type(uint256).max, 0) - ); - - uint256 childTarget = target + BLOCK_INTERVAL; - bytes memory childExtraData = _extraData(childTarget, 0, 0); - vm.prank(proposer); - vm.expectRevert(); - dgf.create{value: PROPOSER_BOND}(WC_GAME_TYPE, Claim.wrap(_rootClaimFor(childTarget)), childExtraData); + dgf.create(WC_GAME_TYPE, childClaim, childExtraData); } function test_Create_UsesPreviousAnchorGameAfterAnchorAdvances() public { @@ -141,14 +124,10 @@ contract MultiProofGameTest is OPStackFixtures { uint256 target = parent.l2SequenceNumber() + BLOCK_INTERVAL; bytes memory previousAnchorParentExtraData = _extraData(target, 0, 0); + Claim claim = Claim.wrap(_rootClaimFor(target)); vm.prank(proposer); - MultiProofGame previousAnchorChild = MultiProofGame( - address( - dgf.create{value: PROPOSER_BOND}( - WC_GAME_TYPE, Claim.wrap(_rootClaimFor(target)), previousAnchorParentExtraData - ) - ) - ); + MultiProofGame previousAnchorChild = + MultiProofGame(address(dgf.create(WC_GAME_TYPE, claim, previousAnchorParentExtraData))); assertEq(previousAnchorChild.parentRef(), address(parent)); assertEq(Hash.unwrap(previousAnchorChild.startingRootHash()), Claim.unwrap(parent.rootClaim())); assertEq(previousAnchorChild.startingBlockNumber(), parent.l2SequenceNumber()); @@ -162,11 +141,11 @@ contract MultiProofGameTest is OPStackFixtures { assertEq(address(asr.anchorGame()), address(parent)); uint256 target = STARTING_ANCHOR_BLOCK + BLOCK_INTERVAL; + Claim claim = Claim.wrap(keccak256("late-bootstrap-root")); + bytes memory extraData = _extraData(target, type(uint256).max, 0); vm.prank(proposer); vm.expectRevert(InvalidParentGame.selector); - dgf.create{value: PROPOSER_BOND}( - WC_GAME_TYPE, Claim.wrap(keccak256("late-bootstrap-root")), _extraData(target, type(uint256).max, 0) - ); + dgf.create(WC_GAME_TYPE, claim, extraData); } function test_Constructor_RejectsInvalidConfiguration() public { @@ -205,6 +184,11 @@ contract MultiProofGameTest is OPStackFixtures { vm.expectRevert(IMultiProofGame.InvalidActivationParameters.selector); new MultiProofGame(config); + config = _gameConfig(); + config.proposerBond = type(uint256).max / gameImpl.CHALLENGER_REWARD_BPS() + 1; + vm.expectRevert(IMultiProofGame.InvalidActivationParameters.selector); + new MultiProofGame(config); + config = _gameConfig(); config.aggregationVKey = bytes32(0); vm.expectRevert(IMultiProofGame.InvalidActivationParameters.selector); @@ -220,14 +204,39 @@ contract MultiProofGameTest is OPStackFixtures { vm.expectRevert(IMultiProofGame.InvalidActivationParameters.selector); new MultiProofGame(config); - // A DelayedWETH wired to a different SystemConfig than the registry's must be rejected. + // A vault wired to a different SystemConfig than the registry's must be rejected. config = _gameConfig(); - vm.mockCall(address(weth), abi.encodeWithSignature("systemConfig()"), abi.encode(address(0xdead))); + vm.mockCall(address(bondVault), abi.encodeWithSignature("systemConfig()"), abi.encode(address(0xdead))); vm.expectRevert(IMultiProofGame.InconsistentSystemConfiguration.selector); new MultiProofGame(config); vm.clearMockedCalls(); } + function test_Create_RejectsTimestampBeyondUint64() public { + (, uint256 anchorBlock) = asr.getAnchorRoot(); + uint256 target = anchorBlock + BLOCK_INTERVAL; + bytes memory extraData = _extraDataForParent(target, address(asr), 0); + + vm.warp(type(uint64).max); + vm.prank(proposer); + vm.expectRevert( + abi.encodeWithSelector( + IMultiProofGame.TimestampOutOfBounds.selector, uint256(type(uint64).max) + uint256(CHALLENGE_PERIOD) + ) + ); + dgf.create(WC_GAME_TYPE, Claim.wrap(_rootClaimFor(target)), extraData); + } + + function test_Constructor_AllowsIndependentBondAmounts() public { + IMultiProofGame.GameConfig memory config = _gameConfig(); + config.challengerBond = CHALLENGER_BOND * 2; + + MultiProofGame implementation = new MultiProofGame(config); + + assertEq(implementation.proposerBond(), PROPOSER_BOND); + assertEq(implementation.challengerBond(), CHALLENGER_BOND * 2); + } + function test_UnchallengedFlow_AnyProofLaneCanFinalize() public { for (uint8 lane; lane < LibProof.PROOF_LANE_COUNT; lane++) { (, uint256 anchorBlock) = asr.getAnchorRoot(); @@ -240,7 +249,7 @@ contract MultiProofGameTest is OPStackFixtures { game.resolve(); assertEq(uint8(game.status()), uint8(GameStatus.DEFENDER_WINS)); - assertEq(game.credit(proposer), PROPOSER_BOND); + assertEq(game.normalModeCredit(proposer), PROPOSER_BOND); } } @@ -294,7 +303,7 @@ contract MultiProofGameTest is OPStackFixtures { game.resolve(); assertEq(uint8(game.status()), uint8(GameStatus.DEFENDER_WINS)); - assertEq(game.credit(proposer), PROPOSER_BOND); + assertEq(game.normalModeCredit(proposer), PROPOSER_BOND); assertLt(block.timestamp, game.challengeDeadline().raw()); } @@ -310,14 +319,11 @@ contract MultiProofGameTest is OPStackFixtures { first.resolve(); assertEq(uint8(first.status()), uint8(GameStatus.CHALLENGER_WINS)); assertEq(uint8(first.invalidationReason()), uint8(InvalidationReason.PROOF_TIMEOUT)); - assertEq(first.credit(protocolFeeRecipient), PROPOSER_BOND); + assertEq(first.normalModeCredit(protocolFeeRecipient), PROPOSER_BOND); _passAirgap(first); - uint256 timeoutRecipientBalance = protocolFeeRecipient.balance; - first.claimCredit(protocolFeeRecipient); - vm.warp(block.timestamp + WETH_DELAY_SECONDS); - first.claimCredit(protocolFeeRecipient); - assertEq(protocolFeeRecipient.balance, timeoutRecipientBalance + PROPOSER_BOND); + first.closeGame(); + assertEq(bondVault.availableBalance(protocolFeeRecipient), PROPOSER_BOND); MultiProofGame retry = _propose(type(uint256).max, Claim.unwrap(first.rootClaim()), first.l2SequenceNumber(), first.attempt() + 1); @@ -332,33 +338,28 @@ contract MultiProofGameTest is OPStackFixtures { game.closeGame(); _passAirgap(game); - uint256 balanceBefore = proposer.balance; address keeper = makeAddr("keeper"); vm.prank(keeper); - game.claimCredit(proposer); - assertEq(game.normalModeCredit(proposer), 0); - assertEq(game.refundModeCredit(proposer), 0); + game.closeGame(); + assertEq(bondVault.availableBalance(proposer), 100 * TOKEN_UNIT); (Hash anchorRoot, uint256 anchorBlock) = asr.getAnchorRoot(); assertEq(Hash.unwrap(anchorRoot), Claim.unwrap(game.rootClaim())); assertEq(anchorBlock, game.l2SequenceNumber()); assertEq(uint8(game.bondDistributionMode()), uint8(BondDistributionMode.NORMAL)); - vm.warp(block.timestamp + WETH_DELAY_SECONDS); - vm.prank(keeper); - game.claimCredit(proposer); - assertEq(proposer.balance, balanceBefore + PROPOSER_BOND); - assertEq(keeper.balance, 0); + assertEq(bondToken.balanceOf(proposer), 0); + assertEq(bondToken.balanceOf(keeper), 0); } function test_Pause_BlocksCreationAndSettlement() public { systemConfig.setPaused(true); uint256 target = STARTING_ANCHOR_BLOCK + BLOCK_INTERVAL; + Claim claim = Claim.wrap(_rootClaimFor(target)); + bytes memory extraData = _extraData(target, type(uint256).max, 0); vm.prank(proposer); vm.expectRevert(GamePaused.selector); - dgf.create{value: PROPOSER_BOND}( - WC_GAME_TYPE, Claim.wrap(_rootClaimFor(target)), _extraData(target, type(uint256).max, 0) - ); + dgf.create(WC_GAME_TYPE, claim, extraData); systemConfig.setPaused(false); MultiProofGame game = _proposeAtAnchor(); @@ -372,18 +373,34 @@ contract MultiProofGameTest is OPStackFixtures { function test_Challenge_RequiresBondAndOpenWindow() public { MultiProofGame game = _proposeAtAnchor(); - vm.prank(challengerAccount); - vm.expectRevert(IncorrectBondAmount.selector); - game.challenge{value: CHALLENGER_BOND - 1}(); + address unfundedChallenger = makeAddr("unfunded-challenger"); + vm.prank(unfundedChallenger); + vm.expectRevert(); + game.challenge(); _challenge(game); assertEq(game.proofBitmap().raw(), 0); assertEq(game.refundModeCredit(challengerAccount), CHALLENGER_BOND); - assertEq(weth.balanceOf(address(game)), PROPOSER_BOND + CHALLENGER_BOND); + (uint256 proposerBond_, uint256 challengerBond_,) = bondVault.gameBonds(address(game)); + assertEq(proposerBond_, PROPOSER_BOND); + assertEq(challengerBond_, CHALLENGER_BOND); vm.prank(challengerAccount); vm.expectRevert(ClaimAlreadyChallenged.selector); - game.challenge{value: CHALLENGER_BOND}(); + game.challenge(); + } + + function test_Challenge_RejectsDivergedFactoryAndVaultOwners() public { + MultiProofGame game = _proposeAtAnchor(); + address newFactoryOwner = makeAddr("new-factory-owner"); + dgf.transferOwnership(newFactoryOwner); + + vm.prank(challengerAccount); + vm.expectRevert(abi.encodeWithSelector(OwnerMismatch.selector, newFactoryOwner, address(this))); + game.challenge(); + + assertEq(game.challenger(), address(0)); + assertEq(bondVault.availableBalance(challengerAccount), 100 * TOKEN_UNIT); } function test_Challenge_DoesNotExtendProofDeadline() public { @@ -415,7 +432,7 @@ contract MultiProofGameTest is OPStackFixtures { assertEq(game.proofBitmap().count(), 1); vm.prank(challengerAccount); - game.challenge{value: CHALLENGER_BOND}(); + game.challenge(); game.submitProofLane(_compact(1, laneRewardRecipient(1), abi.encodePacked(game.rootId()))); game.resolve(); @@ -423,11 +440,12 @@ contract MultiProofGameTest is OPStackFixtures { // Two lanes plus the proposer split the forfeited challenger bond three ways. uint256 share = CHALLENGER_BOND / 3; - assertEq(game.credit(laneRewardRecipient(0)), share); - assertEq(game.credit(laneRewardRecipient(1)), share); - assertEq(game.credit(proposer), PROPOSER_BOND + CHALLENGER_BOND - 2 * share); + assertEq(game.normalModeCredit(laneRewardRecipient(0)), share); + assertEq(game.normalModeCredit(laneRewardRecipient(1)), share); + assertEq(game.normalModeCredit(proposer), PROPOSER_BOND + CHALLENGER_BOND - 2 * share); assertEq( - game.credit(proposer) + game.credit(laneRewardRecipient(0)) + game.credit(laneRewardRecipient(1)), + game.normalModeCredit(proposer) + game.normalModeCredit(laneRewardRecipient(0)) + + game.normalModeCredit(laneRewardRecipient(1)), game.totalBonds() ); } @@ -497,7 +515,7 @@ contract MultiProofGameTest is OPStackFixtures { vm.warp(expired.challengeDeadline().raw()); vm.prank(challengerAccount); vm.expectRevert(GameOver.selector); - expired.challenge{value: CHALLENGER_BOND}(); + expired.challenge(); // Once the threshold already guarantees the defender wins. (, uint256 anchorBlock) = asr.getAnchorRoot(); @@ -506,7 +524,7 @@ contract MultiProofGameTest is OPStackFixtures { _submitLanes(proven, PROOF_THRESHOLD); vm.prank(challengerAccount); vm.expectRevert(GameOver.selector); - proven.challenge{value: CHALLENGER_BOND}(); + proven.challenge(); } function test_ClaimData_FollowsProposalStatusStateMachine() public { @@ -544,10 +562,12 @@ contract MultiProofGameTest is OPStackFixtures { assertEq(uint8(first.invalidationReason()), uint8(InvalidationReason.PROOF_TIMEOUT)); uint256 reward = (PROPOSER_BOND * gameImpl.CHALLENGER_REWARD_BPS()) / 10_000; - assertEq(first.credit(challengerAccount), CHALLENGER_BOND + reward); - assertEq(first.credit(protocolFeeRecipient), PROPOSER_BOND - reward); + assertEq(first.normalModeCredit(challengerAccount), CHALLENGER_BOND + reward); + assertEq(first.normalModeCredit(protocolFeeRecipient), PROPOSER_BOND - reward); assertEq( - first.credit(challengerAccount) + first.credit(protocolFeeRecipient), first.totalBonds(), "bonds conserved" + first.normalModeCredit(challengerAccount) + first.normalModeCredit(protocolFeeRecipient), + first.totalBonds(), + "bonds conserved" ); MultiProofGame retry = _propose(type(uint256).max, Claim.unwrap(first.rootClaim()), first.l2SequenceNumber(), 1); @@ -562,7 +582,29 @@ contract MultiProofGameTest is OPStackFixtures { bytes memory retryExtraData = _extraData(l2BlockNumber, type(uint256).max, 1); vm.prank(proposer); vm.expectRevert(); - dgf.create{value: PROPOSER_BOND}(WC_GAME_TYPE, claim, retryExtraData); + dgf.create(WC_GAME_TYPE, claim, retryExtraData); + } + + function test_Retry_AllowsLocalProofTimeoutWhilePreviousStillInProgress() public { + MultiProofGame parent = _proposeAtAnchor(); + // Challenge the parent so its clock extends to the proof deadline; the child's + // challenge window can then expire while the parent is still a valid parent. + _challenge(parent); + MultiProofGame child = _proposeChild(0); + + vm.warp(child.challengeDeadline().raw()); + (bool resolvable, GameStatus outcome, InvalidationReason reason) = child.resolutionStatus(); + assertFalse(resolvable); + assertEq(uint8(outcome), uint8(GameStatus.CHALLENGER_WINS)); + assertEq(uint8(reason), uint8(InvalidationReason.PROOF_TIMEOUT)); + assertEq(uint8(child.status()), uint8(GameStatus.IN_PROGRESS)); + assertEq(uint8(parent.status()), uint8(GameStatus.IN_PROGRESS)); + (, GameStatus parentOutcome,) = parent.resolutionStatus(); + assertEq(uint8(parentOutcome), uint8(GameStatus.IN_PROGRESS)); + + MultiProofGame retry = _propose(0, Claim.unwrap(child.rootClaim()), child.l2SequenceNumber(), 1); + assertEq(retry.attempt(), 1); + assertEq(uint8(child.status()), uint8(GameStatus.IN_PROGRESS)); } function test_ChildWaitsForParentResolutionNotFinality() public { @@ -586,6 +628,42 @@ contract MultiProofGameTest is OPStackFixtures { assertEq(uint8(child.status()), uint8(GameStatus.DEFENDER_WINS)); } + function test_ResolutionStatus_SurfacesLocalProofTimeoutWhileParentInProgress() public { + MultiProofGame parent = _proposeAtAnchor(); + MultiProofGame child = _proposeChild(0); + + vm.warp(child.challengeDeadline().raw()); + assertTrue(child.gameOver()); + assertEq(uint8(parent.status()), uint8(GameStatus.IN_PROGRESS)); + + (bool resolvable, GameStatus outcome, InvalidationReason reason) = child.resolutionStatus(); + assertFalse(resolvable); + assertEq(uint8(outcome), uint8(GameStatus.CHALLENGER_WINS)); + assertEq(uint8(reason), uint8(InvalidationReason.PROOF_TIMEOUT)); + + vm.expectRevert(ParentGameNotResolved.selector); + child.resolve(); + assertEq(uint8(child.status()), uint8(GameStatus.IN_PROGRESS)); + } + + function test_Create_RejectsLocallyDoomedParent() public { + _proposeAtAnchor(); + MultiProofGame child = _proposeChild(0); + + vm.warp(child.challengeDeadline().raw()); + (, GameStatus outcome, InvalidationReason reason) = child.resolutionStatus(); + assertEq(uint8(outcome), uint8(GameStatus.CHALLENGER_WINS)); + assertEq(uint8(reason), uint8(InvalidationReason.PROOF_TIMEOUT)); + assertEq(uint8(child.status()), uint8(GameStatus.IN_PROGRESS)); + + uint256 grandchildTarget = child.l2SequenceNumber() + BLOCK_INTERVAL; + bytes memory grandchildExtraData = _extraDataForParent(grandchildTarget, address(child), 0); + Claim grandchildClaim = Claim.wrap(_rootClaimFor(grandchildTarget)); + vm.prank(proposer); + vm.expectRevert(InvalidParentGame.selector); + dgf.create(WC_GAME_TYPE, grandchildClaim, grandchildExtraData); + } + function test_ParentBlacklistedDuringFinalityAirgap_InvalidatesChild() public { MultiProofGame parent = _proposeAtAnchor(); MultiProofGame child = _proposeChild(0); @@ -613,8 +691,8 @@ contract MultiProofGameTest is OPStackFixtures { assertEq(uint8(child.status()), uint8(GameStatus.CHALLENGER_WINS)); assertEq(uint8(child.invalidationReason()), uint8(InvalidationReason.INVALID_PARENT)); - assertEq(child.credit(proposer), PROPOSER_BOND); - assertEq(child.credit(challengerAccount), CHALLENGER_BOND); + assertEq(child.normalModeCredit(proposer), PROPOSER_BOND); + assertEq(child.normalModeCredit(challengerAccount), CHALLENGER_BOND); } function test_BlacklistedParent_CascadesBeforeParentResolution() public { @@ -660,8 +738,8 @@ contract MultiProofGameTest is OPStackFixtures { game.closeGame(); assertEq(uint8(game.bondDistributionMode()), uint8(BondDistributionMode.REFUND)); - assertEq(game.credit(proposer), PROPOSER_BOND); - assertEq(game.credit(challengerAccount), CHALLENGER_BOND); + assertEq(game.refundModeCredit(proposer), PROPOSER_BOND); + assertEq(game.refundModeCredit(challengerAccount), CHALLENGER_BOND); (, uint256 anchorBlock) = asr.getAnchorRoot(); assertEq(anchorBlock, STARTING_ANCHOR_BLOCK); } @@ -678,8 +756,8 @@ contract MultiProofGameTest is OPStackFixtures { game.closeGame(); assertEq(uint8(game.bondDistributionMode()), uint8(BondDistributionMode.REFUND)); - assertEq(game.credit(proposer), PROPOSER_BOND); - assertEq(game.credit(challengerAccount), CHALLENGER_BOND); + assertEq(game.refundModeCredit(proposer), PROPOSER_BOND); + assertEq(game.refundModeCredit(challengerAccount), CHALLENGER_BOND); } function test_IDisputeGameSurfaceAndProofDomain() public { @@ -699,17 +777,17 @@ contract MultiProofGameTest is OPStackFixtures { /// @dev A proposer cannot recover a forfeited bond by challenging from a second address. function test_SelfChallenge_IsAlwaysLossMaking() public { address sybil = makeAddr("proposer-sybil"); - vm.deal(sybil, 10 ether); + _fundBondToken(sybil, 10 * TOKEN_UNIT); // Challenging a proofless proposal still burns part of the proposer's bond. MultiProofGame proofless = _proposeAtAnchor(); vm.prank(sybil); - proofless.challenge{value: CHALLENGER_BOND}(); + proofless.challenge(); vm.warp(proofless.proofDeadline().raw()); proofless.resolve(); uint256 staked = PROPOSER_BOND + CHALLENGER_BOND; - uint256 recovered = proofless.credit(proposer) + proofless.credit(sybil); + uint256 recovered = proofless.normalModeCredit(proposer) + proofless.normalModeCredit(sybil); assertLt(recovered, staked, "self-challenge must lose money"); assertEq(staked - recovered, PROPOSER_BOND - (PROPOSER_BOND * gameImpl.CHALLENGER_REWARD_BPS()) / 10_000); @@ -724,12 +802,12 @@ contract MultiProofGameTest is OPStackFixtures { ) ); vm.prank(sybil); - proven.challenge{value: CHALLENGER_BOND}(); + proven.challenge(); vm.warp(proven.proofDeadline().raw()); proven.resolve(); - recovered = proven.credit(proposer) + proven.credit(sybil); + recovered = proven.normalModeCredit(proposer) + proven.normalModeCredit(sybil); assertLt(recovered, staked, "self-challenge must lose money"); assertEq(staked - recovered, PROPOSER_BOND - (PROPOSER_BOND * gameImpl.CHALLENGER_REWARD_BPS()) / 10_000); } @@ -741,14 +819,14 @@ contract MultiProofGameTest is OPStackFixtures { _resolveUnchallenged(game); assertEq(uint8(game.status()), uint8(GameStatus.DEFENDER_WINS)); - assertEq(game.credit(proposer), PROPOSER_BOND); - assertEq(game.credit(proposer), game.totalBonds()); - assertEq(game.credit(laneRewardRecipient(0)), 0); - assertEq(game.credit(laneRewardRecipient(1)), 0); + assertEq(game.normalModeCredit(proposer), PROPOSER_BOND); + assertEq(game.normalModeCredit(proposer), game.totalBonds()); + assertEq(game.normalModeCredit(laneRewardRecipient(0)), 0); + assertEq(game.normalModeCredit(laneRewardRecipient(1)), 0); } - /// @dev A proposer who proves every lane themselves collects the whole forfeited bond. - function test_LaneReward_ProposerProvingEveryLaneTakesAll() public { + /// @dev A proposer who proves every lane is settled once despite occupying multiple payout roles. + function test_Settlement_DeduplicatesProposerAcrossProofLanes() public { MultiProofGame game = _proposeAtAnchor(); bytes memory proof = abi.encodePacked(game.rootId()); @@ -758,11 +836,15 @@ contract MultiProofGameTest is OPStackFixtures { game.resolve(); assertEq(uint8(game.status()), uint8(GameStatus.DEFENDER_WINS)); - assertEq(game.credit(proposer), PROPOSER_BOND + CHALLENGER_BOND); - assertEq(game.credit(proposer), game.totalBonds()); + assertEq(game.normalModeCredit(proposer), PROPOSER_BOND + CHALLENGER_BOND); + assertEq(game.normalModeCredit(proposer), game.totalBonds()); + + _passAirgap(game); + game.closeGame(); + assertEq(bondVault.availableBalance(proposer), 100 * TOKEN_UNIT + CHALLENGER_BOND); } - /// @dev Each lane recipient withdraws independently through the two-phase DelayedWETH claim. + /// @dev Each lane recipient is independently credited in the shared vault. function test_LaneReward_RecipientsClaimIndependently() public { MultiProofGame game = _proposeAtAnchor(); bytes memory proof = abi.encodePacked(game.rootId()); @@ -778,9 +860,10 @@ contract MultiProofGameTest is OPStackFixtures { _claim(game, laneRewardRecipient(1)); _claim(game, proposer); - assertEq(laneRewardRecipient(0).balance, share); - assertEq(laneRewardRecipient(1).balance, share); - assertEq(weth.balanceOf(address(game)), 0, "game must be fully drained"); + assertEq(bondToken.balanceOf(laneRewardRecipient(0)), share); + assertEq(bondToken.balanceOf(laneRewardRecipient(1)), share); + (,, bool settled) = bondVault.gameBonds(address(game)); + assertTrue(settled); } /// @dev A zero recipient forfeits its share without stranding any other payout. @@ -794,9 +877,13 @@ contract MultiProofGameTest is OPStackFixtures { game.resolve(); uint256 share = CHALLENGER_BOND / 3; - assertEq(game.credit(address(0)), share); - assertEq(game.credit(laneRewardRecipient(1)), share); - assertEq(game.credit(proposer), PROPOSER_BOND + CHALLENGER_BOND - 2 * share); + assertEq(game.normalModeCredit(address(0)), share); + assertEq(game.normalModeCredit(laneRewardRecipient(1)), share); + assertEq(game.normalModeCredit(proposer), PROPOSER_BOND + CHALLENGER_BOND - 2 * share); + + _passAirgap(game); + game.closeGame(); + assertEq(bondVault.availableBalance(address(0)), share); } /// @dev `laneRecipient` records the first submitter; a duplicate no-op cannot reassign it. diff --git a/pkg/contracts/test/dispute/NitroGovernance.t.sol b/pkg/contracts/test/dispute/NitroGovernance.t.sol new file mode 100644 index 000000000..2dadff092 --- /dev/null +++ b/pkg/contracts/test/dispute/NitroGovernance.t.sol @@ -0,0 +1,181 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.28; + +import {Test} from "forge-std/Test.sol"; +import {Governance} from "../../scripts/devnet/Governance.s.sol"; +import {DeployNitro} from "../../scripts/devnet/DeployNitro.s.sol"; +import {TransferNitroOwnership} from "../../scripts/devnet/TransferNitroOwnership.s.sol"; +import {DeployCouncilSafe} from "../../scripts/devnet/DeployCouncilSafe.s.sol"; +import {TestGovernanceConfig, CouncilDeploymentHarness, GovernanceHarness} from "./Governance.t.sol"; +import {CertManager} from "@nitro-validator/CertManager.sol"; +import {NitroAttestationVerifier} from "../../src/dispute/nitro/NitroAttestationVerifier.sol"; +import {Safe} from "@safe-global/safe-contracts/contracts/Safe.sol"; + +contract NitroDeploymentHarness is DeployNitro, TestGovernanceConfig { + function _safeTxOut() internal view override(Governance, TestGovernanceConfig) returns (string memory) { + return safeTxOut; + } + + function _safeMode() internal view override(Governance, TestGovernanceConfig) returns (bool) { + return safeMode; + } + + function _safeAddress() internal view override(Governance, TestGovernanceConfig) returns (address) { + return safeAddress; + } + + function _signerKeys() internal view override(Governance, TestGovernanceConfig) returns (uint256, uint256) { + return (firstKey, secondKey); + } + + function _relayerKey() internal pure override(Governance, TestGovernanceConfig) returns (uint256) { + return 0xCAFE; + } +} + +contract NitroHandoffHarness is TransferNitroOwnership, TestGovernanceConfig { + function _safeTxOut() internal view override(Governance, TestGovernanceConfig) returns (string memory) { + return safeTxOut; + } + + Config internal config; + + function setConfig(Config memory value) external { + config = value; + } + + function _readConfig() internal view override returns (Config memory) { + return config; + } + + function _safeMode() internal view override(Governance, TestGovernanceConfig) returns (bool) { + return safeMode; + } + + function _safeAddress() internal view override(Governance, TestGovernanceConfig) returns (address) { + return safeAddress; + } + + function _signerKeys() internal view override(Governance, TestGovernanceConfig) returns (uint256, uint256) { + return (firstKey, secondKey); + } + + function _relayerKey() internal pure override(Governance, TestGovernanceConfig) returns (uint256) { + return 0xCAFE; + } +} + +contract NitroGovernanceTest is Test { + uint256 internal constant ADMIN_KEY = 0xABCD; + Safe internal safe; + NitroDeploymentHarness internal deployer; + NitroHandoffHarness internal handoff; + GovernanceHarness internal executor; + + function setUp() public { + vm.setEnv("PRIVATE_KEY", vm.toString(uint256(0xCAFE))); + vm.setEnv("OWNER", vm.toString(vm.addr(ADMIN_KEY))); + vm.setEnv("NITRO_DEPLOYMENT_OUT", ""); + vm.setEnv("COUNCIL_DEPLOYMENT_OUT", ""); + CouncilDeploymentHarness council = new CouncilDeploymentHarness(); + council.configure(true, address(0), 0xA11CE, 0xB0B); + DeployCouncilSafe.Deployment memory deployed = council.run(); + safe = deployed.councilSafe; + deployer = new NitroDeploymentHarness(); + handoff = new NitroHandoffHarness(); + executor = new GovernanceHarness(); + executor.configure(true, address(safe), 0xA11CE, 0xB0B); + } + + function test_safeOwnsNitroAndApprovesPCRs() public { + deployer.configure(true, address(safe), 0xA11CE, 0xB0B); + DeployNitro.Deployment memory deployed = deployer.run(); + _assertOwner(deployed, address(safe)); + executor.execute( + 0, + address(deployed.verifier), + abi.encodeCall( + NitroAttestationVerifier.approvePCRSet, (bytes32(uint256(1)), bytes32(uint256(2)), bytes32(uint256(3))) + ) + ); + assertEq(safe.nonce(), 1); + vm.prank(vm.addr(ADMIN_KEY)); + vm.expectRevert(); + deployed.verifier.approvePCRSet(bytes32(uint256(1)), bytes32(uint256(2)), bytes32(uint256(3))); + executor.execute(0, address(deployed.certManager), abi.encodeCall(CertManager.setRevoker, (address(safe)))); + assertEq(deployed.certManager.revoker(), address(safe)); + assertTrue(deployed.verifier.isPCRSetApproved(bytes32(uint256(1)), bytes32(uint256(2)), bytes32(uint256(3)))); + } + + function test_eoaOwnsNitroAndApprovesPCRs() public { + DeployNitro.Deployment memory deployed = deployer.run(); + _assertOwner(deployed, vm.addr(ADMIN_KEY)); + executor.configure(false, address(0), 0xA11CE, 0xB0B); + executor.execute( + ADMIN_KEY, + address(deployed.verifier), + abi.encodeCall( + NitroAttestationVerifier.approvePCRSet, (bytes32(uint256(1)), bytes32(uint256(2)), bytes32(uint256(3))) + ) + ); + } + + function test_preparesPCRApprovalWithoutExecuting() public { + deployer.configure(true, address(safe), 0, 0); + DeployNitro.Deployment memory deployed = deployer.run(); + executor.configure(true, address(safe), 0, 0); + executor.setSafeTxOut("cache/nitro-test.safe.json"); + executor.execute( + 0, + address(deployed.verifier), + abi.encodeCall( + NitroAttestationVerifier.approvePCRSet, (bytes32(uint256(1)), bytes32(uint256(2)), bytes32(uint256(3))) + ) + ); + assertFalse(deployed.verifier.isPCRSetApproved(bytes32(uint256(1)), bytes32(uint256(2)), bytes32(uint256(3)))); + assertEq(safe.nonce(), 0); + executor.setSafeTxOut(""); + } + + function test_handoffBothDirectionsAndRetry() public { + DeployNitro.Deployment memory deployed = deployer.run(); + handoff.setConfig( + TransferNitroOwnership.Config( + address(safe), ADMIN_KEY, deployed.certManager, deployed.verifier, deployed.registry + ) + ); + handoff.run(); + _assertOwner(deployed, address(safe)); + handoff.run(); + handoff.configure(true, address(safe), 0xA11CE, 0xB0B); + handoff.setConfig( + TransferNitroOwnership.Config( + vm.addr(ADMIN_KEY), 0, deployed.certManager, deployed.verifier, deployed.registry + ) + ); + handoff.run(); + _assertOwner(deployed, vm.addr(ADMIN_KEY)); + } + + function test_handoffResumesAfterCertManagerTransfer() public { + DeployNitro.Deployment memory deployed = deployer.run(); + vm.startPrank(vm.addr(ADMIN_KEY)); + deployed.certManager.setRevoker(address(safe)); + deployed.certManager.transferOwnership(address(safe)); + vm.stopPrank(); + handoff.setConfig( + TransferNitroOwnership.Config( + address(safe), ADMIN_KEY, deployed.certManager, deployed.verifier, deployed.registry + ) + ); + handoff.run(); + _assertOwner(deployed, address(safe)); + } + + function _assertOwner(DeployNitro.Deployment memory deployed, address owner) internal view { + assertEq(deployed.certManager.owner(), owner); + assertEq(deployed.certManager.revoker(), owner); + assertEq(deployed.verifier.owner(), owner); + assertEq(deployed.registry.owner(), owner); + } +} diff --git a/pkg/contracts/test/dispute/OPStackFixtures.sol b/pkg/contracts/test/dispute/OPStackFixtures.sol index f90448b6e..56d43f94c 100644 --- a/pkg/contracts/test/dispute/OPStackFixtures.sol +++ b/pkg/contracts/test/dispute/OPStackFixtures.sol @@ -4,33 +4,36 @@ pragma solidity 0.8.28; import {Test} from "@forge-std/Test.sol"; import {MultiProofGame} from "../../src/dispute/MultiProofGame.sol"; +import {ERC20StakingVault} from "../../src/dispute/ERC20StakingVault.sol"; import {IMultiProofGame} from "../../src/dispute/interfaces/IMultiProofGame.sol"; +import {IERC20StakingVault} from "../../src/dispute/interfaces/IERC20StakingVault.sol"; import {GameTypes} from "../../src/dispute/lib/GameTypes.sol"; import {LibProof, ProofLane} from "../../src/dispute/lib/LibProof.sol"; import {IWorldChainProofVerifier} from "../../src/dispute/interfaces/IWorldChainProofVerifier.sol"; import {MockRootIdVerifier} from "../mocks/MockRootIdVerifier.sol"; import {MockSystemConfig} from "../mocks/MockSystemConfig.sol"; +import {MockBondToken} from "../mocks/MockBondToken.sol"; import {Claim, GameStatus, GameType, Hash, Proposal} from "@optimism-bedrock/src/dispute/lib/Types.sol"; import {IDisputeGame} from "@optimism-bedrock/interfaces/dispute/IDisputeGame.sol"; import {IDisputeGameFactory} from "@optimism-bedrock/interfaces/dispute/IDisputeGameFactory.sol"; import {IAnchorStateRegistry} from "@optimism-bedrock/interfaces/dispute/IAnchorStateRegistry.sol"; -import {IDelayedWETH} from "@optimism-bedrock/interfaces/dispute/IDelayedWETH.sol"; import {IProxyAdmin} from "@optimism-bedrock/interfaces/universal/IProxyAdmin.sol"; import {ISystemConfig} from "@optimism-bedrock/interfaces/L1/ISystemConfig.sol"; /// @dev Test harness deploying the real (pinned) OP `DisputeGameFactory`, -/// `AnchorStateRegistry`, and `DelayedWETH` from the `opstack/` sub-project artifacts, +/// `AnchorStateRegistry`, and `Proxy` from the `opstack/` sub-project artifacts, /// wired to a `MultiProofGame` implementation. Run `just build-opstack` /// before `forge test`. abstract contract OPStackFixtures is Test { GameType internal constant WC_GAME_TYPE = GameTypes.MULTI_PROOF_GAME_TYPE; uint256 internal constant FINALITY_DELAY_SECONDS = 3.5 days; - uint256 internal constant WETH_DELAY_SECONDS = 7 days; + uint256 internal constant ERC20_WITHDRAWAL_DELAY_SECONDS = 7 days; uint64 internal constant CHALLENGE_PERIOD = 1 days; uint64 internal constant PROOF_PERIOD = 7 days; - uint256 internal constant PROPOSER_BOND = 1 ether; - uint256 internal constant CHALLENGER_BOND = 0.1 ether; + uint256 internal constant TOKEN_UNIT = 1e18; + uint256 internal constant PROPOSER_BOND = TOKEN_UNIT; + uint256 internal constant CHALLENGER_BOND = TOKEN_UNIT; uint8 internal constant PROOF_THRESHOLD = 2; uint256 internal constant CHAIN_ID = 480; @@ -52,7 +55,8 @@ abstract contract OPStackFixtures is Test { IProxyAdmin internal proxyAdmin; IDisputeGameFactory internal dgf; IAnchorStateRegistry internal asr; - IDelayedWETH internal weth; + MockBondToken internal bondToken; + IERC20StakingVault internal bondVault; MockRootIdVerifier internal validityVerifier; MockRootIdVerifier internal teeVerifier; @@ -88,14 +92,14 @@ abstract contract OPStackFixtures is Test { ) ); - // DelayedWETH proxy. - weth = IDelayedWETH( - payable(_proxied("opstack/out/DelayedWETH.sol/DelayedWETH.json", abi.encode(WETH_DELAY_SECONDS))) - ); + // WIP-1006 ERC-20 bond token staking vault proxy. + bondToken = new MockBondToken(); + ERC20StakingVault vaultImpl = new ERC20StakingVault(ERC20_WITHDRAWAL_DELAY_SECONDS); + bondVault = IERC20StakingVault(deployCode("opstack/out/Proxy.sol/Proxy.json", abi.encode(address(proxyAdmin)))); proxyAdmin.upgradeAndCall( - payable(address(weth)), - _lastImpl, - abi.encodeCall(IDelayedWETH.initialize, (ISystemConfig(address(systemConfig)))) + payable(address(bondVault)), + address(vaultImpl), + abi.encodeCall(IERC20StakingVault.initialize, (bondToken, ISystemConfig(address(systemConfig)), dgf)) ); // World Chain proof-system periphery + game implementation. @@ -105,13 +109,13 @@ abstract contract OPStackFixtures is Test { gameImpl = new MultiProofGame(_gameConfig()); dgf.setImplementation(WC_GAME_TYPE, IDisputeGame(address(gameImpl)), hex""); - dgf.setInitBond(WC_GAME_TYPE, PROPOSER_BOND); + dgf.setInitBond(WC_GAME_TYPE, 0); // The registry retires every game created at or before its initialization timestamp. vm.warp(block.timestamp + 1); - vm.deal(proposer, 100 ether); - vm.deal(challengerAccount, 100 ether); + _fundBondToken(proposer, 100 * TOKEN_UNIT); + _fundBondToken(challengerAccount, 100 * TOKEN_UNIT); } /// @dev Address of the implementation most recently deployed by `_proxied`. @@ -141,7 +145,7 @@ abstract contract OPStackFixtures is Test { teeVerifier: IWorldChainProofVerifier(address(teeVerifier)), securityCouncil: IWorldChainProofVerifier(address(councilVerifier)), anchorStateRegistry: asr, - weth: weth + bondVault: bondVault }); } @@ -174,14 +178,24 @@ abstract contract OPStackFixtures is Test { return keccak256(abi.encode("output-root", l2BlockNumber)); } - /// @dev Creates a game through the stock factory as `proposer`. + /// @dev Mints ERC-20 bond token to `account` and deposits it into the vault with no remaining allowance. + function _fundBondToken(address account, uint256 amount) internal { + bondToken.mint(account, amount); + vm.prank(account); + bondToken.approve(address(bondVault), amount); + vm.prank(account); + bondVault.deposit(account, amount); + } + + /// @dev Creates through the stock factory as `proposer`; the vault locks the bond from + /// the creator's available balance during `initialize`. function _propose(uint256 parentIndex, bytes32 rootClaim, uint256 l2BlockNumber, uint256 attempt) internal returns (MultiProofGame) { bytes memory extraData = _extraData(l2BlockNumber, parentIndex, attempt); vm.prank(proposer); - IDisputeGame proxy = dgf.create{value: PROPOSER_BOND}(WC_GAME_TYPE, Claim.wrap(rootClaim), extraData); + IDisputeGame proxy = dgf.create(WC_GAME_TYPE, Claim.wrap(rootClaim), extraData); return MultiProofGame(address(proxy)); } @@ -193,8 +207,7 @@ abstract contract OPStackFixtures is Test { address parent = address(anchorGame) == address(0) ? address(asr) : address(anchorGame); bytes memory extraData = _extraDataForParent(target, parent, 0); vm.prank(proposer); - IDisputeGame proxy = - dgf.create{value: PROPOSER_BOND}(WC_GAME_TYPE, Claim.wrap(_rootClaimFor(target)), extraData); + IDisputeGame proxy = dgf.create(WC_GAME_TYPE, Claim.wrap(_rootClaimFor(target)), extraData); return MultiProofGame(address(proxy)); } @@ -207,7 +220,7 @@ abstract contract OPStackFixtures is Test { function _challenge(MultiProofGame game) internal { vm.prank(challengerAccount); - game.challenge{value: CHALLENGER_BOND}(); + game.challenge(); } /// @dev Packs a compact `submitProofLane` payload: lane id, reward recipient, then the proof. @@ -248,10 +261,15 @@ abstract contract OPStackFixtures is Test { vm.warp(game.resolvedAt().raw() + FINALITY_DELAY_SECONDS + 1); } - /// @dev Runs the full two-phase DelayedWETH claim for `recipient`. + /// @dev Closes the game, then runs the vault's delayed external ERC-20 bond token withdrawal. function _claim(MultiProofGame game, address recipient) internal { - game.claimCredit(recipient); - vm.warp(block.timestamp + WETH_DELAY_SECONDS); - game.claimCredit(recipient); + game.closeGame(); + uint256 available = bondVault.availableBalance(recipient); + vm.prank(recipient); + bondVault.requestWithdrawal(available); + vm.warp(block.timestamp + ERC20_WITHDRAWAL_DELAY_SECONDS); + (uint256 amount,) = bondVault.withdrawals(recipient); + vm.prank(recipient); + bondVault.withdraw(amount); } } diff --git a/pkg/contracts/test/dispute/SecurityCouncilSafeSubmission.t.sol b/pkg/contracts/test/dispute/SecurityCouncilSafeSubmission.t.sol new file mode 100644 index 000000000..0ae89d774 --- /dev/null +++ b/pkg/contracts/test/dispute/SecurityCouncilSafeSubmission.t.sol @@ -0,0 +1,134 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.28; + +import {OPStackFixtures} from "./OPStackFixtures.sol"; +import {MultiProofGame} from "../../src/dispute/MultiProofGame.sol"; +import {SecurityCouncilVerifier} from "../../src/dispute/council/SecurityCouncilVerifier.sol"; +import {IMultiProofGame} from "../../src/dispute/interfaces/IMultiProofGame.sol"; +import {IWorldChainProofVerifier} from "../../src/dispute/interfaces/IWorldChainProofVerifier.sol"; +import {Bitmap} from "../../src/dispute/lib/LibProof.sol"; +import {IDisputeGame} from "@optimism-bedrock/interfaces/dispute/IDisputeGame.sol"; +import {Safe} from "@safe-global/safe-contracts/contracts/Safe.sol"; +import { + CompatibilityFallbackHandler +} from "@safe-global/safe-contracts/contracts/handler/CompatibilityFallbackHandler.sol"; +import {SafeProxyFactory} from "@safe-global/safe-contracts/contracts/proxies/SafeProxyFactory.sol"; +import {SignMessageLib} from "@safe-global/safe-contracts/contracts/libraries/SignMessageLib.sol"; +import {MultiSend} from "@safe-global/safe-contracts/contracts/libraries/MultiSend.sol"; +import {Enum} from "@safe-global/safe-contracts/contracts/common/Enum.sol"; + +contract SecurityCouncilSafeSubmissionTest is OPStackFixtures { + Safe internal safe; + SecurityCouncilVerifier internal verifier; + SignMessageLib internal signMessageLib; + MultiSend internal multiSend; + uint256 internal pk1; + uint256 internal pk2; + + function setUp() public override { + super.setUp(); + (pk1, pk2) = (0xA11CE, 0xB0B); + if (vm.addr(pk1) > vm.addr(pk2)) (pk1, pk2) = (pk2, pk1); + address[] memory owners = new address[](2); + (owners[0], owners[1]) = (vm.addr(pk1), vm.addr(pk2)); + Safe singleton = new Safe(); + CompatibilityFallbackHandler handler = new CompatibilityFallbackHandler(); + safe = Safe(payable(address(new SafeProxyFactory().createProxyWithNonce(address(singleton), "", 0)))); + safe.setup(owners, 2, address(0), "", address(handler), address(0), 0, payable(address(0))); + signMessageLib = new SignMessageLib(); + multiSend = new MultiSend(); + verifier = new SecurityCouncilVerifier(address(safe)); + IMultiProofGame.GameConfig memory config = _gameConfig(); + config.securityCouncil = IWorldChainProofVerifier(address(verifier)); + gameImpl = new MultiProofGame(config); + dgf.setImplementation(WC_GAME_TYPE, IDisputeGame(address(gameImpl)), ""); + } + + function test_CouncilBatch_ApprovesAndSubmitsWithOneSafeTransaction() public { + MultiProofGame game = _proposeAtAnchor(); + bytes memory data = _batch(game); + assertTrue(_execute(data, _signatures(data, true))); + assertEq(safe.nonce(), 1); + assertEq(Bitmap.unwrap(game.proofBitmap()), 4); + assertEq(game.laneRecipient(2), address(safe)); + assertTrue(verifier.verify("", bytes32(0), abi.encode(game.rootId()))); + assertFalse(verifier.verify("", bytes32(0), abi.encode(keccak256("another root")))); + } + + function test_CouncilBatch_RequiresBothSafeOwners() public { + MultiProofGame game = _proposeAtAnchor(); + bytes memory data = _batch(game); + bytes memory sigs = _signatures(data, false); + vm.expectRevert("GS020"); + _execute(data, sigs); + assertFalse(verifier.verify("", bytes32(0), abi.encode(game.rootId()))); + assertEq(Bitmap.unwrap(game.proofBitmap()), 0); + } + + function test_CouncilBatch_FailedSubmissionRollsBackApproval() public { + MultiProofGame game = _proposeAtAnchor(); + bytes memory data = _batch(game); + bytes memory sigs = _signatures(data, true); + vm.warp(block.timestamp + PROOF_PERIOD + 1); + vm.expectRevert("GS013"); + _execute(data, sigs); + assertEq(safe.nonce(), 0); + assertFalse(verifier.verify("", bytes32(0), abi.encode(game.rootId()))); + assertEq(Bitmap.unwrap(game.proofBitmap()), 0); + } + + function test_CouncilBatch_SimulationDoesNotPersistApproval() public { + MultiProofGame game = _proposeAtAnchor(); + (bool success,) = + address(safe).call(abi.encodeWithSignature("simulate(address,bytes)", address(multiSend), _batch(game))); + assertTrue(success); + assertEq(safe.nonce(), 0); + assertFalse(verifier.verify("", bytes32(0), abi.encode(game.rootId()))); + assertEq(Bitmap.unwrap(game.proofBitmap()), 0); + } + + function _batch(MultiProofGame game) internal view returns (bytes memory) { + bytes memory approval = + abi.encodeCall(SignMessageLib.signMessage, (abi.encode(verifier.attestationDigest(game.rootId())))); + bytes memory submission = + abi.encodeCall(MultiProofGame.submitProofLane, (abi.encodePacked(uint8(2), address(safe)))); + bytes memory actions = abi.encodePacked( + uint8(1), + address(signMessageLib), + uint256(0), + approval.length, + approval, + uint8(0), + address(game), + uint256(0), + submission.length, + submission + ); + return abi.encodeCall(MultiSend.multiSend, (actions)); + } + + function _signatures(bytes memory data, bool both) internal view returns (bytes memory) { + bytes32 hash = safe.getTransactionHash( + address(multiSend), + 0, + data, + Enum.Operation.DelegateCall, + 0, + 0, + 0, + address(0), + payable(address(0)), + safe.nonce() + ); + (uint8 v1, bytes32 r1, bytes32 s1) = vm.sign(pk1, hash); + if (!both) return abi.encodePacked(r1, s1, v1); + (uint8 v2, bytes32 r2, bytes32 s2) = vm.sign(pk2, hash); + return abi.encodePacked(r1, s1, v1, r2, s2, v2); + } + + function _execute(bytes memory data, bytes memory sigs) internal returns (bool) { + return safe.execTransaction( + address(multiSend), 0, data, Enum.Operation.DelegateCall, 0, 0, 0, address(0), payable(address(0)), sigs + ); + } +} diff --git a/pkg/contracts/test/dispute/nitro/NitroAttestationVerifier.t.sol b/pkg/contracts/test/dispute/nitro/NitroAttestationVerifier.t.sol index 8d000f7f2..bb3f5993c 100644 --- a/pkg/contracts/test/dispute/nitro/NitroAttestationVerifier.t.sol +++ b/pkg/contracts/test/dispute/nitro/NitroAttestationVerifier.t.sol @@ -60,7 +60,7 @@ contract NitroAttestationVerifierTest is Test { function setUp() public { p384Verifier = new P384Verifier(); - certManager = new CertManager(IP384Verifier(address(p384Verifier))); + certManager = new CertManager(IP384Verifier(address(p384Verifier)), address(this), address(this)); verifier = new NitroAttestationVerifier( ICertManager(address(certManager)), IP384Verifier(address(p384Verifier)), owner @@ -343,6 +343,43 @@ contract NitroAttestationVerifierTest is Test { h2 = keccak256(p2); } + function _sparsePcrBank() internal pure returns (CborElement[] memory bank) { + bank = new CborElement[](32); + for (uint256 i; i < bank.length; i++) { + bank[i] = LibCborElement.toCborElement(0xf6, 0, 0); + } + for (uint256 i; i < 3; i++) { + bank[i] = LibCborElement.toCborElement(0x40, i * 48, 48); + } + } + + function test_VerifyValidated_AcceptsSparsePcrBank() public { + (bytes memory tbs, bytes memory expectedKey) = _buildTbsWithPcrsAndKey(); + (bytes32 h0, bytes32 h1, bytes32 h2) = _approvedPcrHashes(); + vm.prank(owner); + harness.approvePCRSet(h0, h1, h2); + vm.warp(1_000_000); + NitroValidator.Ptrs memory ptrs = + _buildPtrs(uint64(1_000_000 * 1000), 3, _sparsePcrBank(), LibCborElement.toCborElement(0x40, 144, 65)); + (bytes memory pk, bytes32 p0, bytes32 p1, bytes32 p2) = harness.exposeVerifyValidated(tbs, ptrs); + assertEq(pk, expectedKey); + assertEq(p0, h0); + assertEq(p1, h1); + assertEq(p2, h2); + } + + function testFuzz_VerifyValidated_RejectsMissingRequiredPcr(uint8 missing) public { + missing = uint8(bound(missing, 0, 2)); + (bytes memory tbs,) = _buildTbsWithPcrsAndKey(); + CborElement[] memory bank = _sparsePcrBank(); + bank[missing] = LibCborElement.toCborElement(0xf6, 0, 0); + vm.warp(1_000_000); + NitroValidator.Ptrs memory ptrs = + _buildPtrs(uint64(1_000_000 * 1000), 3, bank, LibCborElement.toCborElement(0x40, 144, 65)); + vm.expectRevert(abi.encodeWithSelector(NitroAttestationVerifier.MissingPcr.selector, uint256(missing))); + harness.exposeVerifyValidated(tbs, ptrs); + } + function test_VerifyValidated_HappyPath() public { (bytes memory tbs, bytes memory expectedKey) = _buildTbsWithPcrsAndKey(); (bytes32 h0, bytes32 h1, bytes32 h2) = _approvedPcrHashes(); diff --git a/pkg/contracts/test/mocks/MockBondToken.sol b/pkg/contracts/test/mocks/MockBondToken.sol new file mode 100644 index 000000000..3642cc45a --- /dev/null +++ b/pkg/contracts/test/mocks/MockBondToken.sol @@ -0,0 +1,12 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.28; + +import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; + +contract MockBondToken is ERC20 { + constructor() ERC20("Bond Token", "BOND") {} + + function mint(address recipient, uint256 amount) external { + _mint(recipient, amount); + } +} diff --git a/proofs/README.md b/proofs/README.md index f9d8b3445..13e25a385 100644 --- a/proofs/README.md +++ b/proofs/README.md @@ -3,3 +3,7 @@ > **This code is currently under active development and has not been audited.** > > Any external security audits conducted prior to the completion of development will not be valid. Please do not rely on this code for production use until a full audit has been completed and development is finalized. + +## Architecture and maintenance + +- [Reproducible proof builds](../docs/proof/reproducible-builds.md): measured workspaces, verification keys and enclave PCRs. diff --git a/proofs/backends/nitro/fuzz/Cargo.lock b/proofs/backends/nitro/fuzz/Cargo.lock index 5122e9360..16ca5b7dd 100644 --- a/proofs/backends/nitro/fuzz/Cargo.lock +++ b/proofs/backends/nitro/fuzz/Cargo.lock @@ -3604,9 +3604,9 @@ dependencies = [ [[package]] name = "rustls-webpki" -version = "0.103.15" +version = "0.103.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" dependencies = [ "ring", "rustls-pki-types", diff --git a/proofs/backends/nitro/register/Cargo.toml b/proofs/backends/nitro/register/Cargo.toml index bcd56a013..8bb33c7b1 100644 --- a/proofs/backends/nitro/register/Cargo.toml +++ b/proofs/backends/nitro/register/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "world-chain-proof-nitro-register" description = "Host-side on-chain registration of a Nitro enclave's ephemeral signing key" -version = "1.0.0-rc.1" +version = "1.0.0-rc.5" edition.workspace = true rust-version.workspace = true license.workspace = true diff --git a/proofs/backends/sp1/elfs/Cargo.toml b/proofs/backends/sp1/elfs/Cargo.toml index bd0b0422e..f83d258e1 100644 --- a/proofs/backends/sp1/elfs/Cargo.toml +++ b/proofs/backends/sp1/elfs/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "world-chain-proof-sp1-elfs" -version = "1.0.0-rc.1" +version = "1.0.0-rc.5" edition.workspace = true rust-version.workspace = true license.workspace = true @@ -9,10 +9,10 @@ repository.workspace = true build = "build.rs" [build-dependencies] -sp1-build = "=6.3.1" +sp1-build = "=6.8.1" [dependencies] -sp1-sdk = { version = "=6.3.1", features = ["network"] } +sp1-sdk = { version = "=6.8.1", features = ["network"] } # Proofs release train: cargo-release bumps every shared-version member in lockstep. [package.metadata.release] diff --git a/proofs/backends/sp1/elfs/build.rs b/proofs/backends/sp1/elfs/build.rs index 92609a2a6..527da8d04 100644 --- a/proofs/backends/sp1/elfs/build.rs +++ b/proofs/backends/sp1/elfs/build.rs @@ -9,7 +9,7 @@ //! //! Behaviour: //! - Uses `docker: true` by default with the pinned SP1 toolchain image -//! (matches the `=6.3.1` version of `sp1-zkvm` the guest workspace pins to) +//! (matches the `=6.8.1` version of `sp1-zkvm` the guest workspace pins to) //! for bit-for-bit reproducible ELFs. This is the ecosystem //! standard used by op-succinct, sp1-helios, and all other SP1 adopters. //! Docker provides reproducibility by fixing the build environment path @@ -34,6 +34,8 @@ fn main() { println!("cargo:rerun-if-env-changed=SP1_SKIP_PROGRAM_BUILD"); println!("cargo:rerun-if-env-changed=SP1_BUILD_DOCKER"); + // sp1-build watches package manifests, but profiles live in the workspace manifest. + println!("cargo:rerun-if-changed=../../../measured/sp1-programs/Cargo.toml"); // Under `cargo clippy` the build script receives `CARGO_CFG_CLIPPY=1`. // The `#[cfg(clippy)]` guards in `src/lib.rs` prevent `include_elf!()` @@ -96,7 +98,7 @@ fn main() { // reference for readability, while the digest prevents a mutable tag from // silently rotating the guest ELFs and their on-chain vkeys. tag: - "v6.3.1@sha256:7c1c8201de6f63e3f1fb9075bd9a67a4c5fc8c2d546d11a5ff71587bb51e6eb3" + "v6.8.1@sha256:e672d7160039916f40a6a4c2ea4cb0c8cd3dab120fdb24d08560d386ad8f59c2" .to_string(), ignore_rust_version: true, locked: true, diff --git a/proofs/backends/sp1/guest-builder/Cargo.toml b/proofs/backends/sp1/guest-builder/Cargo.toml index 067504f4d..4ccf8230e 100644 --- a/proofs/backends/sp1/guest-builder/Cargo.toml +++ b/proofs/backends/sp1/guest-builder/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "world-chain-proof-sp1-guest-builder" -version = "1.0.0-rc.1" +version = "1.0.0-rc.5" edition.workspace = true rust-version.workspace = true license.workspace = true @@ -10,7 +10,7 @@ publish = false [dependencies] anyhow.workspace = true -sp1-build = "=6.3.1" +sp1-build = "=6.8.1" # Proofs release train: cargo-release bumps every shared-version member in lockstep. [package.metadata.release] diff --git a/proofs/backends/sp1/host/Cargo.toml b/proofs/backends/sp1/host/Cargo.toml index 0ea639c27..62c3861d7 100644 --- a/proofs/backends/sp1/host/Cargo.toml +++ b/proofs/backends/sp1/host/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "world-chain-proof-sp1-host" -version = "1.0.0-rc.1" +version = "1.0.0-rc.5" edition.workspace = true rust-version.workspace = true license.workspace = true @@ -36,9 +36,8 @@ alloy-sol-types = { workspace = true, optional = true } bincode = { version = "1", optional = true } hex = { workspace = true, optional = true } sha2 = { workspace = true, optional = true } -sp1-sdk = { version = "=6.3.1", features = ["network"], optional = true } +sp1-sdk = { version = "=6.8.1", features = ["network"], optional = true } async-trait.workspace = true -world-chain-prover-service.workspace = true # Proofs release train: cargo-release bumps every shared-version member in lockstep. [package.metadata.release] diff --git a/proofs/backends/sp1/host/src/network_prover.rs b/proofs/backends/sp1/host/src/network_prover.rs index 8223e1e2e..15c7a795b 100644 --- a/proofs/backends/sp1/host/src/network_prover.rs +++ b/proofs/backends/sp1/host/src/network_prover.rs @@ -1,7 +1,7 @@ //! Range proofs are produced in `Compressed` mode so the aggregation guest can recursively //! verify them; the aggregation proof mode is configurable (Groth16 for on-chain verification). -use std::time::Duration; +use std::time::{Duration, Instant}; use crate::{SuccinctProverError, WorldSuccinctProver}; use alloy_primitives::{B256, U256}; @@ -16,9 +16,12 @@ use sp1_sdk::{ signer::NetworkSigner, }, }; +use tokio::time::MissedTickBehavior; use world_chain_proof_core::types::AggregationInputs; use world_chain_proof_sp1_types::{AggregationProofRequest, RangeProofRequest, Sp1ProofRequest}; +const LOCAL_LIMIT_ESTIMATION_HEARTBEAT_INTERVAL: Duration = Duration::from_secs(15 * 60); + /// [`WorldSuccinctProver`] network implementation over the sp1-sdk network prover. pub struct NetworkSuccinctProver { client: NetworkProver, @@ -204,6 +207,7 @@ impl NetworkSuccinctProver { } async fn request_range_proof(&self, request: RangeProofRequest) -> anyhow::Result { + let witness_bytes = request.witness_rkyv.len(); let mut stdin = SP1Stdin::new(); stdin.write_vec(request.witness_rkyv); @@ -221,10 +225,41 @@ impl NetworkSuccinctProver { proof_request = proof_request.timeout(proof_timeout); } - let backend_session_id = proof_request - .request() - .await - .context("request range proving failed")?; + let (backend_session_id, limit_estimation_elapsed) = if self.limits.is_none() { + tracing::info!( + witness_bytes, + heartbeat_interval_seconds = LOCAL_LIMIT_ESTIMATION_HEARTBEAT_INTERVAL.as_secs(), + "starting local SP1 range limit simulation" + ); + let started_at = Instant::now(); + let request_future = proof_request.request(); + tokio::pin!(request_future); + let mut heartbeat = tokio::time::interval(LOCAL_LIMIT_ESTIMATION_HEARTBEAT_INTERVAL); + heartbeat.set_missed_tick_behavior(MissedTickBehavior::Delay); + heartbeat.tick().await; + + let result = loop { + tokio::select! { + result = &mut request_future => break result, + _ = heartbeat.tick() => tracing::info!( + witness_bytes, + elapsed_seconds = started_at.elapsed().as_secs(), + "local SP1 range limit simulation still running" + ), + } + }; + (result, Some(started_at.elapsed())) + } else { + (proof_request.request().await, None) + }; + let backend_session_id = backend_session_id.context("request range proving failed")?; + if let Some(elapsed) = limit_estimation_elapsed { + tracing::info!( + witness_bytes, + elapsed_seconds = elapsed.as_secs(), + "local SP1 range limit-estimation request completed" + ); + } Ok(backend_session_id.to_string()) } @@ -233,6 +268,7 @@ impl NetworkSuccinctProver { &self, request: AggregationProofRequest, ) -> anyhow::Result { + let range_count = request.inputs.transition_public_values.len(); let mut stdin = SP1Stdin::new(); let range_vk = self.range_pk.verifying_key().vk.clone(); for proof_bytes in &request.range_proofs { @@ -263,10 +299,41 @@ impl NetworkSuccinctProver { proof_request = proof_request.timeout(proof_timeout); } - let backend_session_id = proof_request - .request() - .await - .context("aggregation proving failed")?; + let (backend_session_id, limit_estimation_elapsed) = if self.limits.is_none() { + tracing::info!( + range_count, + heartbeat_interval_seconds = LOCAL_LIMIT_ESTIMATION_HEARTBEAT_INTERVAL.as_secs(), + "starting local SP1 aggregation limit simulation" + ); + let started_at = Instant::now(); + let request_future = proof_request.request(); + tokio::pin!(request_future); + let mut heartbeat = tokio::time::interval(LOCAL_LIMIT_ESTIMATION_HEARTBEAT_INTERVAL); + heartbeat.set_missed_tick_behavior(MissedTickBehavior::Delay); + heartbeat.tick().await; + + let result = loop { + tokio::select! { + result = &mut request_future => break result, + _ = heartbeat.tick() => tracing::info!( + range_count, + elapsed_seconds = started_at.elapsed().as_secs(), + "local SP1 aggregation limit simulation still running" + ), + } + }; + (result, Some(started_at.elapsed())) + } else { + (proof_request.request().await, None) + }; + let backend_session_id = backend_session_id.context("aggregation proving failed")?; + if let Some(elapsed) = limit_estimation_elapsed { + tracing::info!( + range_count, + elapsed_seconds = elapsed.as_secs(), + "local SP1 aggregation limit-estimation request completed" + ); + } Ok(backend_session_id.to_string()) } diff --git a/proofs/backends/sp1/host/src/vkeys.rs b/proofs/backends/sp1/host/src/vkeys.rs index 2534c1285..24487ce80 100644 --- a/proofs/backends/sp1/host/src/vkeys.rs +++ b/proofs/backends/sp1/host/src/vkeys.rs @@ -3,7 +3,6 @@ use anyhow::{Result, anyhow}; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use sp1_sdk::{CpuProver, HashableKey, Prover, ProvingKey, env::EnvProver}; -use world_chain_proof_core::types::u32_to_u8; #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct ElfHash { @@ -56,6 +55,6 @@ pub async fn embedded_vkey_manifest() -> Result { sha256: aggregation_sha256, }, }, - range_vkey_commitment: B256::from(u32_to_u8(range_pk.verifying_key().hash_u32())), + range_vkey_commitment: B256::from(range_pk.verifying_key().hash_bytes()), }) } diff --git a/proofs/backends/sp1/types/Cargo.toml b/proofs/backends/sp1/types/Cargo.toml index d4448bee5..a92d5c598 100644 --- a/proofs/backends/sp1/types/Cargo.toml +++ b/proofs/backends/sp1/types/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "world-chain-proof-sp1-types" -version = "1.0.0-rc.1" +version = "1.0.0-rc.5" edition.workspace = true rust-version.workspace = true license.workspace = true diff --git a/proofs/debug/bin/prover-cli/Cargo.toml b/proofs/debug/bin/prover-cli/Cargo.toml index 4242fdbb2..adc844d82 100644 --- a/proofs/debug/bin/prover-cli/Cargo.toml +++ b/proofs/debug/bin/prover-cli/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "world-chain-prover-cli" -version = "1.0.0-rc.1" +version = "1.0.0-rc.5" edition.workspace = true rust-version.workspace = true license.workspace = true diff --git a/proofs/debug/bin/prover-cli/src/main.rs b/proofs/debug/bin/prover-cli/src/main.rs index a60657d77..589a63f96 100644 --- a/proofs/debug/bin/prover-cli/src/main.rs +++ b/proofs/debug/bin/prover-cli/src/main.rs @@ -230,6 +230,7 @@ async fn run(cli: Cli) -> Result<()> { let response = client.get_proof(id).await; bail!("proof request {id} failed: {response:?}"); } + ProofStatus::Cancelled => bail!("proof request {id} was cancelled"), ProofStatus::Created | ProofStatus::Running => { if tokio::time::Instant::now() >= deadline { bail!( diff --git a/proofs/debug/bin/prover-nitro/Cargo.toml b/proofs/debug/bin/prover-nitro/Cargo.toml index e1ba05980..046757f1f 100644 --- a/proofs/debug/bin/prover-nitro/Cargo.toml +++ b/proofs/debug/bin/prover-nitro/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "world-chain-prover-nitro" -version = "1.0.0-rc.1" +version = "1.0.0-rc.5" edition.workspace = true rust-version.workspace = true license.workspace = true diff --git a/proofs/debug/bin/prover-sp1/Cargo.toml b/proofs/debug/bin/prover-sp1/Cargo.toml index e33aa07ba..381c0479a 100644 --- a/proofs/debug/bin/prover-sp1/Cargo.toml +++ b/proofs/debug/bin/prover-sp1/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "world-chain-prover-sp1" -version = "1.0.0-rc.1" +version = "1.0.0-rc.5" edition.workspace = true rust-version.workspace = true license.workspace = true @@ -19,7 +19,7 @@ dotenvy.workspace = true hex.workspace = true serde_json.workspace = true sha2.workspace = true -sp1-sdk = { version = "=6.3.1", features = ["network"] } +sp1-sdk = { version = "=6.8.1", features = ["network"] } tokio.workspace = true world-chain-prover.workspace = true world-chain-proof-core.workspace = true diff --git a/proofs/debug/prover/Cargo.toml b/proofs/debug/prover/Cargo.toml index 070a3893f..cbf64804d 100644 --- a/proofs/debug/prover/Cargo.toml +++ b/proofs/debug/prover/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "world-chain-prover" -version = "1.0.0-rc.1" +version = "1.0.0-rc.5" edition.workspace = true rust-version.workspace = true license.workspace = true diff --git a/proofs/it/Cargo.toml b/proofs/it/Cargo.toml index 75c1f6616..9797c4843 100644 --- a/proofs/it/Cargo.toml +++ b/proofs/it/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "world-chain-proof-it" -version = "1.0.0-rc.1" +version = "1.0.0-rc.5" edition.workspace = true rust-version.workspace = true license.workspace = true diff --git a/proofs/it/src/lib.rs b/proofs/it/src/lib.rs index 4af500381..9b67b4e8d 100644 --- a/proofs/it/src/lib.rs +++ b/proofs/it/src/lib.rs @@ -23,7 +23,7 @@ use world_chain_proof_protocol::{ ClaimData, ConsensusError, ConsensusProvider, GameCreation, GameStatus, InvalidationReason, LineageAnchor, LineageError, LineageGame, LineageProvider, LineageTransition, MAX_ATTEMPT_SCAN, PROOF_SYSTEM_VERSION, PROOF_THRESHOLD, ProofDomain, ProofLane, ProposalCommitment, - ProposalStatus, ResolutionStatus, RootCommitment, has_threshold, + ProposalStatus, RecoveryParent, ResolutionStatus, RootCommitment, has_threshold, }; use world_chain_proof_worker::{ClaimedProofJobHandler, ProofJob}; use world_chain_proposer::{ @@ -65,11 +65,15 @@ impl GameLifecycle { } } - const fn proposal_status(self, proven: bool) -> ProposalStatus { + const fn proposal_status(self, proof_bitmap: u8) -> ProposalStatus { match self { - Self::Proposed if proven => ProposalStatus::UnchallengedAndValidProofProvided, + Self::Proposed if proof_bitmap != 0 => { + ProposalStatus::UnchallengedAndValidProofProvided + } Self::Proposed => ProposalStatus::Unchallenged, - Self::Challenged if proven => ProposalStatus::ChallengedAndValidProofProvided, + Self::Challenged if has_threshold(proof_bitmap) => { + ProposalStatus::ChallengedAndValidProofProvided + } Self::Challenged => ProposalStatus::Challenged, Self::Finalized | Self::Invalidated => ProposalStatus::Resolved, } @@ -338,6 +342,30 @@ impl LineageProvider for FakeExecution { .anchor) } + async fn recovery_parent(&self, game: Address) -> Result { + let state = self.state.lock().expect("fake execution mutex poisoned"); + let record = state + .games_by_address + .get(&game) + .ok_or(LineageError::InvalidRecoveryParent(game))?; + Ok(RecoveryParent { + anchor: LineageAnchor { + address: game, + l2_block_number: record.creation.l2_block_number, + }, + root_claim: record.creation.root_claim, + eligible: record.state == GameLifecycle::Finalized, + }) + } + + async fn lineage_anchor_claim_valid(&self, game: Address) -> Result { + let state = self.state.lock().expect("fake execution mutex poisoned"); + Ok(state + .games_by_address + .get(&game) + .is_some_and(|record| record.state == GameLifecycle::Finalized)) + } + async fn game_for_transition( &self, transition: LineageTransition, @@ -373,13 +401,30 @@ impl LineageProvider for FakeExecution { let outcome = record.state.outcome(); if record.state == GameLifecycle::Finalized { return Ok(ResolutionStatus { + status: outcome, resolvable: false, outcome, invalidation_reason: InvalidationReason::None, }); } + let local_timeout = match record.state { + GameLifecycle::Proposed => record.challenge_deadline == 0 && record.proof_bitmap == 0, + GameLifecycle::Challenged => { + record.proof_deadline == 0 && !has_threshold(record.proof_bitmap) + } + _ => false, + }; + if local_timeout { + return Ok(ResolutionStatus { + status: outcome, + resolvable: !parent_is_unresolved(&state, record), + outcome: GameStatus::ChallengerWins, + invalidation_reason: InvalidationReason::ProofTimeout, + }); + } if parent_is_unresolved(&state, record) { return Ok(ResolutionStatus { + status: outcome, resolvable: false, outcome, invalidation_reason: InvalidationReason::None, @@ -391,35 +436,23 @@ impl LineageProvider for FakeExecution { ) && has_threshold(record.proof_bitmap) { return Ok(ResolutionStatus { + status: outcome, resolvable: true, outcome: GameStatus::DefenderWins, invalidation_reason: InvalidationReason::None, }); } - if record.state == GameLifecycle::Challenged && record.proof_deadline == 0 { - return Ok(ResolutionStatus { - resolvable: true, - outcome: GameStatus::ChallengerWins, - invalidation_reason: InvalidationReason::ProofTimeout, - }); - } if record.state == GameLifecycle::Proposed && record.challenge_deadline == 0 { return Ok(ResolutionStatus { + status: outcome, resolvable: true, - outcome: if record.proof_bitmap == 0 { - GameStatus::ChallengerWins - } else { - GameStatus::DefenderWins - }, - invalidation_reason: if record.proof_bitmap == 0 { - InvalidationReason::ProofTimeout - } else { - InvalidationReason::None - }, + outcome: GameStatus::DefenderWins, + invalidation_reason: InvalidationReason::None, }); } Ok(ResolutionStatus { + status: outcome, resolvable: false, outcome, invalidation_reason: InvalidationReason::None, @@ -548,7 +581,7 @@ impl ChallengerClient for FakeExecution { .games_by_address .get(&game) .map_or(ProposalStatus::Resolved, |record| { - record.state.proposal_status(record.proof_bitmap != 0) + record.state.proposal_status(record.proof_bitmap) })) } @@ -611,7 +644,7 @@ impl DefenderClient for FakeExecution { .games_by_address .get(&game) .map(|record| ClaimData { - status: record.state.proposal_status(record.proof_bitmap != 0), + status: record.state.proposal_status(record.proof_bitmap), challenger: Address::ZERO, deadline: record.proof_deadline, proof_bitmap: record.proof_bitmap, diff --git a/proofs/it/tests/orchestration.rs b/proofs/it/tests/orchestration.rs index 80c446dbb..43f577dc6 100644 --- a/proofs/it/tests/orchestration.rs +++ b/proofs/it/tests/orchestration.rs @@ -22,6 +22,7 @@ use world_chain_prover_service::{ProofBackend, ProverServiceConfig}; fn proposer_config() -> ProposerConfig { ProposerConfig { + recovery_parent: None, poll_interval: Duration::from_secs(1), max_resolutions_per_tick: 1, } @@ -84,6 +85,11 @@ async fn fake_resolution_matches_contract_transition_semantics() { .await .expect("proposal posted"); let game = chain.latest_game().expect("game created").game; + let parent = chain.recovery_parent(game).await.unwrap(); + assert_eq!(parent.root_claim, canonical_root); + assert_eq!(parent.anchor.l2_block_number, BLOCK_INTERVAL); + assert!(!parent.eligible); + assert!(!chain.lineage_anchor_claim_valid(game).await.unwrap()); chain.challenge_game(game); chain @@ -109,6 +115,8 @@ async fn fake_resolution_matches_contract_transition_semantics() { .expect("resolution status available"); assert!(!finalized.resolvable); assert_eq!(finalized.outcome, GameStatus::DefenderWins); + assert!(chain.recovery_parent(game).await.unwrap().eligible); + assert!(chain.lineage_anchor_claim_valid(game).await.unwrap()); assert!(ProposerClient::resolve_game(&chain, game).await.is_err()); } diff --git a/proofs/kona-host/Cargo.toml b/proofs/kona-host/Cargo.toml index aec84effe..7332665b4 100644 --- a/proofs/kona-host/Cargo.toml +++ b/proofs/kona-host/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "world-chain-proof-kona-host" -version = "1.0.0-rc.1" +version = "1.0.0-rc.5" edition.workspace = true rust-version.workspace = true license.workspace = true @@ -12,24 +12,19 @@ workspace = true [dependencies] alloy-consensus.workspace = true -alloy-eips = { workspace = true, features = ["kzg"] } alloy-primitives = { workspace = true, features = ["serde"] } anyhow.workspace = true -async-trait.workspace = true -c-kzg.workspace = true hex.workspace = true -kona-derive.workspace = true kona-genesis.workspace = true kona-host = { workspace = true, features = ["single"] } kona-preimage.workspace = true kona-proof.workspace = true +kona-sp1-host-utils.workspace = true kona-protocol.workspace = true -kzg-rs.workspace = true reqwest = { workspace = true, features = ["blocking", "json", "rustls-tls"] } serde = { workspace = true, features = ["derive"] } serde_json.workspace = true tokio.workspace = true -tracing.workspace = true world-chain-proof-core.workspace = true world-chain-proof-kona-client.workspace = true world-chain-chainspec.workspace = true diff --git a/proofs/kona-host/src/lib.rs b/proofs/kona-host/src/lib.rs index 00383567a..1be21752c 100644 --- a/proofs/kona-host/src/lib.rs +++ b/proofs/kona-host/src/lib.rs @@ -1,4 +1,3 @@ pub mod online; -pub mod witness_generation; -pub use witness_generation::{OnlineBlobStore, PreimageWitnessCollector}; +pub use kona_sp1_host_utils::witness_generation::{OnlineBlobStore, PreimageWitnessCollector}; diff --git a/proofs/kona-host/src/online.rs b/proofs/kona-host/src/online.rs index 16349dc97..2553e9cba 100644 --- a/proofs/kona-host/src/online.rs +++ b/proofs/kona-host/src/online.rs @@ -25,17 +25,18 @@ use kona_preimage::{ PreimageKey, VerifyingPreimageFetcher, }; use kona_proof::{CachingOracle, HintType, l1::OracleBlobProvider}; +use kona_protocol::OutputRoot; use reqwest::Client; use serde::{Deserialize, Serialize, de::DeserializeOwned}; use serde_json::{Value, json}; use world_chain_chainspec::{WorldChainHardfork, WorldChainHardforks}; use world_chain_proof_core::{ hash_world_rollup_config, - range::{WorldRangeHardfork, WorldRangeHardforkConfig, WorldRangeSpecId}, + range::{WorldRangeHardfork, WorldRangeHardforkConfig}, witness::{BlobData, WorldRangeWitnessData, preimage_store::PreimageStore}, }; use world_chain_proof_kona_client::{ - ETHDAWitnessExecutor, OutputRootWitness, WitnessExecutor, get_inputs_for_pipeline, + ETHDAWitnessExecutor, WitnessExecutor, get_inputs_for_pipeline, }; const L1_BLOCK_PREDEPLOY: Address = address!("0x4200000000000000000000000000000000000015"); @@ -215,6 +216,18 @@ pub struct RangeProofInput { pub witness: WorldRangeWitnessData, } +/// Returns whether a failed witness build exhausted its collection deadline. +/// +/// The public builder returns `anyhow::Error` so callers can keep their existing error context; +/// this centralizes the timeout classification used for low-cardinality worker metrics. +pub fn is_witness_generation_timeout(error: &anyhow::Error) -> bool { + error.chain().any(|cause| { + cause + .to_string() + .starts_with("Kona witness generation timed out after ") + }) +} + /// Context captured while building a range witness. #[derive(Clone, Debug, Serialize)] #[serde(rename_all = "camelCase")] @@ -334,8 +347,8 @@ pub async fn build_range_input( &post_block, ) .await?; - let pre_root = pre_state.output_root(); - let post_root = post_state.output_root(); + let pre_root = pre_state.hash(); + let post_root = post_state.hash(); let l1_head = match request.l1_head { Some(hash) => hash, @@ -345,7 +358,6 @@ pub async fn build_range_input( let active_fork = config .schedule .active_fork_at(request.end_block, post_block.timestamp.0); - let world_spec_id = WorldRangeSpecId::from_hardfork(active_fork); let host = SingleChainHost { l1_head, @@ -387,7 +399,7 @@ pub async fn build_range_input( l2_post_root: post_root, rollup_config_hash: config.rollup_config_hash, active_fork: format!("{active_fork:?}"), - world_spec_id: <&'static str>::from(world_spec_id).to_string(), + world_spec_id: format!("{active_fork:?}"), }, witness, }) @@ -395,7 +407,7 @@ pub async fn build_range_input( async fn collect_world_range_witness( host: SingleChainHost, - agreed_output: &OutputRootWitness, + agreed_output: &OutputRoot, schedule: WorldRangeHardforkConfig, timeout: Duration, ) -> anyhow::Result { @@ -408,7 +420,7 @@ async fn collect_world_range_witness( // Kona asks for this preimage to recover the agreed L2 head. Seeding the value avoids // recomputing the post-Isthmus storage root through `eth_getProof`. - let agreed_output_root = agreed_output.output_root(); + let agreed_output_root = agreed_output.hash(); kv_store.write().await.set( PreimageKey::new_keccak256(*agreed_output_root).into(), agreed_output.encode().to_vec(), @@ -556,14 +568,14 @@ async fn output_root_witness( consensus_rpc_url: Option<&str>, block_number: u64, block: &RpcBlock, -) -> anyhow::Result { +) -> anyhow::Result { if schedule.is_active(WorldRangeHardfork::Isthmus, block_number, block.timestamp.0) { - let message_passer_storage_root = block.withdrawals_root.with_context(|| { + let bridge_storage_root = block.withdrawals_root.with_context(|| { format!("post-Isthmus L2 block {block_number} is missing withdrawalsRoot") })?; - return Ok(OutputRootWitness { + return Ok(OutputRoot { state_root: block.state_root, - message_passer_storage_root, + bridge_storage_root, block_hash: block.hash, }); } @@ -601,9 +613,9 @@ async fn output_root_witness( } }; - Ok(OutputRootWitness { + Ok(OutputRoot { state_root: block.state_root, - message_passer_storage_root: proof.storage_hash, + bridge_storage_root: proof.storage_hash, block_hash: block.hash, }) } @@ -613,7 +625,7 @@ async fn output_root_witness_from_op_node( rpc_url: &str, block_number: u64, block: &RpcBlock, -) -> anyhow::Result { +) -> anyhow::Result { let output: OptimismOutputAtBlock = rpc( client, rpc_url, @@ -623,12 +635,12 @@ async fn output_root_witness_from_op_node( .await? .context("optimism_outputAtBlock returned null")?; - let witness = OutputRootWitness { + let witness = OutputRoot { state_root: output.state_root, - message_passer_storage_root: output.withdrawal_storage_root, + bridge_storage_root: output.withdrawal_storage_root, block_hash: block.hash, }; - let computed = witness.output_root(); + let computed = witness.hash(); if computed != output.output_root { bail!( "output root mismatch for block {block_number}: computed {computed}, RPC returned {}", @@ -791,7 +803,7 @@ mod tests { .await .unwrap(); - assert_eq!(witness.message_passer_storage_root, withdrawals_root); + assert_eq!(witness.bridge_storage_root, withdrawals_root); assert_eq!(witness.state_root, block.state_root); assert_eq!(witness.block_hash, block.hash); } @@ -817,15 +829,4 @@ mod tests { assert!(err.to_string().contains("missing withdrawalsRoot")); } - - #[test] - fn starting_output_preimage_matches_output_root() { - let output = OutputRootWitness { - state_root: B256::with_last_byte(1), - message_passer_storage_root: B256::with_last_byte(2), - block_hash: B256::with_last_byte(3), - }; - - assert_eq!(keccak256(output.encode()), output.output_root()); - } } diff --git a/proofs/kona-host/src/witness_generation/mod.rs b/proofs/kona-host/src/witness_generation/mod.rs deleted file mode 100644 index beb5f913b..000000000 --- a/proofs/kona-host/src/witness_generation/mod.rs +++ /dev/null @@ -1,7 +0,0 @@ -//! Host-side witness collection helpers for OP Succinct/Kona execution. - -mod online_blob_store; -pub use online_blob_store::OnlineBlobStore; - -mod preimage_witness_collector; -pub use preimage_witness_collector::PreimageWitnessCollector; diff --git a/proofs/kona-host/src/witness_generation/online_blob_store.rs b/proofs/kona-host/src/witness_generation/online_blob_store.rs deleted file mode 100644 index cd7df4dd8..000000000 --- a/proofs/kona-host/src/witness_generation/online_blob_store.rs +++ /dev/null @@ -1,56 +0,0 @@ -use std::sync::{Arc, Mutex}; - -use alloy_consensus::Blob; -use alloy_eips::eip4844::env_settings::EnvKzgSettings; -use alloy_primitives::B256; -use anyhow::Result; -use async_trait::async_trait; -use kona_derive::BlobProvider; -use kona_protocol::BlockInfo; -use kzg_rs::{Blob as KzgRsBlob, Bytes48}; -use world_chain_proof_core::witness::BlobData; - -#[derive(Clone, Debug)] -pub struct OnlineBlobStore { - pub provider: T, - pub store: Arc>, -} - -impl OnlineBlobStore { - fn record_blob(&self, blob: &Blob) { - let settings = EnvKzgSettings::default(); - let c_kzg_blob = c_kzg::Blob::from_bytes(blob.as_slice()).unwrap(); - let commitment = settings.get().blob_to_kzg_commitment(&c_kzg_blob).unwrap(); - let proof = settings - .get() - .compute_blob_kzg_proof(&c_kzg_blob, &commitment.to_bytes()) - .unwrap(); - - let mut store = self.store.lock().unwrap(); - store - .blobs - .push(KzgRsBlob::from_slice(&*c_kzg_blob).unwrap()); - store.commitments.push(Bytes48(*commitment.to_bytes())); - store.proofs.push(Bytes48(*proof.to_bytes())); - } -} - -#[async_trait] -impl BlobProvider for OnlineBlobStore { - type Error = T::Error; - - async fn get_and_validate_blobs( - &mut self, - block_ref: &BlockInfo, - blob_hashes: &[B256], - ) -> Result>, Self::Error> { - let blobs = self - .provider - .get_and_validate_blobs(block_ref, blob_hashes) - .await?; - for blob in &blobs { - self.record_blob(blob); - } - Ok(blobs) - } -} diff --git a/proofs/kona-host/src/witness_generation/preimage_witness_collector.rs b/proofs/kona-host/src/witness_generation/preimage_witness_collector.rs deleted file mode 100644 index bc00fa9ee..000000000 --- a/proofs/kona-host/src/witness_generation/preimage_witness_collector.rs +++ /dev/null @@ -1,64 +0,0 @@ -use std::sync::{Arc, Mutex}; - -use async_trait::async_trait; -use kona_preimage::{ - CommsClient, HintWriterClient, PreimageKey, PreimageOracleClient, - errors::{PreimageOracleError, PreimageOracleResult}, -}; -use kona_proof::FlushableCache; -use world_chain_proof_core::witness::preimage_store::PreimageStore; - -#[derive(Clone, Debug)] -pub struct PreimageWitnessCollector { - pub preimage_oracle: Arc

, - pub preimage_witness_store: Arc>, -} - -#[async_trait] -impl

PreimageOracleClient for PreimageWitnessCollector

-where - P: CommsClient + FlushableCache + Send + Sync + Clone, -{ - async fn get(&self, key: PreimageKey) -> PreimageOracleResult> { - let value = self.preimage_oracle.get(key).await?; - self.save(key, &value)?; - Ok(value) - } - - async fn get_exact(&self, key: PreimageKey, buf: &mut [u8]) -> PreimageOracleResult<()> { - self.preimage_oracle.get_exact(key, buf).await?; - self.save(key, buf)?; - Ok(()) - } -} - -#[async_trait] -impl

HintWriterClient for PreimageWitnessCollector

-where - P: CommsClient + FlushableCache + Send + Sync + Clone, -{ - async fn write(&self, hint: &str) -> PreimageOracleResult<()> { - self.preimage_oracle.write(hint).await - } -} - -impl

FlushableCache for PreimageWitnessCollector

-where - P: CommsClient + FlushableCache + Send + Sync + Clone, -{ - fn flush(&self) { - self.preimage_oracle.flush(); - } -} - -impl

PreimageWitnessCollector

-where - P: CommsClient + FlushableCache + Send + Sync + Clone, -{ - pub fn save(&self, key: PreimageKey, value: &[u8]) -> PreimageOracleResult<()> { - let mut witness_store_lock = self.preimage_witness_store.lock().map_err(|_| { - PreimageOracleError::Other("failed to acquire preimage witness store lock".to_string()) - })?; - witness_store_lock.save_preimage(key, value.to_vec()) - } -} diff --git a/proofs/measured/core/Cargo.toml b/proofs/measured/core/Cargo.toml index 158c3289d..d6fa18457 100644 --- a/proofs/measured/core/Cargo.toml +++ b/proofs/measured/core/Cargo.toml @@ -11,7 +11,7 @@ resolver = "3" members = ["."] [workspace.package] -version = "1.0.0-rc.1" +version = "1.0.0-rc.5" edition = "2024" rust-version = "1.95.0" license = "MIT" @@ -22,25 +22,26 @@ repository = "https://github.com/worldcoin/world-chain/" semicolon_in_expressions_from_macros = "allow" [workspace.dependencies] -alloy-consensus = { version = "=2.1.1", default-features = false } -alloy-eips = { version = "=2.1.1", default-features = false, features = [ +alloy-consensus = { version = "2.3.0", default-features = false } +alloy-eips = { version = "2.3.0", default-features = false, features = [ "serde", ] } -alloy-primitives = { version = "1.6.0", default-features = false, features = [ +alloy-primitives = { version = "1.6.1", default-features = false, features = [ "std", "map-foldhash", ] } -alloy-sol-types = "1.6.0" +alloy-sol-types = "1.6.1" anyhow = { version = "1.0.86", default-features = false } async-trait = "0.1.88" -kona-derive = { git = "https://github.com/ethereum-optimism/optimism", rev = "96ffbb2a94f19886fe7e27c45f3310e64ccd18b3", default-features = false } -kona-genesis = { git = "https://github.com/ethereum-optimism/optimism", rev = "96ffbb2a94f19886fe7e27c45f3310e64ccd18b3", default-features = false } -kona-preimage = { git = "https://github.com/ethereum-optimism/optimism", rev = "96ffbb2a94f19886fe7e27c45f3310e64ccd18b3", features = [ +kona-derive = { git = "https://github.com/ethereum-optimism/optimism", rev = "da6d3252491754837a778061db0cc47236ec13c6", default-features = false } +kona-genesis = { git = "https://github.com/ethereum-optimism/optimism", rev = "da6d3252491754837a778061db0cc47236ec13c6", default-features = false } +kona-preimage = { git = "https://github.com/ethereum-optimism/optimism", rev = "da6d3252491754837a778061db0cc47236ec13c6", features = [ "rkyv", "serde", ] } -kona-proof = { git = "https://github.com/ethereum-optimism/optimism", rev = "96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" } -kona-protocol = { git = "https://github.com/ethereum-optimism/optimism", rev = "96ffbb2a94f19886fe7e27c45f3310e64ccd18b3", default-features = false } +kona-sp1-client-utils = { git = "https://github.com/ethereum-optimism/optimism", rev = "da6d3252491754837a778061db0cc47236ec13c6" } +kona-proof = { git = "https://github.com/ethereum-optimism/optimism", rev = "da6d3252491754837a778061db0cc47236ec13c6" } +kona-protocol = { git = "https://github.com/ethereum-optimism/optimism", rev = "da6d3252491754837a778061db0cc47236ec13c6", default-features = false } kzg-rs = { version = "0.2.8", features = ["rkyv", "serde"] } rkyv = { version = "0.8", features = ["hashbrown-0_15", "std"] } serde = { version = "1", features = ["derive"] } @@ -59,20 +60,20 @@ repository.workspace = true description = "Shared proof primitives for World Chain fault-proof backends (SP1 and Nitro TEE)." [dependencies] -alloy-consensus.workspace = true -alloy-eips.workspace = true alloy-primitives = { workspace = true, features = ["serde"] } alloy-sol-types.workspace = true -anyhow.workspace = true -async-trait.workspace = true -kona-derive.workspace = true kona-genesis.workspace = true -kona-preimage.workspace = true kona-proof.workspace = true -kona-protocol.workspace = true -kzg-rs.workspace = true +kona-sp1-client-utils.workspace = true rkyv.workspace = true serde = { workspace = true, features = ["derive"] } serde_json.workspace = true sha2.workspace = true thiserror.workspace = true + +[dev-dependencies] +alloy-eips.workspace = true +kona-derive.workspace = true +kona-preimage.workspace = true +kona-protocol.workspace = true +kzg-rs.workspace = true diff --git a/proofs/measured/core/src/lib.rs b/proofs/measured/core/src/lib.rs index 4cae3f710..52a99dbb1 100644 --- a/proofs/measured/core/src/lib.rs +++ b/proofs/measured/core/src/lib.rs @@ -9,7 +9,6 @@ extern crate alloc; pub mod artifacts; pub mod boot; -pub mod oracle; pub mod range; pub mod types; pub mod witness; @@ -18,5 +17,5 @@ pub use boot::{ RollupConfigHashError, hash_rollup_config, hash_world_rollup_config, hash_world_rollup_config_generic, }; -pub use oracle::BlobStore; +pub use kona_sp1_client_utils::BlobStore; pub use witness::preimage_store::PreimageStore; diff --git a/proofs/measured/core/src/oracle/blob_provider.rs b/proofs/measured/core/src/oracle/blob_provider.rs deleted file mode 100644 index 745939c7f..000000000 --- a/proofs/measured/core/src/oracle/blob_provider.rs +++ /dev/null @@ -1,96 +0,0 @@ -use alloc::{boxed::Box, vec::Vec}; -use alloy_consensus::Blob; -use alloy_eips::eip4844::kzg_to_versioned_hash; -use alloy_primitives::B256; -use async_trait::async_trait; -use kona_derive::{BlobProvider, BlobProviderError}; -use kona_protocol::BlockInfo; -use kzg_rs::{KzgError, get_kzg_settings}; - -use crate::witness::BlobData; - -#[derive(Clone, Debug, Default)] -pub struct BlobStore { - versioned_blobs: Vec<(B256, Blob)>, -} - -/// Errors that can occur while converting raw [`BlobData`] into a verified [`BlobStore`]. -/// -/// The conversion is fallible because both the blob payload bytes and the KZG -/// proofs/commitments come from the preimage oracle (which in turn was populated from the L1 -/// beacon chain). Malformed or tampered data must surface as a `Result` rather than a panic -/// because callers run inside the guest program and we never want network-controlled input to -/// abort the zkVM. -#[derive(Debug, thiserror::Error)] -pub enum BlobStoreError { - /// One of the raw blob byte slices was not 4096 field elements wide. - #[error("invalid blob bytes at index {index}: {error:?}")] - InvalidBlob { - /// Position of the offending blob in [`BlobData::blobs`]. - index: usize, - /// Underlying KZG error returned by `kzg_rs`. `kzg_rs::KzgError` does not implement - /// `std::error::Error`, so it is intentionally not annotated with `#[source]`. - error: KzgError, - }, - /// KZG batch verification reported the proofs as invalid. - #[error("kzg batch proof verification failed: proofs are invalid")] - InvalidProofs, - /// KZG batch verification returned an internal error. - #[error("kzg batch proof verification error: {0:?}")] - KzgError(KzgError), -} - -impl TryFrom for BlobStore { - type Error = BlobStoreError; - - fn try_from(value: BlobData) -> Result { - let blobs: Vec = value - .blobs - .iter() - .enumerate() - .map(|(index, b)| { - kzg_rs::Blob::from_slice(&b.0) - .map_err(|error| BlobStoreError::InvalidBlob { index, error }) - }) - .collect::>()?; - let versioned_blobs = value - .commitments - .iter() - .map(|c| kzg_to_versioned_hash(c.as_slice())) - .zip(blobs.iter().map(|b| Blob::from(b.0))) - .rev() - .collect(); - - match kzg_rs::KzgProof::verify_blob_kzg_proof_batch( - blobs, - value.commitments, - value.proofs, - &get_kzg_settings(), - ) { - Ok(true) => {} - Ok(false) => return Err(BlobStoreError::InvalidProofs), - Err(e) => return Err(BlobStoreError::KzgError(e)), - } - - Ok(Self { versioned_blobs }) - } -} - -#[async_trait] -impl BlobProvider for BlobStore { - type Error = BlobProviderError; - - async fn get_and_validate_blobs( - &mut self, - _: &BlockInfo, - blob_hashes: &[B256], - ) -> Result>, Self::Error> { - Ok(blob_hashes - .iter() - .filter_map(|hash| { - let (blob_hash, blob) = self.versioned_blobs.pop().unwrap(); - (*hash == blob_hash).then(|| Box::new(blob)) - }) - .collect()) - } -} diff --git a/proofs/measured/core/src/oracle/mod.rs b/proofs/measured/core/src/oracle/mod.rs deleted file mode 100644 index 912b408ed..000000000 --- a/proofs/measured/core/src/oracle/mod.rs +++ /dev/null @@ -1,2 +0,0 @@ -mod blob_provider; -pub use blob_provider::BlobStore; diff --git a/proofs/measured/core/src/range.rs b/proofs/measured/core/src/range.rs index b3741d372..3a1967572 100644 --- a/proofs/measured/core/src/range.rs +++ b/proofs/measured/core/src/range.rs @@ -140,76 +140,6 @@ pub enum WorldRangeHardfork { Strato, } -/// World proof spec id used by the range proof wrapper. -#[repr(u8)] -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[allow(non_camel_case_types)] -pub enum WorldRangeSpecId { - /// Bedrock spec id. - BEDROCK = 100, - /// Regolith spec id. - REGOLITH, - /// Canyon spec id. - CANYON, - /// Ecotone spec id. - ECOTONE, - /// Fjord spec id. - FJORD, - /// Granite spec id. - GRANITE, - /// Holocene spec id. - HOLOCENE, - /// Isthmus spec id. - ISTHMUS, - /// Jovian spec id. - JOVIAN, - /// Karst spec id. - KARST, - /// Tropo spec id. - TROPO, - /// Strato spec id. - STRATO, -} - -impl WorldRangeSpecId { - /// Converts a World hardfork name to the corresponding proof spec id. - pub const fn from_hardfork(hardfork: WorldRangeHardfork) -> Self { - match hardfork { - WorldRangeHardfork::Bedrock => Self::BEDROCK, - WorldRangeHardfork::Regolith => Self::REGOLITH, - WorldRangeHardfork::Canyon => Self::CANYON, - WorldRangeHardfork::Ecotone => Self::ECOTONE, - WorldRangeHardfork::Fjord => Self::FJORD, - WorldRangeHardfork::Granite => Self::GRANITE, - WorldRangeHardfork::Holocene => Self::HOLOCENE, - WorldRangeHardfork::Isthmus => Self::ISTHMUS, - WorldRangeHardfork::Jovian => Self::JOVIAN, - WorldRangeHardfork::Karst => Self::KARST, - WorldRangeHardfork::Tropo => Self::TROPO, - WorldRangeHardfork::Strato => Self::STRATO, - } - } -} - -impl From for &'static str { - fn from(spec_id: WorldRangeSpecId) -> Self { - match spec_id { - WorldRangeSpecId::BEDROCK => "Bedrock", - WorldRangeSpecId::REGOLITH => "Regolith", - WorldRangeSpecId::CANYON => "Canyon", - WorldRangeSpecId::ECOTONE => "Ecotone", - WorldRangeSpecId::FJORD => "Fjord", - WorldRangeSpecId::GRANITE => "Granite", - WorldRangeSpecId::HOLOCENE => "Holocene", - WorldRangeSpecId::ISTHMUS => "Isthmus", - WorldRangeSpecId::JOVIAN => "Jovian", - WorldRangeSpecId::KARST => "Karst", - WorldRangeSpecId::TROPO => "Tropo", - WorldRangeSpecId::STRATO => "Strato", - } - } -} - #[cfg(test)] mod tests { use super::*; @@ -252,13 +182,5 @@ mod tests { assert_eq!(config.active_fork_at(1, 20), WorldRangeHardfork::Karst); assert_eq!(config.active_fork_at(1, 30), WorldRangeHardfork::Tropo); assert_eq!(config.active_fork_at(1, 40), WorldRangeHardfork::Strato); - assert_eq!( - WorldRangeSpecId::from_hardfork(config.active_fork_at(1, 20)), - WorldRangeSpecId::KARST - ); - assert_eq!( - WorldRangeSpecId::from_hardfork(config.active_fork_at(1, 40)), - WorldRangeSpecId::STRATO - ); } } diff --git a/proofs/measured/core/src/types.rs b/proofs/measured/core/src/types.rs index a656ce322..fd218a7fa 100644 --- a/proofs/measured/core/src/types.rs +++ b/proofs/measured/core/src/types.rs @@ -25,34 +25,3 @@ sol! { bytes32 multiBlockVKey; } } - -/// Converts an SP1 vkey digest from `[u32; 8]` to the bytes used on-chain. -pub fn u32_to_u8(input: [u32; 8]) -> [u8; 32] { - std::array::from_fn(|i| input[i / 4].to_be_bytes()[i % 4]) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn converts_vkey_words_big_endian() { - let words = [ - 0x0102_0304, - 0x0506_0708, - 0x090a_0b0c, - 0x0d0e_0f10, - 0x1112_1314, - 0x1516_1718, - 0x191a_1b1c, - 0x1d1e_1f20, - ]; - assert_eq!( - u32_to_u8(words), - [ - 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, - ] - ); - } -} diff --git a/proofs/measured/core/src/witness/mod.rs b/proofs/measured/core/src/witness/mod.rs index 1aa3379d4..d93ed2a24 100644 --- a/proofs/measured/core/src/witness/mod.rs +++ b/proofs/measured/core/src/witness/mod.rs @@ -1,44 +1,7 @@ -pub mod preimage_store; - -use std::sync::Arc; - -use anyhow::Result; -use async_trait::async_trait; -use kzg_rs::{Blob, Bytes48}; +pub use kona_sp1_client_utils::witness::{BlobData, WitnessData, preimage_store}; use preimage_store::PreimageStore; -use serde::{Deserialize, Serialize}; - -use crate::{oracle::BlobStore, range::WorldRangeHardforkConfig}; - -#[async_trait] -pub trait WitnessData: Sized { - /// Creates a new WitnessData from the given preimage store and blob data. - fn from_parts(preimage_store: PreimageStore, blob_data: BlobData) -> Self; - - /// Consumes the WitnessData to extract its core components. - fn into_parts(self) -> (PreimageStore, BlobData); - - /// Gets the oracle and blob provider from the witness data and validates the correctness of the - /// preimages. - async fn get_oracle_and_blob_provider(self) -> Result<(Arc, BlobStore)> { - let (owned_preimage_store, owned_blob_data) = self.into_parts(); - println!("cycle-tracker-report-start: oracle-verify"); - owned_preimage_store - .check_preimages() - .expect("Failed to validate preimages"); - println!("cycle-tracker-report-end: oracle-verify"); - - let oracle = Arc::new(owned_preimage_store); - - println!("cycle-tracker-report-start: blob-verification"); - let beacon = BlobStore::try_from(owned_blob_data) - .map_err(|err| anyhow::anyhow!("failed to verify blob data: {err}"))?; - println!("cycle-tracker-report-end: blob-verification"); - - Ok((oracle, beacon)) - } -} +use crate::range::WorldRangeHardforkConfig; #[derive(Clone, Debug, Default, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)] pub struct WorldRangeWitnessData { @@ -47,7 +10,6 @@ pub struct WorldRangeWitnessData { pub schedule: WorldRangeHardforkConfig, } -#[async_trait] impl WitnessData for WorldRangeWitnessData { fn from_parts(preimage_store: PreimageStore, blob_data: BlobData) -> Self { Self { @@ -76,11 +38,87 @@ impl WorldRangeWitnessData { } } -#[derive( - Clone, Debug, Default, Serialize, Deserialize, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, -)] -pub struct BlobData { - pub blobs: Vec, - pub commitments: Vec, - pub proofs: Vec, +#[cfg(test)] +mod tests { + use super::*; + use alloy_eips::eip4844::kzg_to_versioned_hash; + use alloy_primitives::{hex_literal::hex, keccak256}; + use kona_derive::BlobProvider; + use kona_preimage::{PreimageKey, PreimageOracleClient}; + use kona_proof::block_on; + use kona_protocol::BlockInfo; + use kzg_rs::{Blob, Bytes48}; + + fn blob_data() -> BlobData { + // Constant-zero and constant-two vectors from kzg-rs 0.2.8's verify_blob_kzg_proof tests. + let mut infinity = [0; 48]; + infinity[0] = 0xc0; + let two_commitment = hex!( + "a572cbea904d67468808c8eb50a9450c9721db309128012543902d0ac358a62ae28f75bb8f1c7c42c39a8c5529bf0f4e" + ); + let mut twos = vec![0; 131072]; + for field in twos.as_chunks_mut::<32>().0 { + field[31] = 2; + } + BlobData { + blobs: vec![ + Blob::from_slice(&vec![0; 131072]).unwrap(), + Blob::from_slice(&twos).unwrap(), + ], + commitments: vec![Bytes48(infinity), Bytes48(two_commitment)], + proofs: vec![Bytes48(infinity); 2], + } + } + + #[test] + fn world_witness_roundtrip_preserves_schedule_and_preimages() { + let value = b"world witness".to_vec(); + let key = PreimageKey::new_keccak256(keccak256(&value).0); + let mut preimages = PreimageStore::default(); + preimages.save_preimage(key, value.clone()).unwrap(); + let schedule = WorldRangeHardforkConfig { + tropo_time: Some(42), + strato_time: Some(84), + ..Default::default() + }; + let witness = WorldRangeWitnessData::from_parts_with_world_config( + preimages, + BlobData::default(), + schedule.clone(), + ); + let bytes = rkyv::to_bytes::(&witness).unwrap(); + let decoded = + rkyv::from_bytes::(&bytes).unwrap(); + assert_eq!(decoded.schedule, schedule); + assert_eq!(block_on(decoded.preimage_store.get(key)).unwrap(), value); + } + + #[test] + fn upstream_witness_returns_verified_blobs_in_requested_order() { + let data = blob_data(); + let hashes: Vec<_> = data + .commitments + .iter() + .map(|c| kzg_to_versioned_hash(c.as_slice())) + .collect(); + let expected_first = data.blobs[1].0.to_vec(); + let expected_second = data.blobs[0].0.to_vec(); + let witness = WorldRangeWitnessData::from_parts(PreimageStore::default(), data); + let (_, mut store) = block_on(witness.get_oracle_and_blob_provider()).unwrap(); + let result = + block_on(store.get_and_validate_blobs(&BlockInfo::default(), &[hashes[1], hashes[0]])) + .unwrap(); + assert_eq!(result.len(), 2); + assert_eq!(result[0].as_slice(), expected_first); + assert_eq!(result[1].as_slice(), expected_second); + } + + #[test] + #[should_panic(expected = "KZG proof verification failed: invalid proofs")] + fn upstream_witness_rejects_invalid_blob_proof() { + let mut data = blob_data(); + data.blobs.swap(0, 1); + let witness = WorldRangeWitnessData::from_parts(PreimageStore::default(), data); + let _ = block_on(witness.get_oracle_and_blob_provider()); + } } diff --git a/proofs/measured/core/src/witness/preimage_store.rs b/proofs/measured/core/src/witness/preimage_store.rs deleted file mode 100644 index 831220346..000000000 --- a/proofs/measured/core/src/witness/preimage_store.rs +++ /dev/null @@ -1,86 +0,0 @@ -use alloy_primitives::keccak256; -use async_trait::async_trait; -use kona_preimage::{ - HintWriterClient, PreimageKey, PreimageKeyType, PreimageOracleClient, - errors::{PreimageOracleError, PreimageOracleResult}, -}; -use kona_proof::FlushableCache; -use serde::{Deserialize, Serialize}; -use sha2::Digest; -use std::collections::{HashMap, hash_map::Entry}; - -#[derive( - Clone, Debug, Default, Serialize, Deserialize, rkyv::Serialize, rkyv::Archive, rkyv::Deserialize, -)] -pub struct PreimageStore { - pub preimage_map: HashMap>, -} - -impl PreimageStore { - pub fn check_preimages(&self) -> PreimageOracleResult<()> { - for (key, value) in &self.preimage_map { - check_preimage(key, value)?; - } - Ok(()) - } - - pub fn save_preimage(&mut self, key: PreimageKey, value: Vec) -> PreimageOracleResult<()> { - check_preimage(&key, &value)?; - - match self.preimage_map.entry(key) { - Entry::Vacant(e) => { - e.insert(value); - } - Entry::Occupied(e) => { - if e.get() != &value { - return Err(PreimageOracleError::Other( - "cannot overwrite key".to_string(), - )); - } - } - }; - - Ok(()) - } -} - -/// Check that the preimage matches the expected hash. -pub fn check_preimage(key: &PreimageKey, value: &[u8]) -> PreimageOracleResult<()> { - if let Some(expected_hash) = match key.key_type() { - PreimageKeyType::Keccak256 => Some(keccak256(value).0), - PreimageKeyType::Sha256 => Some(sha2::Sha256::digest(value).into()), - PreimageKeyType::Local | PreimageKeyType::GlobalGeneric => None, - PreimageKeyType::Precompile => unimplemented!("Precompile not supported in zkVM"), - PreimageKeyType::Blob => unreachable!("Blob keys validated in blob witness"), - } && key != &PreimageKey::new(expected_hash, key.key_type()) - { - return Err(PreimageOracleError::InvalidPreimageKey); - } - Ok(()) -} - -#[async_trait] -impl HintWriterClient for PreimageStore { - async fn write(&self, _hint: &str) -> PreimageOracleResult<()> { - Ok(()) - } -} - -#[async_trait] -impl PreimageOracleClient for PreimageStore { - async fn get(&self, key: PreimageKey) -> PreimageOracleResult> { - let Some(value) = self.preimage_map.get(&key) else { - return Err(PreimageOracleError::InvalidPreimageKey); - }; - Ok(value.clone()) - } - - async fn get_exact(&self, key: PreimageKey, buf: &mut [u8]) -> PreimageOracleResult<()> { - buf.copy_from_slice(&self.get(key).await?); - Ok(()) - } -} - -impl FlushableCache for PreimageStore { - fn flush(&self) {} -} diff --git a/proofs/measured/kona-client/Cargo.toml b/proofs/measured/kona-client/Cargo.toml index dcd0a9d1b..ac63bec1b 100644 --- a/proofs/measured/kona-client/Cargo.toml +++ b/proofs/measured/kona-client/Cargo.toml @@ -7,7 +7,7 @@ resolver = "3" members = ["."] [workspace.package] -version = "1.0.0-rc.1" +version = "1.0.0-rc.5" edition = "2024" rust-version = "1.95.0" license = "MIT" @@ -19,13 +19,10 @@ semicolon_in_expressions_from_macros = "allow" [workspace.dependencies] world-chain-proof-core = { path = "../core", default-features = false } -alloy-consensus = { version = "=2.1.1", default-features = false } -alloy-eips = { version = "=2.1.1", default-features = false, features = [ - "serde", -] } -alloy-evm = { version = "0.37.0", default-features = false } -alloy-op-evm = { git = "https://github.com/ethereum-optimism/optimism", rev = "96ffbb2a94f19886fe7e27c45f3310e64ccd18b3", default-features = false } -alloy-primitives = { version = "1.6.0", default-features = false, features = [ +alloy-consensus = { version = "2.3.0", default-features = false } +alloy-evm = { version = "0.38.0", default-features = false } +alloy-op-evm = { git = "https://github.com/ethereum-optimism/optimism", rev = "da6d3252491754837a778061db0cc47236ec13c6", default-features = false } +alloy-primitives = { version = "1.6.1", default-features = false, features = [ "std", "map-foldhash", ] } @@ -34,21 +31,17 @@ alloy-rlp = { version = "0.3.16", default-features = false, features = [ ] } anyhow = { version = "1.0.86", default-features = false } async-trait = "0.1.88" -kona-derive = { git = "https://github.com/ethereum-optimism/optimism", rev = "96ffbb2a94f19886fe7e27c45f3310e64ccd18b3", default-features = false } -kona-driver = { git = "https://github.com/ethereum-optimism/optimism", rev = "96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" } -kona-executor = { git = "https://github.com/ethereum-optimism/optimism", rev = "96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" } -kona-genesis = { git = "https://github.com/ethereum-optimism/optimism", rev = "96ffbb2a94f19886fe7e27c45f3310e64ccd18b3", default-features = false } -kona-preimage = { git = "https://github.com/ethereum-optimism/optimism", rev = "96ffbb2a94f19886fe7e27c45f3310e64ccd18b3", features = [ +kona-derive = { git = "https://github.com/ethereum-optimism/optimism", rev = "da6d3252491754837a778061db0cc47236ec13c6", default-features = false } +kona-driver = { git = "https://github.com/ethereum-optimism/optimism", rev = "da6d3252491754837a778061db0cc47236ec13c6" } +kona-genesis = { git = "https://github.com/ethereum-optimism/optimism", rev = "da6d3252491754837a778061db0cc47236ec13c6", default-features = false } +kona-preimage = { git = "https://github.com/ethereum-optimism/optimism", rev = "da6d3252491754837a778061db0cc47236ec13c6", features = [ "rkyv", "serde", ] } -kona-proof = { git = "https://github.com/ethereum-optimism/optimism", rev = "96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" } -kona-protocol = { git = "https://github.com/ethereum-optimism/optimism", rev = "96ffbb2a94f19886fe7e27c45f3310e64ccd18b3", default-features = false } -kzg-rs = { version = "0.2.8", features = ["rkyv", "serde"] } -op-alloy-consensus = { git = "https://github.com/ethereum-optimism/optimism", rev = "96ffbb2a94f19886fe7e27c45f3310e64ccd18b3", default-features = false } -op-revm = { git = "https://github.com/ethereum-optimism/optimism", rev = "96ffbb2a94f19886fe7e27c45f3310e64ccd18b3", default-features = false } -revm = { version = "41.0.0", default-features = false } -revm-precompile = { version = "41.0.0", default-features = false } +kona-proof = { git = "https://github.com/ethereum-optimism/optimism", rev = "da6d3252491754837a778061db0cc47236ec13c6" } +kona-sp1-client-utils = { git = "https://github.com/ethereum-optimism/optimism", rev = "da6d3252491754837a778061db0cc47236ec13c6" } +op-revm = { git = "https://github.com/ethereum-optimism/optimism", rev = "da6d3252491754837a778061db0cc47236ec13c6", default-features = false } +revm = { version = "42.0.1", default-features = false } serde = { version = "1", features = ["derive"] } spin = "0.10" tracing = "0.1" @@ -65,9 +58,11 @@ repository.workspace = true [lints] workspace = true +[features] +bn = ["revm/bn"] + [dependencies] alloy-consensus.workspace = true -alloy-eips.workspace = true alloy-evm.workspace = true alloy-op-evm.workspace = true alloy-primitives = { workspace = true, features = ["serde"] } @@ -76,17 +71,15 @@ anyhow.workspace = true async-trait.workspace = true kona-derive.workspace = true kona-driver.workspace = true -kona-executor.workspace = true kona-genesis.workspace = true kona-preimage.workspace = true kona-proof.workspace = true -kona-protocol.workspace = true -kzg-rs.workspace = true -op-alloy-consensus.workspace = true +kona-sp1-client-utils.workspace = true op-revm.workspace = true revm.workspace = true -revm-precompile.workspace = true -serde = { workspace = true, features = ["derive"] } spin.workspace = true tracing.workspace = true world-chain-proof-core.workspace = true + +[dev-dependencies] +serde_json = "1" diff --git a/proofs/measured/kona-client/src/client.rs b/proofs/measured/kona-client/src/client.rs deleted file mode 100644 index 24cfe3e92..000000000 --- a/proofs/measured/kona-client/src/client.rs +++ /dev/null @@ -1,210 +0,0 @@ -use alloy_consensus::BlockBody; -use alloy_eips::eip2718::Decodable2718; -use alloy_primitives::B256; -use anyhow::Result; -use kona_derive::{Pipeline, PipelineError, PipelineErrorKind, Signal, SignalReceiver}; -use kona_driver::{Driver, DriverError, DriverPipeline, DriverResult, Executor, TipCursor}; -use kona_genesis::RollupConfig; -use kona_preimage::{CommsClient, PreimageKey}; -use kona_proof::{HintType, errors::OracleProviderError}; -use kona_protocol::{FromBlockError, L2BlockInfo}; -use op_alloy_consensus::{OpBlock, OpTxEnvelope, OpTxType}; -use std::fmt::Debug; -use tracing::{error, info, warn}; - -/// Fetches the safe head hash of the L2 chain based on the agreed upon L2 output root. -pub async fn fetch_safe_head_hash( - caching_oracle: &O, - agreed_l2_output_root: B256, -) -> Result -where - O: CommsClient, -{ - let mut output_preimage = [0u8; 128]; - HintType::StartingL2Output - .with_data(&[agreed_l2_output_root.as_ref()]) - .send(caching_oracle) - .await?; - caching_oracle - .get_exact( - PreimageKey::new_keccak256(*agreed_l2_output_root), - output_preimage.as_mut(), - ) - .await?; - - output_preimage[96..128] - .try_into() - .map_err(OracleProviderError::SliceConversion) -} - -/// Advances the derivation pipeline to the target block number. -#[allow(clippy::result_large_err)] -pub async fn advance_to_target( - driver: &mut Driver, - cfg: &RollupConfig, - mut target: Option, -) -> DriverResult<(L2BlockInfo, B256), E::Error> -where - E: Executor + Send + Sync + Debug, - DP: DriverPipeline

+ Send + Sync + Debug, - P: Pipeline + SignalReceiver + Send + Sync + Debug, -{ - let start_block_number = driver.cursor.read().tip().l2_safe_head.block_info.number; - // Progress is logged at least every 10% of the range, but never less often than every - // 100 blocks, so small ranges still get a handful of updates and huge ranges don't get - // spammed. `target` is `None` for open-ended derivation (no fixed range), in which case - // we just fall back to a flat every-100-blocks cadence. - let progress_interval = target - .map(|target_block| { - target_block - .saturating_sub(start_block_number) - .max(1) - .div_ceil(10) - .min(100) - }) - .unwrap_or(100) - .max(1); - let mut last_logged_block_number = start_block_number; - - loop { - let pipeline_cursor = driver.cursor.read(); - let tip_cursor = pipeline_cursor.tip(); - if let Some(tb) = target - && tip_cursor.l2_safe_head.block_info.number >= tb - { - info!(target: "client", "Derivation complete, reached L2 safe head."); - return Ok((tip_cursor.l2_safe_head, tip_cursor.l2_safe_head_output_root)); - } - - #[cfg(target_os = "zkvm")] - println!("cycle-tracker-report-start: payload-derivation"); - let mut attributes = match driver - .pipeline - .produce_payload(tip_cursor.l2_safe_head) - .await - { - Ok(attrs) => attrs.take_inner(), - Err(PipelineErrorKind::Critical(PipelineError::EndOfSource)) => { - warn!(target: "client", "Exhausted data source; Halting derivation and using current safe head."); - - if target.is_some() { - target = Some(tip_cursor.l2_safe_head.block_info.number); - }; - - if cfg.is_interop_active(driver.cursor.read().l2_safe_head().block_info.timestamp) { - return Err(PipelineError::EndOfSource.crit().into()); - } else { - continue; - } - } - Err(e) => { - error!(target: "client", "Failed to produce payload: {:?}", e); - return Err(DriverError::Pipeline(e)); - } - }; - #[cfg(target_os = "zkvm")] - println!("cycle-tracker-report-end: payload-derivation"); - - driver - .executor - .update_safe_head(tip_cursor.l2_safe_head_header.clone()); - - #[cfg(target_os = "zkvm")] - println!("cycle-tracker-report-start: block-execution"); - let outcome = match driver.executor.execute_payload(attributes.clone()).await { - Ok(outcome) => outcome, - Err(e) => { - error!(target: "client", "Failed to execute L2 block: {}", e); - - if cfg.is_holocene_active(attributes.payload_attributes.timestamp) { - warn!(target: "client", "Flushing current channel and retrying deposit only block"); - - driver.pipeline.signal(Signal::FlushChannel).await?; - - attributes.transactions = attributes.transactions.map(|txs| { - txs.into_iter() - .filter(|tx| !tx.is_empty() && tx[0] == OpTxType::Deposit as u8) - .collect::>() - }); - - driver - .executor - .update_safe_head(tip_cursor.l2_safe_head_header.clone()); - match driver.executor.execute_payload(attributes.clone()).await { - Ok(header) => header, - Err(e) => { - error!( - target: "client", - "Critical - Failed to execute deposit-only block: {e}", - ); - return Err(DriverError::Executor(e)); - } - } - } else { - continue; - } - } - }; - #[cfg(target_os = "zkvm")] - println!("cycle-tracker-report-end: block-execution"); - - let block = OpBlock { - header: outcome.header.inner().clone(), - body: BlockBody { - transactions: attributes - .transactions - .as_ref() - .unwrap_or(&Vec::new()) - .iter() - .map(|tx| { - OpTxEnvelope::decode_2718(&mut tx.as_ref()).map_err(|err| { - DriverError::FromBlock(FromBlockError::TxEnvelopeDecodeError(err)) - }) - }) - .collect::, E::Error>>()?, - ommers: Vec::new(), - withdrawals: None, - }, - }; - - let origin = driver - .pipeline - .origin() - .ok_or(PipelineError::MissingOrigin.crit())?; - let l2_info = - L2BlockInfo::from_block_and_genesis(&block, &driver.pipeline.rollup_config().genesis)?; - let tip_cursor = TipCursor::new( - l2_info, - outcome.header, - driver - .executor - .compute_output_root() - .map_err(DriverError::Executor)?, - ); - - drop(pipeline_cursor); - driver.cursor.write().advance(origin, tip_cursor); - - let processed_block_number = l2_info.block_info.number; - if processed_block_number.saturating_sub(last_logged_block_number) >= progress_interval { - last_logged_block_number = processed_block_number; - match target { - Some(target_block) => { - let total = target_block.saturating_sub(start_block_number).max(1); - let done = processed_block_number.saturating_sub(start_block_number); - let percent = done.saturating_mul(100) / total; - info!( - target: "client", - "Processed block {processed_block_number} ({done}/{total}, {percent}%)" - ); - } - None => { - info!(target: "client", "Processed block {processed_block_number}"); - } - } - } - - #[cfg(target_os = "zkvm")] - std::mem::forget(block); - } -} diff --git a/proofs/measured/kona-client/src/executor.rs b/proofs/measured/kona-client/src/executor.rs index 3339da262..99b81dab3 100644 --- a/proofs/measured/kona-client/src/executor.rs +++ b/proofs/measured/kona-client/src/executor.rs @@ -16,15 +16,13 @@ use kona_proof::{ l1::{OracleL1ChainProvider, OraclePipeline}, l2::OracleL2ChainProvider, }; +use kona_sp1_client_utils::metrics::CycleTrackerDriverMetrics; use spin::RwLock; use tracing::info; use world_chain_proof_core::range::WorldRangeHardforkConfig; -use crate::{ - advance_to_target, - precompiles::{CustomCrypto, ZkvmOpEvmFactory}, -}; +use crate::precompiles::{CustomCrypto, ZkvmOpEvmFactory}; #[async_trait] pub trait WitnessExecutor { @@ -45,22 +43,6 @@ pub trait WitnessExecutor { l2_provider: Self::L2, ) -> Result>; - async fn run( - &self, - boot: BootInfo, - pipeline: DP, - cursor: Arc>, - l2_provider: OracleL2ChainProvider, - ) -> Result - where - O: CommsClient + FlushableCache + Send + Sync + Debug, - DP: DriverPipeline

+ Send + Sync + Debug, - P: Pipeline + SignalReceiver + Send + Sync + Debug, - { - self.run_with_world_schedule(boot, pipeline, cursor, l2_provider, None) - .await - } - async fn run_with_world_schedule( &self, boot: BootInfo, @@ -96,12 +78,13 @@ pub trait WitnessExecutor { #[cfg(target_os = "zkvm")] println!("cycle-tracker-report-start: block-execution-and-derivation"); - let (safe_head, output_root) = advance_to_target( - &mut driver, - rollup_config.as_ref(), - Some(boot.claimed_l2_block_number), - ) - .await?; + let (safe_head, output_root) = driver + .advance_to_target_with_metrics( + rollup_config.as_ref(), + Some(boot.claimed_l2_block_number), + &CycleTrackerDriverMetrics, + ) + .await?; #[cfg(target_os = "zkvm")] println!("cycle-tracker-report-end: block-execution-and-derivation"); @@ -211,38 +194,3 @@ where .await?) } } - -#[cfg(test)] -mod tests { - use super::ensure_derived_block_matches_claim; - - #[test] - fn returns_ok_when_derived_equals_claimed() { - assert!(ensure_derived_block_matches_claim(0, 0).is_ok()); - assert!(ensure_derived_block_matches_claim(123_456, 123_456).is_ok()); - assert!(ensure_derived_block_matches_claim(u64::MAX, u64::MAX).is_ok()); - } - - #[test] - fn returns_err_with_both_numbers_when_derived_below_claimed() { - let err = ensure_derived_block_matches_claim(50, 100).expect_err("expected mismatch error"); - let msg = err.to_string(); - assert!( - msg.contains("#50"), - "missing derived block number in: {msg}" - ); - assert!( - msg.contains("#100"), - "missing claimed block number in: {msg}" - ); - } - - #[test] - fn returns_err_with_both_numbers_when_derived_above_claimed() { - let err = - ensure_derived_block_matches_claim(150, 100).expect_err("expected mismatch error"); - let msg = err.to_string(); - assert!(msg.contains("#150")); - assert!(msg.contains("#100")); - } -} diff --git a/proofs/measured/kona-client/src/lib.rs b/proofs/measured/kona-client/src/lib.rs index 9945dd3e0..1cf3dc5f5 100644 --- a/proofs/measured/kona-client/src/lib.rs +++ b/proofs/measured/kona-client/src/lib.rs @@ -1,12 +1,7 @@ -pub mod client; pub mod executor; pub mod pipeline; pub mod precompiles; -pub mod range; -pub mod witness; -pub use client::{advance_to_target, fetch_safe_head_hash}; pub use executor::{ETHDAWitnessExecutor, WitnessExecutor}; pub use pipeline::get_inputs_for_pipeline; pub use precompiles::{CustomCrypto, ZkvmOpEvmFactory}; -pub use range::OutputRootWitness; diff --git a/proofs/measured/kona-client/src/pipeline.rs b/proofs/measured/kona-client/src/pipeline.rs index 463dc5ab5..701073315 100644 --- a/proofs/measured/kona-client/src/pipeline.rs +++ b/proofs/measured/kona-client/src/pipeline.rs @@ -1,19 +1,20 @@ use std::{fmt::Debug, sync::Arc}; -use alloy_primitives::{BlockNumber, Sealed}; -use anyhow::{Result, anyhow}; -use kona_driver::PipelineCursor; -use kona_executor::TrieDBProvider as _; +use alloy_consensus::{Header, Sealed}; +use alloy_op_evm::{block::OpAlloyReceiptBuilder, post_exec::PostExecEvmFactoryAdapter}; +use alloy_primitives::BlockNumber; +use anyhow::{Context, Result, ensure}; +use kona_driver::{Executor, PipelineCursor}; use kona_preimage::CommsClient; use kona_proof::{ - BootInfo, FlushableCache, l1::OracleL1ChainProvider, l2::OracleL2ChainProvider, - sync::new_oracle_pipeline_cursor, + BootInfo, FlushableCache, executor::KonaExecutor, l1::OracleL1ChainProvider, + l2::OracleL2ChainProvider, }; use spin::RwLock; -use crate::client::fetch_safe_head_hash; +use crate::precompiles::ZkvmOpEvmFactory; -/// Loads boot info and constructs the initial pipeline cursor and providers. +/// Prepares the upstream pipeline and returns its starting L2 height for World public values. pub async fn get_inputs_for_pipeline( oracle: Arc, ) -> Result<( @@ -28,48 +29,275 @@ pub async fn get_inputs_for_pipeline( where O: CommsClient + FlushableCache + Send + Sync + Debug, { - let boot = match BootInfo::load(oracle.as_ref()).await { - Ok(boot) => boot, - Err(e) => { - return Err(anyhow!("Failed to load boot info: {:?}", e)); + let (boot, inputs) = + kona_sp1_client_utils::witness::executor::get_inputs_for_pipeline(oracle).await?; + let safe_head_number = match &inputs { + Some((cursor, _, l2_provider)) => { + let safe_header = cursor.read().tip().l2_safe_head_header.clone(); + validate_starting_output_root(&boot, safe_header, l2_provider.clone())?; + cursor.read().tip().l2_safe_head.block_info.number } + // Upstream accepts a zero-step claim only when its height and root match the safe head. + None => boot.claimed_l2_block_number, }; + Ok((boot, inputs, safe_head_number)) +} - let boot_clone = boot.clone(); +fn validate_starting_output_root( + boot: &BootInfo, + safe_header: Sealed

, + l2_provider: OracleL2ChainProvider, +) -> Result<()> +where + O: CommsClient + Send + Sync + Debug, +{ + let mut executor = KonaExecutor::new( + &boot.rollup_config, + l2_provider.clone(), + l2_provider, + PostExecEvmFactoryAdapter::new(ZkvmOpEvmFactory::new()), + OpAlloyReceiptBuilder::default(), + None, + ); + executor.update_safe_head(safe_header); + // Authenticate the message-passer storage root against the starting state trie. + let output_root = executor + .compute_output_root() + .context("failed to authenticate starting output root")?; + ensure!( + output_root == boot.agreed_l2_output_root, + "Starting output root mismatch: agreed {}, computed {output_root}", + boot.agreed_l2_output_root, + ); + Ok(()) +} - let rollup_config = Arc::new(boot.rollup_config); - let safe_head_hash = fetch_safe_head_hash(oracle.as_ref(), boot.agreed_l2_output_root).await?; +#[cfg(test)] +mod tests { + use super::*; + use alloy_consensus::Header; + use alloy_primitives::{B256, Bytes, address, keccak256}; + use kona_preimage::{ + L1_HEAD_KEY, L2_CHAIN_ID_KEY, L2_CLAIM_BLOCK_NUMBER_KEY, L2_CLAIM_KEY, L2_OUTPUT_ROOT_KEY, + L2_ROLLUP_CONFIG_KEY, PreimageKey, + }; + use kona_proof::{block_on, sync::SyncStartError}; + use world_chain_proof_core::witness::preimage_store::PreimageStore; - let mut l1_provider = OracleL1ChainProvider::new(boot.l1_head, oracle.clone()); - let mut l2_provider = - OracleL2ChainProvider::new(safe_head_hash, rollup_config.clone(), oracle.clone()); + fn oracle(claimed_height: u64, matching_root: bool, version: u8) -> Arc { + let header = Header { + number: 42, + ..Default::default() + }; + let hash = header.hash_slow(); + let mut output = [0u8; 128]; + output[31] = version; + output[96..].copy_from_slice(hash.as_slice()); + let root = keccak256(output); + let claim = if matching_root { root } else { B256::ZERO }; + let mut oracle = PreimageStore::default(); + for (key, value) in [ + ( + PreimageKey::new_keccak256(hash.0), + alloy_rlp::encode(&header), + ), + (PreimageKey::new_keccak256(root.0), output.to_vec()), + ( + PreimageKey::new_local(L1_HEAD_KEY.to()), + B256::ZERO.to_vec(), + ), + ( + PreimageKey::new_local(L2_OUTPUT_ROOT_KEY.to()), + root.to_vec(), + ), + (PreimageKey::new_local(L2_CLAIM_KEY.to()), claim.to_vec()), + ( + PreimageKey::new_local(L2_CLAIM_BLOCK_NUMBER_KEY.to()), + claimed_height.to_be_bytes().to_vec(), + ), + ( + PreimageKey::new_local(L2_CHAIN_ID_KEY.to()), + 10u64.to_be_bytes().to_vec(), + ), + ] { + oracle.save_preimage(key, value).unwrap(); + } + Arc::new(oracle) + } - let safe_head = l2_provider - .header_by_hash(safe_head_hash) - .map(|header| Sealed::new_unchecked(header, safe_head_hash))?; - let safe_head_block_number = safe_head.number; + #[test] + fn unchanged_claim_preserves_starting_height_without_l1_witness() { + let (boot, inputs, pre_height) = + block_on(get_inputs_for_pipeline(oracle(42, true, 0))).unwrap(); + assert!(inputs.is_none()); + assert_eq!(pre_height, 42); + assert_eq!(boot.claimed_l2_block_number, pre_height); + assert_eq!(boot.claimed_l2_output_root, boot.agreed_l2_output_root); + } - if boot.claimed_l2_block_number < safe_head.number { - return Err(anyhow!( - "Claimed L2 block number {claimed} is less than the safe head {safe}", - claimed = boot.claimed_l2_block_number, - safe = safe_head.number + #[test] + fn unchanged_height_rejects_different_root() { + let error = block_on(get_inputs_for_pipeline(oracle(42, false, 0))).unwrap_err(); + assert!(matches!( + error.downcast_ref::(), + Some(SyncStartError::ClaimedRootMismatch { .. }) )); } - let cursor = new_oracle_pipeline_cursor( - rollup_config.as_ref(), - safe_head, - boot.agreed_l2_output_root, - &mut l1_provider, - &mut l2_provider, - ) - .await?; - l2_provider.set_cursor(cursor.clone()); + #[test] + fn claim_before_safe_head_is_rejected() { + let error = block_on(get_inputs_for_pipeline(oracle(41, true, 0))).unwrap_err(); + assert!(matches!( + error.downcast_ref::(), + Some(SyncStartError::ClaimedBlockBeforeSafeHead { .. }) + )); + } + + #[test] + fn pipeline_rejects_unsupported_output_version() { + let error = block_on(get_inputs_for_pipeline(oracle(42, true, 1))).unwrap_err(); + assert!(matches!( + error.downcast_ref::(), + Some(SyncStartError::Oracle( + kona_proof::errors::OracleProviderError::UnknownOutputVersion(_) + )) + )); + } - Ok(( - boot_clone, - Some((cursor, l1_provider, l2_provider)), - safe_head_block_number, - )) + fn starting_root_fixture( + state_root_override: Option, + storage_root_override: Option, + include_state_witness: bool, + ) -> Arc { + let storage_root = B256::repeat_byte(0x55); + let account = alloy_rlp::encode(vec![ + Bytes::new(), + Bytes::new(), + Bytes::copy_from_slice(storage_root.as_slice()), + Bytes::copy_from_slice(keccak256([]).as_slice()), + ]); + // A single-leaf state trie proves the message-passer account's storage root. + let mut path = vec![0x20]; + path.extend_from_slice( + keccak256(address!("4200000000000000000000000000000000000016")).as_slice(), + ); + let state_node = alloy_rlp::encode(vec![Bytes::from(path), Bytes::from(account)]); + let header = Header { + number: 42, + state_root: keccak256(&state_node), + transactions_root: alloy_consensus::EMPTY_ROOT_HASH, + ..Default::default() + }; + let hash = header.hash_slow(); + let mut output_preimage = [0u8; 128]; + output_preimage[32..64] + .copy_from_slice(state_root_override.unwrap_or(header.state_root).as_slice()); + output_preimage[64..96] + .copy_from_slice(storage_root_override.unwrap_or(storage_root).as_slice()); + output_preimage[96..].copy_from_slice(hash.as_slice()); + let agreed_root = keccak256(output_preimage); + let mut store = PreimageStore::default(); + // Even inconsistent output roots have valid Keccak preimages. + store + .save_preimage( + PreimageKey::new_keccak256(agreed_root.0), + output_preimage.to_vec(), + ) + .unwrap(); + if include_state_witness { + store + .save_preimage(PreimageKey::new_keccak256(header.state_root.0), state_node) + .unwrap(); + } + let l1_header = Header::default(); + let l1_hash = l1_header.hash_slow(); + let chain_id = u64::MAX - 1; + let mut config = kona_genesis::RollupConfig { + l1_chain_id: 1, + l2_chain_id: chain_id.into(), + ..Default::default() + }; + config.genesis.l1.hash = l1_hash; + config.genesis.l2.hash = hash; + config.genesis.l2.number = header.number; + for (key, value) in [ + ( + PreimageKey::new_keccak256(hash.0), + alloy_rlp::encode(&header), + ), + ( + PreimageKey::new_keccak256(l1_hash.0), + alloy_rlp::encode(&l1_header), + ), + ( + PreimageKey::new_keccak256(alloy_consensus::EMPTY_ROOT_HASH.0), + vec![0x80], + ), + (PreimageKey::new_local(L1_HEAD_KEY.to()), l1_hash.to_vec()), + ( + PreimageKey::new_local(L2_OUTPUT_ROOT_KEY.to()), + agreed_root.to_vec(), + ), + ( + PreimageKey::new_local(L2_CLAIM_KEY.to()), + B256::ZERO.to_vec(), + ), + ( + PreimageKey::new_local(L2_CLAIM_BLOCK_NUMBER_KEY.to()), + 43u64.to_be_bytes().to_vec(), + ), + ( + PreimageKey::new_local(L2_CHAIN_ID_KEY.to()), + chain_id.to_be_bytes().to_vec(), + ), + ( + PreimageKey::new_local(L2_ROLLUP_CONFIG_KEY.to()), + serde_json::to_vec(&config).unwrap(), + ), + ] { + store.save_preimage(key, value).unwrap(); + } + Arc::new(store) + } + + #[test] + fn starting_output_root_accepts_authenticated_state_and_storage_roots() { + let oracle = starting_root_fixture(None, None, true); + let (boot, inputs, pre_height) = block_on(get_inputs_for_pipeline(oracle)).unwrap(); + assert!(inputs.is_some()); + assert_eq!(pre_height, 42); + assert_eq!(boot.claimed_l2_block_number, 43); + } + + #[test] + fn starting_output_root_rejects_inconsistent_state_root() { + let oracle = starting_root_fixture(Some(B256::repeat_byte(0x99)), None, true); + let error = block_on(get_inputs_for_pipeline(oracle)).unwrap_err(); + assert!( + error.to_string().contains("Starting output root mismatch"), + "{error}" + ); + } + + #[test] + fn starting_output_root_rejects_inconsistent_message_passer_storage_root() { + let oracle = starting_root_fixture(None, Some(B256::repeat_byte(0x99)), true); + let error = block_on(get_inputs_for_pipeline(oracle)).unwrap_err(); + assert!( + error.to_string().contains("Starting output root mismatch"), + "{error}" + ); + } + + #[test] + fn starting_output_root_requires_message_passer_account_witness() { + let oracle = starting_root_fixture(None, None, false); + let error = block_on(get_inputs_for_pipeline(oracle)).unwrap_err(); + assert!( + error + .to_string() + .contains("failed to authenticate starting output root"), + "{error}" + ); + } } diff --git a/proofs/measured/kona-client/src/precompiles/custom.rs b/proofs/measured/kona-client/src/precompiles/custom.rs deleted file mode 100644 index 841c5f78f..000000000 --- a/proofs/measured/kona-client/src/precompiles/custom.rs +++ /dev/null @@ -1,58 +0,0 @@ -//! Custom crypto provider for KZG proof verification. -//! -//! # Why a custom `Crypto` impl? -//! `revm-precompile`'s default [`Crypto`] implementation uses `c-kzg` (backed by the -//! blst C library) for KZG point-evaluation. blst cannot be compiled inside the SP1 -//! zkVM guest because: -//! 1. It requires a C toolchain (not available in the SP1 build environment), and -//! 2. It uses platform SIMD / assembly that is not supported in the RISC-V zkVM ISA. -//! -//! [`kzg-rs`](https://crates.io/crates/kzg-rs) is a pure-Rust KZG implementation that -//! compiles cleanly inside the zkVM. This shim wires it into revm's crypto interface. -//! -//! There is no upstream crate that already provides a `kzg-rs`-backed [`Crypto`] impl, -//! so we roll a minimal one here. SP1's BLS12-381 syscalls only accelerate G1 -//! add/double/decompress — they do not expose a pairing precompile — so a full zkVM -//! hardware-accelerated KZG path is not yet feasible and remains a future optimisation. -//! -use kzg_rs::{Bytes32, Bytes48, KzgProof, KzgSettings}; -use revm::precompile::{Crypto, PrecompileHalt}; - -/// Custom cryptography provider using kzg-rs for KZG proof verification. -/// -/// Uses `kzg-rs` (pure Rust) instead of `c-kzg` so it compiles inside the SP1 zkVM -/// guest where the blst C library is unavailable. -#[derive(Debug)] -pub struct CustomCrypto { - kzg_settings: KzgSettings, -} - -impl Default for CustomCrypto { - fn default() -> Self { - Self { - kzg_settings: KzgSettings::load_trusted_setup_file().unwrap(), - } - } -} - -impl Crypto for CustomCrypto { - fn verify_kzg_proof( - &self, - z: &[u8; 32], - y: &[u8; 32], - commitment: &[u8; 48], - proof: &[u8; 48], - ) -> Result<(), PrecompileHalt> { - let z = Bytes32::from_slice(z).map_err(|_| PrecompileHalt::BlobVerifyKzgProofFailed)?; - let y = Bytes32::from_slice(y).map_err(|_| PrecompileHalt::BlobVerifyKzgProofFailed)?; - let commitment = Bytes48::from_slice(commitment) - .map_err(|_| PrecompileHalt::BlobVerifyKzgProofFailed)?; - let proof = - Bytes48::from_slice(proof).map_err(|_| PrecompileHalt::BlobVerifyKzgProofFailed)?; - - KzgProof::verify_kzg_proof(&commitment, &z, &y, &proof, &self.kzg_settings) - .map_err(|_| PrecompileHalt::BlobVerifyKzgProofFailed)?; - - Ok(()) - } -} diff --git a/proofs/measured/kona-client/src/precompiles/mod.rs b/proofs/measured/kona-client/src/precompiles/mod.rs index 21d30a896..1fe2ba2a3 100644 --- a/proofs/measured/kona-client/src/precompiles/mod.rs +++ b/proofs/measured/kona-client/src/precompiles/mod.rs @@ -1,7 +1,6 @@ //! OP Stack EVM helpers for kona execution (host and zkVM). -mod custom; -pub use custom::CustomCrypto; +pub use kona_sp1_client_utils::precompiles::CustomCrypto; mod factory; pub use factory::ZkvmOpEvmFactory; diff --git a/proofs/measured/kona-client/src/range.rs b/proofs/measured/kona-client/src/range.rs deleted file mode 100644 index 83fb2639d..000000000 --- a/proofs/measured/kona-client/src/range.rs +++ /dev/null @@ -1,30 +0,0 @@ -use alloy_primitives::{B256, keccak256}; -use serde::{Deserialize, Serialize}; - -/// Data needed to recompute an OP Stack output root for one L2 block. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct OutputRootWitness { - /// L2 state root from the execution payload/header. - pub state_root: B256, - /// Storage root of the `L2ToL1MessagePasser` predeploy at this block. - pub message_passer_storage_root: B256, - /// L2 block hash. - pub block_hash: B256, -} - -impl OutputRootWitness { - /// Encodes the versioned OP Stack output-root preimage. - pub fn encode(&self) -> [u8; 128] { - let mut preimage = [0u8; 128]; - preimage[32..64].copy_from_slice(self.state_root.as_slice()); - preimage[64..96].copy_from_slice(self.message_passer_storage_root.as_slice()); - preimage[96..128].copy_from_slice(self.block_hash.as_slice()); - preimage - } - - /// Computes the OP Stack output root: - /// `keccak256(version || state_root || message_passer_storage_root || block_hash)`. - pub fn output_root(&self) -> B256 { - keccak256(self.encode()) - } -} diff --git a/proofs/measured/kona-client/src/witness.rs b/proofs/measured/kona-client/src/witness.rs deleted file mode 100644 index e231f2cf8..000000000 --- a/proofs/measured/kona-client/src/witness.rs +++ /dev/null @@ -1,3 +0,0 @@ -pub use world_chain_proof_core::witness::{ - BlobData, WitnessData, WorldRangeWitnessData, preimage_store, -}; diff --git a/proofs/measured/nitro-enclave/Cargo.lock b/proofs/measured/nitro-enclave/Cargo.lock index cd11159db..638f5461d 100644 --- a/proofs/measured/nitro-enclave/Cargo.lock +++ b/proofs/measured/nitro-enclave/Cargo.lock @@ -66,9 +66,9 @@ dependencies = [ [[package]] name = "alloy-consensus" -version = "2.1.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a6ff0c4adba2abdcd9fb5829ae5f4394c06f8585ed283a9ba79aa33763c802e1" +checksum = "727016fed834c2392d014dd697ea473f3e47bcec31ba31ccffa9c1d18ed904e5" dependencies = [ "alloy-eips", "alloy-primitives", @@ -91,9 +91,9 @@ dependencies = [ [[package]] name = "alloy-consensus-any" -version = "2.1.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7cdf48932b1db3216175e19a2b476d89d53076e004850ee7983c6807ba0fde74" +checksum = "6ea5ae60bbb3ce9dc52685a70a3755ad4432045fd38079b763cfe5127c706134" dependencies = [ "alloy-consensus", "alloy-eips", @@ -153,16 +153,29 @@ dependencies = [ "thiserror", ] +[[package]] +name = "alloy-eip8141" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36422c14bd57dcd638e276c8c9d7ac09eb16598e3a9dbd34e4b55267d4565b5e" +dependencies = [ + "alloy-primitives", + "alloy-rlp", + "serde", + "thiserror", +] + [[package]] name = "alloy-eips" -version = "2.1.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea4c0453065b9206acc0f869a258dc8dcbbd595e144b4446f2c493a24a814d1f" +checksum = "e01905444bd2fc330673f11d2466c0f54e8488f7ce3132b6a5e6497916fca765" dependencies = [ "alloy-eip2124", "alloy-eip2930", "alloy-eip7702", "alloy-eip7928", + "alloy-eip8141", "alloy-primitives", "alloy-rlp", "alloy-serde", @@ -172,14 +185,14 @@ dependencies = [ "either", "serde", "serde_with", - "sha2", + "sha2 0.10.9", ] [[package]] name = "alloy-evm" -version = "0.37.1" +version = "0.38.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "acde665074b478c97047dc2a461b4916cac77922d690e5b7415d1941ae7ff7bf" +checksum = "6b307a52f91f7f3aad56b5cb4f54e5eb17dd0b3f4b2c82823301499fe1c6fdaf" dependencies = [ "alloy-consensus", "alloy-eips", @@ -195,9 +208,9 @@ dependencies = [ [[package]] name = "alloy-genesis" -version = "2.1.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "027ba57264c5d05e4ff52e6090b3592e7526f5d5f5a844add6bbdd17c071c911" +checksum = "53cfa407c1d874cb306187996e30eb551bd98025e60e913e69e298ed2c8ea045" dependencies = [ "alloy-eips", "alloy-primitives", @@ -234,9 +247,9 @@ dependencies = [ [[package]] name = "alloy-network-primitives" -version = "2.1.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d875a11bd98595f57f73890f2e36f4a1cca0fa670623e59c9fb08b2389979c36" +checksum = "3819bf6794d25f679d42c3f2b168e12cae08c56bb41d393cb6249b55e6d5933e" dependencies = [ "alloy-consensus", "alloy-eips", @@ -248,7 +261,7 @@ dependencies = [ [[package]] name = "alloy-op-evm" version = "0.32.0" -source = "git+https://github.com/ethereum-optimism/optimism?rev=96ffbb2a94f19886fe7e27c45f3310e64ccd18b3#96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" +source = "git+https://github.com/ethereum-optimism/optimism?rev=da6d3252491754837a778061db0cc47236ec13c6#da6d3252491754837a778061db0cc47236ec13c6" dependencies = [ "alloy-consensus", "alloy-eips", @@ -265,7 +278,7 @@ dependencies = [ [[package]] name = "alloy-op-hardforks" version = "0.5.0" -source = "git+https://github.com/ethereum-optimism/optimism?rev=96ffbb2a94f19886fe7e27c45f3310e64ccd18b3#96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" +source = "git+https://github.com/ethereum-optimism/optimism?rev=da6d3252491754837a778061db0cc47236ec13c6#da6d3252491754837a778061db0cc47236ec13c6" dependencies = [ "alloy-chains", "alloy-hardforks", @@ -327,9 +340,9 @@ dependencies = [ [[package]] name = "alloy-rpc-types-engine" -version = "2.1.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b1f682c4881aa7000ac7cc86d7aeeb3b09836a77a90b329820140233651aeea" +checksum = "77b967576e97165fed3fae1cf6adad964e192293e4ee61d9187afe3ecaa12323" dependencies = [ "alloy-consensus", "alloy-eips", @@ -344,9 +357,9 @@ dependencies = [ [[package]] name = "alloy-rpc-types-eth" -version = "2.1.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e1bd19904581ee2075b61faabab1a4cefa8b96d8f2c85343adeae8ecf615e2b" +checksum = "32c475e21fe8a8caa02166b326ed22207a1a0597fc9b0dcdfb46e2fe6f80dadf" dependencies = [ "alloy-consensus", "alloy-consensus-any", @@ -356,6 +369,7 @@ dependencies = [ "alloy-rlp", "alloy-serde", "alloy-sol-types", + "alloy-trie", "itertools 0.14.0", "serde", "serde_json", @@ -364,9 +378,9 @@ dependencies = [ [[package]] name = "alloy-serde" -version = "2.4.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ff89f75b8a9d00f659750e9220c31b42d67c69ffc43b2ac8911dfd0506eb4a6" +checksum = "4f44f297d3b9e3ca2c3039e3c0ed69acde9b35edda15381cf78f725b7263fbe2" dependencies = [ "alloy-primitives", "serde", @@ -445,9 +459,9 @@ dependencies = [ [[package]] name = "alloy-trie" -version = "0.9.5" +version = "0.9.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f14b5d9b2c2173980202c6ff470d96e7c5e202c65a9f67884ad565226df7fbb" +checksum = "b94e3e0a88f8db47250ac8a95fb825d020719f833eb1dc661bd3609c3bbece7d" dependencies = [ "alloy-primitives", "alloy-rlp", @@ -461,9 +475,9 @@ dependencies = [ [[package]] name = "alloy-tx-macros" -version = "2.4.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d0626c4f3b2028f7e8db32f53c22d9ecd5939f772317b7c4b6fe5219cb0589a" +checksum = "60fa90c57738ace5b38106c9f743f3d6d47de09a82e82ecfc42702c1acf116ee" dependencies = [ "darling", "proc-macro2", @@ -504,21 +518,33 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3df4dcc01ff89867cd86b0da835f23c3f02738353aaee7dde7495af71363b8d5" dependencies = [ - "ark-ec", + "ark-ec 0.5.0", "ark-ff 0.5.0", "ark-serialize 0.5.0", "ark-std 0.5.0", ] +[[package]] +name = "ark-bls12-381" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be2ede2c0c96fa37d5d3484e8a59fec566c4a52b8c84bf993eaa6c67d7225a4c" +dependencies = [ + "ark-ec 0.6.0", + "ark-ff 0.6.0", + "ark-serialize 0.6.0", + "ark-std 0.6.0", +] + [[package]] name = "ark-bn254" -version = "0.5.0" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d69eab57e8d2663efa5c63135b2af4f396d66424f88954c21104125ab6b3e6bc" +checksum = "6bc66f96ebe2a17a499475b4f94791d379817592ef494171586967ffdc6f95db" dependencies = [ - "ark-ec", - "ark-ff 0.5.0", - "ark-std 0.5.0", + "ark-ec 0.6.0", + "ark-ff 0.6.0", + "ark-std 0.6.0", ] [[package]] @@ -529,7 +555,7 @@ checksum = "43d68f2d516162846c1238e755a7c4d131b892b70cc70c471a8e3ca3ed818fce" dependencies = [ "ahash", "ark-ff 0.5.0", - "ark-poly", + "ark-poly 0.5.0", "ark-serialize 0.5.0", "ark-std 0.5.0", "educe", @@ -542,6 +568,27 @@ dependencies = [ "zeroize", ] +[[package]] +name = "ark-ec" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8352a2b2aedf6ba2cc38f7520fc51191d518dde96175c729af19f2d059f191c4" +dependencies = [ + "ahash", + "ark-ff 0.6.0", + "ark-poly 0.6.0", + "ark-serialize 0.6.0", + "ark-std 0.6.0", + "educe", + "fnv", + "hashbrown 0.17.1", + "itertools 0.14.0", + "num-bigint 0.4.8", + "num-integer", + "num-traits", + "zeroize", +] + [[package]] name = "ark-ff" version = "0.3.0" @@ -723,6 +770,21 @@ dependencies = [ "hashbrown 0.15.5", ] +[[package]] +name = "ark-poly" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75f55af10b672002b8d953e230282c51206842e20e5791a94432219b4201de5c" +dependencies = [ + "ahash", + "ark-ff 0.6.0", + "ark-serialize 0.6.0", + "ark-std 0.6.0", + "educe", + "fnv", + "hashbrown 0.17.1", +] + [[package]] name = "ark-serialize" version = "0.3.0" @@ -891,7 +953,7 @@ checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" dependencies = [ "proc-macro2", "quote", - "syn 3.0.4", + "syn 3.0.6", ] [[package]] @@ -1124,7 +1186,7 @@ checksum = "46d07918caa9eeaaf06b7873925c53a61daac173539b4f7715090745e44e4e69" dependencies = [ "proc-macro2", "quote", - "syn 3.0.4", + "syn 3.0.6", ] [[package]] @@ -1159,9 +1221,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.4.4" +version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ad534f4357a5264cce5019c989cf66a4f0dc4e0d1b1d15f8aacec0ff7360273" +checksum = "f360145194ee8e21db5ee7f3fcd4fe52210864c75c985dae33218202c8bbe040" dependencies = [ "find-msvc-tools", "jobserver", @@ -1556,7 +1618,7 @@ checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" dependencies = [ "proc-macro2", "quote", - "syn 3.0.4", + "syn 3.0.6", ] [[package]] @@ -1652,7 +1714,7 @@ checksum = "a65863d15a4ce2888bd2f0f543cc963d3879c3a022c8ee43f6141d479a3ac815" dependencies = [ "proc-macro2", "quote", - "syn 3.0.4", + "syn 3.0.6", ] [[package]] @@ -1723,9 +1785,9 @@ dependencies = [ [[package]] name = "find-msvc-tools" -version = "0.1.11" +version = "0.1.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d45db016d36b838f563236e9193d0ee6ce38f3f68b6c94e914b4929c96bbb890" +checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484" [[package]] name = "fixed-cache" @@ -1823,7 +1885,7 @@ checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" dependencies = [ "proc-macro2", "quote", - "syn 3.0.4", + "syn 3.0.6", ] [[package]] @@ -2211,9 +2273,9 @@ dependencies = [ [[package]] name = "js-sys" -version = "0.3.104" +version = "0.3.103" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e0c1080212aad755ea003d18543e8768dd432c48819efd73a7bf1e39b7a5a3a" +checksum = "53b44bfcdb3f8d5837a46dae1ca9660a837176eee74a28b229bc626816589102" dependencies = [ "cfg-if", "futures-util", @@ -2231,7 +2293,7 @@ dependencies = [ "elliptic-curve", "once_cell", "serdect", - "sha2", + "sha2 0.10.9", "signature", ] @@ -2258,7 +2320,7 @@ dependencies = [ [[package]] name = "kona-derive" version = "0.4.5" -source = "git+https://github.com/ethereum-optimism/optimism?rev=96ffbb2a94f19886fe7e27c45f3310e64ccd18b3#96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" +source = "git+https://github.com/ethereum-optimism/optimism?rev=da6d3252491754837a778061db0cc47236ec13c6#da6d3252491754837a778061db0cc47236ec13c6" dependencies = [ "alloy-consensus", "alloy-eips", @@ -2280,7 +2342,7 @@ dependencies = [ [[package]] name = "kona-driver" version = "0.4.0" -source = "git+https://github.com/ethereum-optimism/optimism?rev=96ffbb2a94f19886fe7e27c45f3310e64ccd18b3#96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" +source = "git+https://github.com/ethereum-optimism/optimism?rev=da6d3252491754837a778061db0cc47236ec13c6#da6d3252491754837a778061db0cc47236ec13c6" dependencies = [ "alloy-consensus", "alloy-evm", @@ -2300,7 +2362,7 @@ dependencies = [ [[package]] name = "kona-executor" version = "0.4.0" -source = "git+https://github.com/ethereum-optimism/optimism?rev=96ffbb2a94f19886fe7e27c45f3310e64ccd18b3#96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" +source = "git+https://github.com/ethereum-optimism/optimism?rev=da6d3252491754837a778061db0cc47236ec13c6#da6d3252491754837a778061db0cc47236ec13c6" dependencies = [ "alloy-consensus", "alloy-eips", @@ -2324,7 +2386,7 @@ dependencies = [ [[package]] name = "kona-genesis" version = "0.4.5" -source = "git+https://github.com/ethereum-optimism/optimism?rev=96ffbb2a94f19886fe7e27c45f3310e64ccd18b3#96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" +source = "git+https://github.com/ethereum-optimism/optimism?rev=da6d3252491754837a778061db0cc47236ec13c6#da6d3252491754837a778061db0cc47236ec13c6" dependencies = [ "alloy-chains", "alloy-consensus", @@ -2342,7 +2404,7 @@ dependencies = [ [[package]] name = "kona-hardforks" version = "0.4.5" -source = "git+https://github.com/ethereum-optimism/optimism?rev=96ffbb2a94f19886fe7e27c45f3310e64ccd18b3#96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" +source = "git+https://github.com/ethereum-optimism/optimism?rev=da6d3252491754837a778061db0cc47236ec13c6#da6d3252491754837a778061db0cc47236ec13c6" dependencies = [ "alloy-eips", "alloy-primitives", @@ -2357,19 +2419,20 @@ dependencies = [ [[package]] name = "kona-interop" version = "0.4.5" -source = "git+https://github.com/ethereum-optimism/optimism?rev=96ffbb2a94f19886fe7e27c45f3310e64ccd18b3#96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" +source = "git+https://github.com/ethereum-optimism/optimism?rev=da6d3252491754837a778061db0cc47236ec13c6#da6d3252491754837a778061db0cc47236ec13c6" dependencies = [ "alloy-consensus", "alloy-eips", "alloy-primitives", "alloy-rlp", + "alloy-serde", "alloy-sol-types", "async-trait", "derive_more", "kona-genesis", - "kona-protocol", "kona-registry", "op-alloy-consensus", + "serde", "thiserror", "tracing", ] @@ -2377,12 +2440,12 @@ dependencies = [ [[package]] name = "kona-macros" version = "0.1.2" -source = "git+https://github.com/ethereum-optimism/optimism?rev=96ffbb2a94f19886fe7e27c45f3310e64ccd18b3#96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" +source = "git+https://github.com/ethereum-optimism/optimism?rev=da6d3252491754837a778061db0cc47236ec13c6#da6d3252491754837a778061db0cc47236ec13c6" [[package]] name = "kona-mpt" version = "0.3.0" -source = "git+https://github.com/ethereum-optimism/optimism?rev=96ffbb2a94f19886fe7e27c45f3310e64ccd18b3#96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" +source = "git+https://github.com/ethereum-optimism/optimism?rev=da6d3252491754837a778061db0cc47236ec13c6#da6d3252491754837a778061db0cc47236ec13c6" dependencies = [ "alloy-primitives", "alloy-rlp", @@ -2394,7 +2457,7 @@ dependencies = [ [[package]] name = "kona-preimage" version = "0.3.0" -source = "git+https://github.com/ethereum-optimism/optimism?rev=96ffbb2a94f19886fe7e27c45f3310e64ccd18b3#96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" +source = "git+https://github.com/ethereum-optimism/optimism?rev=da6d3252491754837a778061db0cc47236ec13c6#da6d3252491754837a778061db0cc47236ec13c6" dependencies = [ "alloy-primitives", "async-trait", @@ -2407,7 +2470,7 @@ dependencies = [ [[package]] name = "kona-proof" version = "0.3.0" -source = "git+https://github.com/ethereum-optimism/optimism?rev=96ffbb2a94f19886fe7e27c45f3310e64ccd18b3#96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" +source = "git+https://github.com/ethereum-optimism/optimism?rev=da6d3252491754837a778061db0cc47236ec13c6#da6d3252491754837a778061db0cc47236ec13c6" dependencies = [ "alloy-consensus", "alloy-eips", @@ -2416,7 +2479,7 @@ dependencies = [ "alloy-primitives", "alloy-rlp", "alloy-trie", - "ark-bls12-381", + "ark-bls12-381 0.5.0", "ark-ff 0.5.0", "async-trait", "kona-derive", @@ -2443,7 +2506,7 @@ dependencies = [ [[package]] name = "kona-protocol" version = "0.4.5" -source = "git+https://github.com/ethereum-optimism/optimism?rev=96ffbb2a94f19886fe7e27c45f3310e64ccd18b3#96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" +source = "git+https://github.com/ethereum-optimism/optimism?rev=da6d3252491754837a778061db0cc47236ec13c6#da6d3252491754837a778061db0cc47236ec13c6" dependencies = [ "alloc-no-stdlib", "alloy-consensus", @@ -2472,7 +2535,7 @@ dependencies = [ [[package]] name = "kona-registry" version = "0.4.5" -source = "git+https://github.com/ethereum-optimism/optimism?rev=96ffbb2a94f19886fe7e27c45f3310e64ccd18b3#96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" +source = "git+https://github.com/ethereum-optimism/optimism?rev=da6d3252491754837a778061db0cc47236ec13c6#da6d3252491754837a778061db0cc47236ec13c6" dependencies = [ "alloy-chains", "alloy-eips", @@ -2487,6 +2550,41 @@ dependencies = [ "toml", ] +[[package]] +name = "kona-sp1-client-utils" +version = "0.0.1" +source = "git+https://github.com/ethereum-optimism/optimism?rev=da6d3252491754837a778061db0cc47236ec13c6#da6d3252491754837a778061db0cc47236ec13c6" +dependencies = [ + "alloy-consensus", + "alloy-eips", + "alloy-evm", + "alloy-op-evm", + "alloy-primitives", + "alloy-rlp", + "alloy-sol-types", + "anyhow", + "async-trait", + "cfg-if", + "kona-derive", + "kona-driver", + "kona-executor", + "kona-genesis", + "kona-interop", + "kona-preimage", + "kona-proof", + "kona-protocol", + "kzg-rs", + "op-alloy-consensus", + "op-revm", + "revm", + "rkyv", + "serde", + "serde_json", + "sha2 0.10.9", + "spin 0.10.1", + "tracing", +] + [[package]] name = "konst" version = "0.2.20" @@ -2513,7 +2611,7 @@ dependencies = [ "rkyv", "serde", "serde_arrays", - "sha2", + "sha2 0.10.9", "sp1_bls12_381", "spin 0.9.9", ] @@ -2869,7 +2967,7 @@ dependencies = [ [[package]] name = "op-alloy" version = "2.0.0" -source = "git+https://github.com/ethereum-optimism/optimism?rev=96ffbb2a94f19886fe7e27c45f3310e64ccd18b3#96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" +source = "git+https://github.com/ethereum-optimism/optimism?rev=da6d3252491754837a778061db0cc47236ec13c6#da6d3252491754837a778061db0cc47236ec13c6" dependencies = [ "op-alloy-consensus", ] @@ -2877,7 +2975,7 @@ dependencies = [ [[package]] name = "op-alloy-consensus" version = "2.0.0" -source = "git+https://github.com/ethereum-optimism/optimism?rev=96ffbb2a94f19886fe7e27c45f3310e64ccd18b3#96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" +source = "git+https://github.com/ethereum-optimism/optimism?rev=da6d3252491754837a778061db0cc47236ec13c6#da6d3252491754837a778061db0cc47236ec13c6" dependencies = [ "alloy-consensus", "alloy-eips", @@ -2895,7 +2993,7 @@ dependencies = [ [[package]] name = "op-alloy-rpc-types" version = "2.0.0" -source = "git+https://github.com/ethereum-optimism/optimism?rev=96ffbb2a94f19886fe7e27c45f3310e64ccd18b3#96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" +source = "git+https://github.com/ethereum-optimism/optimism?rev=da6d3252491754837a778061db0cc47236ec13c6#da6d3252491754837a778061db0cc47236ec13c6" dependencies = [ "alloy-consensus", "alloy-eips", @@ -2913,7 +3011,7 @@ dependencies = [ [[package]] name = "op-alloy-rpc-types-engine" version = "2.0.0" -source = "git+https://github.com/ethereum-optimism/optimism?rev=96ffbb2a94f19886fe7e27c45f3310e64ccd18b3#96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" +source = "git+https://github.com/ethereum-optimism/optimism?rev=da6d3252491754837a778061db0cc47236ec13c6#da6d3252491754837a778061db0cc47236ec13c6" dependencies = [ "alloy-consensus", "alloy-eips", @@ -2923,14 +3021,14 @@ dependencies = [ "alloy-serde", "op-alloy-consensus", "serde", - "sha2", + "sha2 0.10.9", "thiserror", ] [[package]] name = "op-revm" version = "20.0.0" -source = "git+https://github.com/ethereum-optimism/optimism?rev=96ffbb2a94f19886fe7e27c45f3310e64ccd18b3#96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" +source = "git+https://github.com/ethereum-optimism/optimism?rev=da6d3252491754837a778061db0cc47236ec13c6#da6d3252491754837a778061db0cc47236ec13c6" dependencies = [ "alloy-eips", "auto_impl", @@ -2947,7 +3045,7 @@ dependencies = [ "ecdsa", "elliptic-curve", "primeorder", - "sha2", + "sha2 0.10.9", ] [[package]] @@ -3102,7 +3200,7 @@ dependencies = [ "ecdsa", "elliptic-curve", "primeorder", - "sha2", + "sha2 0.10.9", ] [[package]] @@ -3352,7 +3450,7 @@ checksum = "1c8d9ca532f185d5d4db7a7c9d51420b452168ea1c2b913953281bd6fe1fcbd0" dependencies = [ "proc-macro2", "quote", - "syn 3.0.4", + "syn 3.0.6", ] [[package]] @@ -3473,9 +3571,9 @@ dependencies = [ [[package]] name = "rcgen" -version = "0.14.9" +version = "0.14.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "091e7a8e7d86e6feb87a27ce8e2cba29d49eff9507afeebefab7eeb2ca667fb4" +checksum = "57f6d249aad744e274e682777a50283a225a32705394ee6d5fcc01efa25e4055" dependencies = [ "ring", "rustls-pki-types", @@ -3510,7 +3608,7 @@ checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a" dependencies = [ "proc-macro2", "quote", - "syn 3.0.4", + "syn 3.0.6", ] [[package]] @@ -3541,9 +3639,9 @@ dependencies = [ [[package]] name = "reth-codecs" -version = "0.5.2" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb43f4858fef4e3b42b80954d2edf1ff67c8ad7498347083cdc7d0f6eff2f081" +checksum = "1f0dd7f542fbcae0e490ebe13f3eababcc05547375246ff7f62700b533cf3f01" dependencies = [ "alloy-consensus", "alloy-eips", @@ -3559,9 +3657,9 @@ dependencies = [ [[package]] name = "reth-codecs-derive" -version = "0.5.2" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5798ae4d6b264764bc0d742468bd32c7fb515e774645d4930f95ff6311f3ae14" +checksum = "e7e508fcbb8cb775639dbbb56b81b62756d4322f28e76c60a52aa32575f993fe" dependencies = [ "proc-macro2", "quote", @@ -3570,18 +3668,18 @@ dependencies = [ [[package]] name = "reth-zstd-compressors" -version = "0.5.2" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e1bd4ae4f54a2ba813eef082910bc646bd31cab8ed134308fa71f1068331fb84" +checksum = "80addacffc5df9398c55919f8993922d2b688f2aa5753708fdd658ca3cc63e39" dependencies = [ "zstd", ] [[package]] name = "revm" -version = "41.0.0" +version = "42.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d51c254839fb36357d0b02d02e46ba57e683d7b017e2da33b47ae74685a9e59" +checksum = "b7c7fcd426beab3b91300a6d0d5eb8d583c0fad0fba451126e19fd51443eca62" dependencies = [ "revm-bytecode", "revm-context", @@ -3598,9 +3696,9 @@ dependencies = [ [[package]] name = "revm-bytecode" -version = "41.0.0" +version = "42.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e33493cf6d996e9242db4f2002caef48ec9aa8c4f3fff3b18aed10ef3942eec7" +checksum = "537356bdec80dbc04e4e6bb688b3441ff7cf18eecdcf3cac23150633c46467f1" dependencies = [ "bitvec", "revm-primitives", @@ -3608,9 +3706,9 @@ dependencies = [ [[package]] name = "revm-context" -version = "41.0.0" +version = "42.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "86e48fc736d9542c082ea5305be44b6a14b53a615f0147ad57f62189fd813068" +checksum = "cc6512f05f83378e29b2b016fa5bd7f5a533e3625548be4113732e1a536c2564" dependencies = [ "bitvec", "cfg-if", @@ -3624,9 +3722,9 @@ dependencies = [ [[package]] name = "revm-context-interface" -version = "41.0.0" +version = "42.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac68282a454318246817486835a446519291dd0a8167d09de14c7e96f2147696" +checksum = "103fff818b10311034c0c11ff8760294ee0e3c320daab3c5717990fe8ee2617b" dependencies = [ "alloy-eip2930", "alloy-eip7702", @@ -3639,9 +3737,9 @@ dependencies = [ [[package]] name = "revm-database" -version = "41.0.0" +version = "42.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d761681a43e48408ea23f7f66ff56ff7b6128cadb8f9135d1b94787d0c0fc6b4" +checksum = "df72760eab0852100e748c7cb03ce0221626d60ac14534118c84c5cc894fb4c9" dependencies = [ "derive_more", "either", @@ -3653,9 +3751,9 @@ dependencies = [ [[package]] name = "revm-database-interface" -version = "41.0.0" +version = "42.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b96e37d62fa60b45987b408486c84ebef4af4e7ddf1b3b96b4955a7263fd4e92" +checksum = "d9286c059a11be1dee814cafdc3a3ade57521c8caa050785a52c19a9d894f400" dependencies = [ "auto_impl", "either", @@ -3666,9 +3764,9 @@ dependencies = [ [[package]] name = "revm-handler" -version = "41.0.0" +version = "42.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f5e043ebfc0899c435e44475796285898e4f822e637bd67856da79cc170bd9df" +checksum = "09126175c3fa482e71e80cc28c6bb17e681911e472b94d4f7f73dd6780411798" dependencies = [ "auto_impl", "derive-where", @@ -3684,9 +3782,9 @@ dependencies = [ [[package]] name = "revm-inspector" -version = "41.0.0" +version = "42.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e470b2a5e177918944d8cd26174455b61b8fbfbbe7fe411d28b4097e410d11e" +checksum = "4aa55b208b52f0c083ea68147c78866eeecadd7c0071a614f477de316b60648e" dependencies = [ "auto_impl", "either", @@ -3700,9 +3798,9 @@ dependencies = [ [[package]] name = "revm-interpreter" -version = "41.0.0" +version = "42.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa5547f653f9e4c47b4f9a9075a0b7c0faea5fa29b7873f392733a943837825d" +checksum = "fd310927437752ce4bac6997b385772823b84843f04c82e151993bec1265a5ed" dependencies = [ "revm-bytecode", "revm-context-interface", @@ -3712,15 +3810,15 @@ dependencies = [ [[package]] name = "revm-precompile" -version = "41.0.0" +version = "42.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6d785931e4b8750cf9d79c808c22f05979c8d191baafc8badd4651db82584c1c" +checksum = "f2431091420999795df6a200b9f7933defe3d654710560a895e6bcabbd9954a5" dependencies = [ - "ark-bls12-381", + "ark-bls12-381 0.6.0", "ark-bn254", - "ark-ec", - "ark-ff 0.5.0", - "ark-serialize 0.5.0", + "ark-ec 0.6.0", + "ark-ff 0.6.0", + "ark-serialize 0.6.0", "arrayref", "aurora-engine-modexp", "cfg-if", @@ -3729,14 +3827,14 @@ dependencies = [ "revm-context-interface", "revm-primitives", "ripemd", - "sha2", + "sha2 0.11.0", ] [[package]] name = "revm-primitives" -version = "41.0.0" +version = "42.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "66f39151a31afe93d97f7ac894dd9dcc989368d5ccba19ce079bfc1d73b77452" +checksum = "2ef5564c1bce219fd08beca43d4f39fdcbc19193fa4f604c0c6b58950a13194a" dependencies = [ "alloy-primitives", "once_cell", @@ -3744,9 +3842,9 @@ dependencies = [ [[package]] name = "revm-state" -version = "41.0.0" +version = "42.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73ef2fffc28acc41e8ef7525f2b1d16288a10f80579a1b33e7e62abc9892314a" +checksum = "2c4ae66db3abfcb565854dbfc95513bfa440b3dc390ddf8e50b0363d12a6fa79" dependencies = [ "alloy-eip7928", "bitflags 2.13.1", @@ -3781,11 +3879,11 @@ dependencies = [ [[package]] name = "ripemd" -version = "0.1.3" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd124222d17ad93a644ed9d011a40f4fb64aa54275c08cc216524a9ea82fb09f" +checksum = "4dd4211456b4172d7e44261920c25acf07367c4f04bb5f5d54fc21b090d9b159" dependencies = [ - "digest 0.10.7", + "digest 0.11.3", ] [[package]] @@ -3816,7 +3914,7 @@ checksum = "1c25ef604ac7dd839d44d64648952ea23c97866f124ff671b0ed2cf3ad9bb06e" dependencies = [ "proc-macro2", "quote", - "syn 3.0.4", + "syn 3.0.6", ] [[package]] @@ -3914,9 +4012,9 @@ dependencies = [ [[package]] name = "rustls-webpki" -version = "0.103.15" +version = "0.103.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" dependencies = [ "ring", "rustls-pki-types", @@ -4095,7 +4193,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn 3.0.4", + "syn 3.0.6", ] [[package]] @@ -4174,6 +4272,17 @@ dependencies = [ "digest 0.10.7", ] +[[package]] +name = "sha2" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.0", + "digest 0.11.3", +] + [[package]] name = "sha3" version = "0.11.0" @@ -4249,9 +4358,9 @@ checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" [[package]] name = "slop-algebra" -version = "6.4.0" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "546efc4c8df95113752bce97387423a67ebe9ee5dd01170819dc1ca467d006d4" +checksum = "733d477823f02646fa8025c5e2d4227ed806ca33a469def68994f63122f9f106" dependencies = [ "itertools 0.14.0", "p3-field", @@ -4260,9 +4369,9 @@ dependencies = [ [[package]] name = "slop-bn254" -version = "6.4.0" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44aed289b288c6f60d31b89124d97e0424cfee33a7ddcbc8c650df032594cf8a" +checksum = "0207095beb89a56e3875a0ca43e5782a2efc8637124b43ce453df42410e12a4c" dependencies = [ "ff", "p3-bn254-fr", @@ -4275,11 +4384,10 @@ dependencies = [ [[package]] name = "slop-challenger" -version = "6.4.0" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a472bd4cf17c6fdd5090955290ee0de883f34c7707871ee099a4840d8736dc71" +checksum = "cfc4121b9b84df835c8a6677a90dc9935562172a4a370758987407c793633334" dependencies = [ - "futures", "p3-challenger", "serde", "slop-algebra", @@ -4288,9 +4396,9 @@ dependencies = [ [[package]] name = "slop-koala-bear" -version = "6.4.0" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5cf01dc278c282f732ba67e8bb90a710d4779778f1a195cdae92baacae8f8d6a" +checksum = "b27fec4aae6811dbf6a384cc7993e74621aede443356ef67c301c19c1f302865" dependencies = [ "lazy_static", "p3-koala-bear", @@ -4303,27 +4411,24 @@ dependencies = [ [[package]] name = "slop-poseidon2" -version = "6.4.0" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f27ec95c66d641b84741af6d8071b207625d191ae9026c7cedcfabf57f519a59" +checksum = "13388d3c92bac6214ef7585869b968cf895d2715ebbb8b1a0e1464dd2ada30b2" dependencies = [ "p3-poseidon2", ] [[package]] name = "slop-primitives" -version = "6.4.0" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3dd98992a3dd8b608fd94d1b8f96d392478f6fd613cbe5db1017f8c97d6d3e13" -dependencies = [ - "slop-algebra", -] +checksum = "93f569cac42b24e672f6b06ffde272d4086c2c2620f16d31c1d1ce88cddff681" [[package]] name = "slop-symmetric" -version = "6.4.0" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95ea707679a9bee285392aa505aa353f8f473502a4f0776eec944c0b3baf4929" +checksum = "693b50b55c3f5a2bb20dd3b975da79b80e4bf15b839b90f82e5dc7ba7262d3dc" dependencies = [ "p3-symmetric", ] @@ -4349,9 +4454,9 @@ dependencies = [ [[package]] name = "sp1-lib" -version = "6.4.0" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "27ac4a731d44d3588c59c320e9c4fa8cb6d1aca8be822f2d125f42887213e420" +checksum = "1d4bc4b2a4b6e5fd3105912c722f51de9d66e2440a44e4ddffaad04bfba42bdf" dependencies = [ "bincode", "serde", @@ -4360,9 +4465,9 @@ dependencies = [ [[package]] name = "sp1-primitives" -version = "6.4.0" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab9b6b5cc2f53c2c96b3ef611781ea151c61d541a90c467041ce3aac476001fe" +checksum = "d387e4babbee68d30774ef52aad88aad3607eda8145a0badfa823e1759187c0c" dependencies = [ "bincode", "blake3", @@ -4372,7 +4477,7 @@ dependencies = [ "lazy_static", "num-bigint 0.4.8", "serde", - "sha2", + "sha2 0.10.9", "slop-algebra", "slop-bn254", "slop-challenger", @@ -4485,9 +4590,9 @@ dependencies = [ [[package]] name = "syn" -version = "3.0.4" +version = "3.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6275cddf4610d1775e6d1fe9469b2e77d0f39fd98fb7450901b821e0c53649f" +checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee" dependencies = [ "proc-macro2", "quote", @@ -4540,7 +4645,7 @@ checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af" dependencies = [ "proc-macro2", "quote", - "syn 3.0.4", + "syn 3.0.6", ] [[package]] @@ -4631,7 +4736,7 @@ checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" dependencies = [ "proc-macro2", "quote", - "syn 3.0.4", + "syn 3.0.6", ] [[package]] @@ -4822,9 +4927,9 @@ checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" [[package]] name = "uuid" -version = "1.25.0" +version = "1.26.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f053576934f05a761a402421fbbe3d425d9366f75f978806a037b3ca481abecc" +checksum = "2ef6dac1e96601b4fb3acccccff2139741fcb757cb9a36089bf5be91cfb285ce" dependencies = [ "js-sys", "wasm-bindgen", @@ -4869,9 +4974,9 @@ dependencies = [ [[package]] name = "wasm-bindgen" -version = "0.2.127" +version = "0.2.126" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b70935747edd64d89de3efa29d73789b806c15798f8e7dca4d8ac356b50ce70" +checksum = "4b067c0c11094aef6b7a801c1e34a26affafdf3d051dba08456b868789aaf9a4" dependencies = [ "cfg-if", "once_cell", @@ -4882,9 +4987,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro" -version = "0.2.127" +version = "0.2.126" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77775f8f3f7217702089053b94958f8f54061a3f663417df76e19cbdcca29bc1" +checksum = "167ce5e579f6bcf889c4f7175a8a5a585de84e8ff93976ce393efa5f2837aab1" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -4892,9 +4997,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.127" +version = "0.2.126" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e11d33f857dc2fb11b8bc75aee111aa9cbeb12cd9f25efd3d4c2a3dd4e235284" +checksum = "f3997c7839262f4ef12cf90b818d6340c18e80f263f1a94bf157d0ec4420380e" dependencies = [ "bumpalo", "proc-macro2", @@ -4905,9 +5010,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-shared" -version = "0.2.127" +version = "0.2.126" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ef64dbcc55df09c7e5a46182d181c2cfa3e925f3da937ea764728b4bbb9dcbf" +checksum = "dc1b4cb0cc549fcf58d7dfc081778139b3d283a081644e833e84682ad71cea24" dependencies = [ "unicode-ident", ] @@ -5076,33 +5181,25 @@ checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" [[package]] name = "world-chain-proof-core" -version = "1.0.0-rc.1" +version = "1.0.0-rc.5" dependencies = [ - "alloy-consensus", - "alloy-eips", "alloy-primitives", "alloy-sol-types", - "anyhow", - "async-trait", - "kona-derive", "kona-genesis", - "kona-preimage", "kona-proof", - "kona-protocol", - "kzg-rs", + "kona-sp1-client-utils", "rkyv", "serde", "serde_json", - "sha2", + "sha2 0.10.9", "thiserror", ] [[package]] name = "world-chain-proof-kona-client" -version = "1.0.0-rc.1" +version = "1.0.0-rc.5" dependencies = [ "alloy-consensus", - "alloy-eips", "alloy-evm", "alloy-op-evm", "alloy-primitives", @@ -5111,17 +5208,12 @@ dependencies = [ "async-trait", "kona-derive", "kona-driver", - "kona-executor", "kona-genesis", "kona-preimage", "kona-proof", - "kona-protocol", - "kzg-rs", - "op-alloy-consensus", + "kona-sp1-client-utils", "op-revm", "revm", - "revm-precompile", - "serde", "spin 0.10.1", "tracing", "world-chain-proof-core", @@ -5129,7 +5221,7 @@ dependencies = [ [[package]] name = "world-chain-proof-nitro-enclave" -version = "1.0.0-rc.1" +version = "1.0.0-rc.5" dependencies = [ "alloy-primitives", "alloy-sol-types", @@ -5152,7 +5244,7 @@ dependencies = [ "serde", "serde_bytes", "serde_json", - "sha2", + "sha2 0.10.9", "thiserror", "tokio", "tokio-vsock", diff --git a/proofs/measured/nitro-enclave/Cargo.toml b/proofs/measured/nitro-enclave/Cargo.toml index 19bfed448..0c5589496 100644 --- a/proofs/measured/nitro-enclave/Cargo.toml +++ b/proofs/measured/nitro-enclave/Cargo.toml @@ -14,7 +14,7 @@ resolver = "3" members = ["."] [workspace.package] -version = "1.0.0-rc.1" +version = "1.0.0-rc.5" edition = "2024" rust-version = "1.95.0" license = "MIT" @@ -27,11 +27,11 @@ semicolon_in_expressions_from_macros = "allow" [workspace.dependencies] world-chain-proof-core = { path = "../core", default-features = false } world-chain-proof-kona-client = { path = "../kona-client", default-features = false } -alloy-primitives = { version = "1.6.0", default-features = false, features = [ +alloy-primitives = { version = "1.6.1", default-features = false, features = [ "std", "map-foldhash", ] } -alloy-sol-types = "1.6.0" +alloy-sol-types = "1.6.1" anyhow = { version = "1.0.86", default-features = false } base64 = { version = "0.22", default-features = false, features = ["alloc"] } hex = "0.4.3" @@ -43,7 +43,7 @@ thiserror = "2" tokio = { version = "1.52.3", features = ["full"] } tracing = "0.1" tracing-subscriber = { version = "0.3.18", features = ["env-filter"] } -kona-proof = { git = "https://github.com/ethereum-optimism/optimism", rev = "96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" } +kona-proof = { git = "https://github.com/ethereum-optimism/optimism", rev = "da6d3252491754837a778061db0cc47236ec13c6" } [package] name = "world-chain-proof-nitro-enclave" @@ -98,7 +98,7 @@ world-chain-proof-core.workspace = true p384 = { version = "0.13", features = ["ecdsa", "pkcs8"] } x509-parser = { version = "0.18", features = ["verify"] } rustls-pki-types = "1" -webpki = { package = "rustls-webpki", version = "0.103", default-features = false, features = [ +webpki = { package = "rustls-webpki", version = "0.103.16", default-features = false, features = [ "ring", "std", ] } diff --git a/proofs/measured/nitro-enclave/deny.toml b/proofs/measured/nitro-enclave/deny.toml index ced441f02..63f096d6a 100644 --- a/proofs/measured/nitro-enclave/deny.toml +++ b/proofs/measured/nitro-enclave/deny.toml @@ -17,6 +17,16 @@ ignore = [ multiple-versions = "deny" # Version-epoch splits inherited from the alloy/revm/kona upstreams skip = [ + # Kona uses Arkworks 0.5; revm-precompile 42 uses 0.6. + { name = "ark-bls12-381", version = "=0.5.0" }, + { name = "ark-ec", version = "=0.5.0" }, + { name = "ark-ff", version = "=0.5.0" }, + { name = "ark-ff-asm", version = "=0.5.0" }, + { name = "ark-ff-macros", version = "=0.5.0" }, + { name = "ark-poly", version = "=0.5.0" }, + { name = "ark-serialize", version = "=0.5.0" }, + { name = "ark-serialize-derive", version = "=0.5.0" }, + { name = "ark-std", version = "=0.5.0" }, "block-buffer", "cpufeatures", "crypto-common", @@ -25,6 +35,8 @@ skip = [ "hashbrown", "itertools", "num-bigint", + # The proof stack uses SHA-2 0.10; revm-precompile 42 uses 0.11. + { name = "sha2", version = "=0.10.9" }, "spin", "syn", "windows-sys", diff --git a/proofs/measured/nitro-enclave/src/cose.rs b/proofs/measured/nitro-enclave/src/cose.rs index 450d1a252..d52f3d7dd 100644 --- a/proofs/measured/nitro-enclave/src/cose.rs +++ b/proofs/measured/nitro-enclave/src/cose.rs @@ -124,7 +124,7 @@ mod tests { let signing_key = SigningKey::random(&mut rand::thread_rng()); let signature: Signature = signing_key.sign(&reference_tbs(&protected, payload)); - let doc = make_cose(&protected, payload, signature.to_bytes().as_slice()); + let doc = make_cose(&protected, payload, &signature.to_bytes()); let sign1 = parse_cose_sign1(&doc).unwrap(); let verifying_key = signing_key.verifying_key(); diff --git a/proofs/measured/nitro-enclave/src/prewarm.rs b/proofs/measured/nitro-enclave/src/prewarm.rs index 36de2a53b..2adfd8a37 100644 --- a/proofs/measured/nitro-enclave/src/prewarm.rs +++ b/proofs/measured/nitro-enclave/src/prewarm.rs @@ -77,7 +77,7 @@ pub fn cert_cache_key(der: &[u8]) -> Result { /// # Errors /// /// Returns an error if the certificate or its signature cannot be parsed, or if either -/// signature component exceeds 384 bits. +/// signature scalar is outside the valid P-384 range. pub fn parse_cert_signature(der: &[u8]) -> Result<(Vec, Vec)> { use x509_parser::prelude::{FromDer as _, X509Certificate}; @@ -85,8 +85,10 @@ pub fn parse_cert_signature(der: &[u8]) -> Result<(Vec, Vec)> { X509Certificate::from_der(der).map_err(|e| anyhow!("X.509 parse error: {e:?}"))?; let hash = Sha384::digest(cert.tbs_certificate.as_ref()).to_vec(); - let sig = decode_ecdsa_der_sig(cert.signature_value.data.as_ref()) - .context("decoding certificate ECDSA signature")?; + let sig = p384::ecdsa::Signature::from_der(cert.signature_value.data.as_ref()) + .context("decoding certificate ECDSA signature")? + .to_bytes() + .to_vec(); Ok((hash, sig)) } @@ -186,82 +188,6 @@ pub fn packed_cert_not_after(packed: &[u8]) -> Option { Some(u64::from_be_bytes(bytes)) } -// ─── DER helpers ───────────────────────────────────────────────────────────── - -/// Decodes a DER `SEQUENCE { INTEGER r, INTEGER s }` into raw `r || s`, each left-padded to -/// 48 bytes. -fn decode_ecdsa_der_sig(der: &[u8]) -> Result> { - if der.first() != Some(&0x30) { - bail!( - "expected SEQUENCE tag 0x30, got 0x{:02x}", - der.first().copied().unwrap_or(0) - ); - } - let mut pos = 1; - let (seq_len, consumed) = decode_der_length(&der[pos..])?; - pos += consumed; - let end = pos - .checked_add(seq_len) - .filter(|end| *end <= der.len()) - .ok_or_else(|| anyhow!("DER SEQUENCE length overflows input"))?; - - let (r_bytes, advanced) = decode_der_integer(&der[pos..end])?; - pos += advanced; - let (s_bytes, _) = decode_der_integer(&der[pos..end])?; - - let mut out = Vec::with_capacity(96); - out.extend_from_slice(&pad_to_48(&r_bytes)?); - out.extend_from_slice(&pad_to_48(&s_bytes)?); - Ok(out) -} - -fn decode_der_length(data: &[u8]) -> Result<(usize, usize)> { - let first = *data - .first() - .ok_or_else(|| anyhow!("unexpected end of DER length"))?; - if first < 0x80 { - return Ok((first as usize, 1)); - } - let num_bytes = (first & 0x7f) as usize; - if num_bytes == 0 || num_bytes > 4 || data.len() < 1 + num_bytes { - bail!("unsupported DER length encoding"); - } - let mut len = 0usize; - for &b in &data[1..=num_bytes] { - len = (len << 8) | b as usize; - } - Ok((len, 1 + num_bytes)) -} - -fn decode_der_integer(data: &[u8]) -> Result<(Vec, usize)> { - if data.first() != Some(&0x02) { - bail!( - "expected INTEGER tag 0x02, got 0x{:02x}", - data.first().copied().unwrap_or(0) - ); - } - let (len, header) = decode_der_length(&data[1..])?; - let start = 1 + header; - let bytes = data - .get(start..start + len) - .ok_or_else(|| anyhow!("DER INTEGER length overflows input"))?; - // DER prefixes a zero byte to keep the sign bit clear on positive integers. - let stripped = match bytes.first() { - Some(0x00) => &bytes[1..], - _ => bytes, - }; - Ok((stripped.to_vec(), start + len)) -} - -fn pad_to_48(bytes: &[u8]) -> Result> { - if bytes.len() > 48 { - bail!("integer exceeds 384 bits ({} bytes)", bytes.len()); - } - let mut out = vec![0u8; 48 - bytes.len()]; - out.extend_from_slice(bytes); - Ok(out) -} - #[cfg(test)] mod tests { use super::*; @@ -286,11 +212,40 @@ mod tests { } #[test] - fn cert_signature_decodes_to_96_bytes() { - let cert = include_bytes!("testdata/aws_zonal.der"); - let (hash, sig) = parse_cert_signature(cert).unwrap(); - assert_eq!(hash.len(), 48, "SHA-384 digest"); - assert_eq!(sig.len(), 96, "r || s"); + fn extracted_certificate_signatures_verify_against_their_issuers() { + use p384::ecdsa::{Signature, VerifyingKey, signature::hazmat::PrehashVerifier}; + + let chain = [ + include_bytes!("testdata/aws_root.der").as_slice(), + include_bytes!("testdata/aws_regional.der").as_slice(), + include_bytes!("testdata/aws_zonal.der").as_slice(), + include_bytes!("testdata/aws_instance.der").as_slice(), + include_bytes!("testdata/aws_leaf.der").as_slice(), + ]; + for (index, certificate) in chain.iter().enumerate() { + let issuer = chain[index.saturating_sub(1)]; + let mut public_key = vec![4]; + public_key.extend_from_slice(&cert_pubkey_xy(issuer).unwrap()); + let key = VerifyingKey::from_sec1_bytes(&public_key).unwrap(); + let (hash, signature) = parse_cert_signature(certificate).unwrap(); + let signature = Signature::from_slice(&signature).unwrap(); + key.verify_prehash(&hash, &signature).unwrap(); + } + } + + #[test] + fn rejects_invalid_signature_scalars_in_certificate() { + use x509_parser::prelude::{FromDer as _, X509Certificate}; + + let mut certificate = include_bytes!("testdata/aws_zonal.der").to_vec(); + let (_, parsed) = X509Certificate::from_der(&certificate).unwrap(); + let signature = parsed.signature_value.data.as_ref(); + let offset = certificate.len() - signature.len(); + // The fixture uses short DER lengths. Zeroing r preserves certificate framing. + assert_eq!(&signature[..3], &[0x30, (signature.len() - 2) as u8, 0x02]); + let r_len = signature[3] as usize; + certificate[offset + 4..offset + 4 + r_len].fill(0); + assert!(parse_cert_signature(&certificate).is_err()); } #[test] @@ -310,18 +265,4 @@ mod tests { assert_eq!(packed_cert_not_after(&[]), None, "uncached record"); assert_eq!(packed_cert_not_after(&[0x01, 0x00]), None, "truncated"); } - - #[test] - fn der_integer_strips_the_sign_padding_byte() { - // INTEGER 0x00FF → 0xFF once the sign byte is stripped. - let (bytes, consumed) = decode_der_integer(&[0x02, 0x02, 0x00, 0xFF]).unwrap(); - assert_eq!(bytes, vec![0xFF]); - assert_eq!(consumed, 4); - } - - #[test] - fn der_length_rejects_overflowing_sequence() { - // SEQUENCE claiming 0x7F bytes of content but carrying none. - assert!(decode_ecdsa_der_sig(&[0x30, 0x7F]).is_err()); - } } diff --git a/proofs/measured/nitro-enclave/supply-chain/config.toml b/proofs/measured/nitro-enclave/supply-chain/config.toml index 3a1a0e9df..897668727 100644 --- a/proofs/measured/nitro-enclave/supply-chain/config.toml +++ b/proofs/measured/nitro-enclave/supply-chain/config.toml @@ -94,11 +94,11 @@ version = "0.2.37" criteria = "safe-to-deploy" [[exemptions.alloy-consensus]] -version = "2.1.1" +version = "2.5.0" criteria = "safe-to-deploy" [[exemptions.alloy-consensus-any]] -version = "2.1.1" +version = "2.5.0" criteria = "safe-to-deploy" [[exemptions.alloy-eip2124]] @@ -117,16 +117,20 @@ criteria = "safe-to-deploy" version = "0.4.8" criteria = "safe-to-deploy" +[[exemptions.alloy-eip8141]] +version = "0.1.1" +criteria = "safe-to-deploy" + [[exemptions.alloy-eips]] -version = "2.1.1" +version = "2.5.0" criteria = "safe-to-deploy" [[exemptions.alloy-evm]] -version = "0.37.1" +version = "0.38.0" criteria = "safe-to-deploy" [[exemptions.alloy-genesis]] -version = "2.1.1" +version = "2.5.0" criteria = "safe-to-deploy" [[exemptions.alloy-hardforks]] @@ -138,15 +142,15 @@ version = "1.6.1" criteria = "safe-to-deploy" [[exemptions.alloy-network-primitives]] -version = "2.1.1" +version = "2.5.0" criteria = "safe-to-deploy" [[exemptions.alloy-op-evm]] -version = "0.32.0@git:96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" +version = "0.32.0@git:da6d3252491754837a778061db0cc47236ec13c6" criteria = "safe-to-deploy" [[exemptions.alloy-op-hardforks]] -version = "0.5.0@git:96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" +version = "0.5.0@git:da6d3252491754837a778061db0cc47236ec13c6" criteria = "safe-to-deploy" [[exemptions.alloy-primitives]] @@ -162,15 +166,15 @@ version = "0.3.16" criteria = "safe-to-deploy" [[exemptions.alloy-rpc-types-engine]] -version = "2.1.1" +version = "2.5.0" criteria = "safe-to-deploy" [[exemptions.alloy-rpc-types-eth]] -version = "2.1.1" +version = "2.5.0" criteria = "safe-to-deploy" [[exemptions.alloy-serde]] -version = "2.4.1" +version = "2.5.0" criteria = "safe-to-deploy" [[exemptions.alloy-sol-macro]] @@ -194,11 +198,11 @@ version = "1.6.1" criteria = "safe-to-deploy" [[exemptions.alloy-trie]] -version = "0.9.5" +version = "0.9.8" criteria = "safe-to-deploy" [[exemptions.alloy-tx-macros]] -version = "2.4.1" +version = "2.5.0" criteria = "safe-to-deploy" [[exemptions.ambassador]] @@ -217,14 +221,22 @@ criteria = "safe-to-deploy" version = "0.5.0" criteria = "safe-to-deploy" +[[exemptions.ark-bls12-381]] +version = "0.6.0" +criteria = "safe-to-deploy" + [[exemptions.ark-bn254]] -version = "0.5.0" +version = "0.6.0" criteria = "safe-to-deploy" [[exemptions.ark-ec]] version = "0.5.0" criteria = "safe-to-deploy" +[[exemptions.ark-ec]] +version = "0.6.0" +criteria = "safe-to-deploy" + [[exemptions.ark-ff]] version = "0.3.0" criteria = "safe-to-deploy" @@ -277,6 +289,10 @@ criteria = "safe-to-deploy" version = "0.5.0" criteria = "safe-to-deploy" +[[exemptions.ark-poly]] +version = "0.6.0" +criteria = "safe-to-deploy" + [[exemptions.ark-serialize]] version = "0.3.0" criteria = "safe-to-deploy" @@ -434,7 +450,7 @@ version = "2.1.8" criteria = "safe-to-deploy" [[exemptions.cc]] -version = "1.4.4" +version = "1.5.1" criteria = "safe-to-deploy" [[exemptions.cfg-if]] @@ -622,7 +638,7 @@ version = "0.13.1" criteria = "safe-to-deploy" [[exemptions.find-msvc-tools]] -version = "0.1.11" +version = "0.1.14" criteria = "safe-to-deploy" [[exemptions.fixed-cache]] @@ -790,7 +806,7 @@ version = "0.1.35" criteria = "safe-to-deploy" [[exemptions.js-sys]] -version = "0.3.104" +version = "0.3.103" criteria = "safe-to-deploy" [[exemptions.k256]] @@ -806,51 +822,51 @@ version = "0.1.8" criteria = "safe-to-deploy" [[exemptions.kona-derive]] -version = "0.4.5@git:96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" +version = "0.4.5@git:da6d3252491754837a778061db0cc47236ec13c6" criteria = "safe-to-deploy" [[exemptions.kona-driver]] -version = "0.4.0@git:96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" +version = "0.4.0@git:da6d3252491754837a778061db0cc47236ec13c6" criteria = "safe-to-deploy" [[exemptions.kona-executor]] -version = "0.4.0@git:96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" +version = "0.4.0@git:da6d3252491754837a778061db0cc47236ec13c6" criteria = "safe-to-deploy" [[exemptions.kona-genesis]] -version = "0.4.5@git:96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" +version = "0.4.5@git:da6d3252491754837a778061db0cc47236ec13c6" criteria = "safe-to-deploy" [[exemptions.kona-hardforks]] -version = "0.4.5@git:96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" +version = "0.4.5@git:da6d3252491754837a778061db0cc47236ec13c6" criteria = "safe-to-deploy" [[exemptions.kona-interop]] -version = "0.4.5@git:96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" +version = "0.4.5@git:da6d3252491754837a778061db0cc47236ec13c6" criteria = "safe-to-deploy" [[exemptions.kona-macros]] -version = "0.1.2@git:96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" +version = "0.1.2@git:da6d3252491754837a778061db0cc47236ec13c6" criteria = "safe-to-deploy" [[exemptions.kona-mpt]] -version = "0.3.0@git:96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" +version = "0.3.0@git:da6d3252491754837a778061db0cc47236ec13c6" criteria = "safe-to-deploy" [[exemptions.kona-preimage]] -version = "0.3.0@git:96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" +version = "0.3.0@git:da6d3252491754837a778061db0cc47236ec13c6" criteria = "safe-to-deploy" [[exemptions.kona-proof]] -version = "0.3.0@git:96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" +version = "0.3.0@git:da6d3252491754837a778061db0cc47236ec13c6" criteria = "safe-to-deploy" [[exemptions.kona-protocol]] -version = "0.4.5@git:96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" +version = "0.4.5@git:da6d3252491754837a778061db0cc47236ec13c6" criteria = "safe-to-deploy" [[exemptions.kona-registry]] -version = "0.4.5@git:96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" +version = "0.4.5@git:da6d3252491754837a778061db0cc47236ec13c6" criteria = "safe-to-deploy" [[exemptions.konst]] @@ -986,23 +1002,23 @@ version = "1.21.4" criteria = "safe-to-deploy" [[exemptions.op-alloy]] -version = "2.0.0@git:96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" +version = "2.0.0@git:da6d3252491754837a778061db0cc47236ec13c6" criteria = "safe-to-deploy" [[exemptions.op-alloy-consensus]] -version = "2.0.0@git:96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" +version = "2.0.0@git:da6d3252491754837a778061db0cc47236ec13c6" criteria = "safe-to-deploy" [[exemptions.op-alloy-rpc-types]] -version = "2.0.0@git:96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" +version = "2.0.0@git:da6d3252491754837a778061db0cc47236ec13c6" criteria = "safe-to-deploy" [[exemptions.op-alloy-rpc-types-engine]] -version = "2.0.0@git:96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" +version = "2.0.0@git:da6d3252491754837a778061db0cc47236ec13c6" criteria = "safe-to-deploy" [[exemptions.op-revm]] -version = "20.0.0@git:96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" +version = "20.0.0@git:da6d3252491754837a778061db0cc47236ec13c6" criteria = "safe-to-deploy" [[exemptions.p256]] @@ -1190,7 +1206,7 @@ version = "4.5.1" criteria = "safe-to-deploy" [[exemptions.rcgen]] -version = "0.14.9" +version = "0.14.8" criteria = "safe-to-run" [[exemptions.redox_syscall]] @@ -1218,63 +1234,63 @@ version = "0.5.4" criteria = "safe-to-deploy" [[exemptions.reth-codecs]] -version = "0.5.2" +version = "0.6.0" criteria = "safe-to-deploy" [[exemptions.reth-codecs-derive]] -version = "0.5.2" +version = "0.6.0" criteria = "safe-to-deploy" [[exemptions.reth-zstd-compressors]] -version = "0.5.2" +version = "0.6.0" criteria = "safe-to-deploy" [[exemptions.revm]] -version = "41.0.0" +version = "42.0.1" criteria = "safe-to-deploy" [[exemptions.revm-bytecode]] -version = "41.0.0" +version = "42.0.0" criteria = "safe-to-deploy" [[exemptions.revm-context]] -version = "41.0.0" +version = "42.0.0" criteria = "safe-to-deploy" [[exemptions.revm-context-interface]] -version = "41.0.0" +version = "42.0.0" criteria = "safe-to-deploy" [[exemptions.revm-database]] -version = "41.0.0" +version = "42.0.0" criteria = "safe-to-deploy" [[exemptions.revm-database-interface]] -version = "41.0.0" +version = "42.0.0" criteria = "safe-to-deploy" [[exemptions.revm-handler]] -version = "41.0.0" +version = "42.0.1" criteria = "safe-to-deploy" [[exemptions.revm-inspector]] -version = "41.0.0" +version = "42.0.1" criteria = "safe-to-deploy" [[exemptions.revm-interpreter]] -version = "41.0.0" +version = "42.0.0" criteria = "safe-to-deploy" [[exemptions.revm-precompile]] -version = "41.0.0" +version = "42.0.1" criteria = "safe-to-deploy" [[exemptions.revm-primitives]] -version = "41.0.0" +version = "42.0.0" criteria = "safe-to-deploy" [[exemptions.revm-state]] -version = "41.0.0" +version = "42.0.0" criteria = "safe-to-deploy" [[exemptions.rfc6979]] @@ -1286,7 +1302,7 @@ version = "0.17.14" criteria = "safe-to-deploy" [[exemptions.ripemd]] -version = "0.1.3" +version = "0.2.0" criteria = "safe-to-deploy" [[exemptions.rkyv]] @@ -1330,7 +1346,7 @@ version = "1.15.1" criteria = "safe-to-deploy" [[exemptions.rustls-webpki]] -version = "0.103.15" +version = "0.103.16" criteria = "safe-to-deploy" [[exemptions.rustversion]] @@ -1417,6 +1433,10 @@ criteria = "safe-to-deploy" version = "0.10.9" criteria = "safe-to-deploy" +[[exemptions.sha2]] +version = "0.11.0" +criteria = "safe-to-deploy" + [[exemptions.sha3]] version = "0.11.0" criteria = "safe-to-deploy" @@ -1446,31 +1466,31 @@ version = "0.4.12" criteria = "safe-to-deploy" [[exemptions.slop-algebra]] -version = "6.4.0" +version = "6.8.1" criteria = "safe-to-deploy" [[exemptions.slop-bn254]] -version = "6.4.0" +version = "6.8.1" criteria = "safe-to-deploy" [[exemptions.slop-challenger]] -version = "6.4.0" +version = "6.8.1" criteria = "safe-to-deploy" [[exemptions.slop-koala-bear]] -version = "6.4.0" +version = "6.8.1" criteria = "safe-to-deploy" [[exemptions.slop-poseidon2]] -version = "6.4.0" +version = "6.8.1" criteria = "safe-to-deploy" [[exemptions.slop-primitives]] -version = "6.4.0" +version = "6.8.1" criteria = "safe-to-deploy" [[exemptions.slop-symmetric]] -version = "6.4.0" +version = "6.8.1" criteria = "safe-to-deploy" [[exemptions.socket2]] @@ -1478,11 +1498,11 @@ version = "0.6.5" criteria = "safe-to-deploy" [[exemptions.sp1-lib]] -version = "6.4.0" +version = "6.8.1" criteria = "safe-to-deploy" [[exemptions.sp1-primitives]] -version = "6.4.0" +version = "6.8.1" criteria = "safe-to-deploy" [[exemptions.sp1_bls12_381]] @@ -1514,7 +1534,7 @@ version = "2.0.119" criteria = "safe-to-deploy" [[exemptions.syn]] -version = "3.0.4" +version = "3.0.6" criteria = "safe-to-deploy" [[exemptions.syn-solidity]] @@ -1618,7 +1638,7 @@ version = "0.9.0" criteria = "safe-to-deploy" [[exemptions.uuid]] -version = "1.25.0" +version = "1.26.1" criteria = "safe-to-deploy" [[exemptions.valuable]] @@ -1638,19 +1658,19 @@ version = "0.11.1+wasi-snapshot-preview1" criteria = "safe-to-deploy" [[exemptions.wasm-bindgen]] -version = "0.2.127" +version = "0.2.126" criteria = "safe-to-deploy" [[exemptions.wasm-bindgen-macro]] -version = "0.2.127" +version = "0.2.126" criteria = "safe-to-deploy" [[exemptions.wasm-bindgen-macro-support]] -version = "0.2.127" +version = "0.2.126" criteria = "safe-to-deploy" [[exemptions.wasm-bindgen-shared]] -version = "0.2.127" +version = "0.2.126" criteria = "safe-to-deploy" [[exemptions.windows-core]] diff --git a/proofs/measured/sp1-programs/Cargo.lock b/proofs/measured/sp1-programs/Cargo.lock index 26fc3dd34..27cd6cb02 100644 --- a/proofs/measured/sp1-programs/Cargo.lock +++ b/proofs/measured/sp1-programs/Cargo.lock @@ -57,9 +57,9 @@ dependencies = [ [[package]] name = "alloy-consensus" -version = "2.1.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a6ff0c4adba2abdcd9fb5829ae5f4394c06f8585ed283a9ba79aa33763c802e1" +checksum = "727016fed834c2392d014dd697ea473f3e47bcec31ba31ccffa9c1d18ed904e5" dependencies = [ "alloy-eips", "alloy-primitives", @@ -82,9 +82,9 @@ dependencies = [ [[package]] name = "alloy-consensus-any" -version = "2.1.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7cdf48932b1db3216175e19a2b476d89d53076e004850ee7983c6807ba0fde74" +checksum = "6ea5ae60bbb3ce9dc52685a70a3755ad4432045fd38079b763cfe5127c706134" dependencies = [ "alloy-consensus", "alloy-eips", @@ -144,16 +144,29 @@ dependencies = [ "thiserror", ] +[[package]] +name = "alloy-eip8141" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36422c14bd57dcd638e276c8c9d7ac09eb16598e3a9dbd34e4b55267d4565b5e" +dependencies = [ + "alloy-primitives", + "alloy-rlp", + "serde", + "thiserror", +] + [[package]] name = "alloy-eips" -version = "2.1.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea4c0453065b9206acc0f869a258dc8dcbbd595e144b4446f2c493a24a814d1f" +checksum = "e01905444bd2fc330673f11d2466c0f54e8488f7ce3132b6a5e6497916fca765" dependencies = [ "alloy-eip2124", "alloy-eip2930", "alloy-eip7702", "alloy-eip7928", + "alloy-eip8141", "alloy-primitives", "alloy-rlp", "alloy-serde", @@ -163,14 +176,14 @@ dependencies = [ "either", "serde", "serde_with", - "sha2", + "sha2 0.10.9", ] [[package]] name = "alloy-evm" -version = "0.37.1" +version = "0.38.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "acde665074b478c97047dc2a461b4916cac77922d690e5b7415d1941ae7ff7bf" +checksum = "6b307a52f91f7f3aad56b5cb4f54e5eb17dd0b3f4b2c82823301499fe1c6fdaf" dependencies = [ "alloy-consensus", "alloy-eips", @@ -186,9 +199,9 @@ dependencies = [ [[package]] name = "alloy-genesis" -version = "2.1.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "027ba57264c5d05e4ff52e6090b3592e7526f5d5f5a844add6bbdd17c071c911" +checksum = "53cfa407c1d874cb306187996e30eb551bd98025e60e913e69e298ed2c8ea045" dependencies = [ "alloy-eips", "alloy-primitives", @@ -213,9 +226,9 @@ dependencies = [ [[package]] name = "alloy-json-abi" -version = "1.6.0" +version = "1.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7c36c9d7f9021601b04bfef14a4b64849f6d73116a4e91e071d7fbfe10247901" +checksum = "858acd7fdad1e4a7057fd9c1b39c1f2cd6bcd57ebf3c56e2853c02ead049e816" dependencies = [ "alloy-primitives", "alloy-sol-type-parser", @@ -225,9 +238,9 @@ dependencies = [ [[package]] name = "alloy-network-primitives" -version = "2.1.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d875a11bd98595f57f73890f2e36f4a1cca0fa670623e59c9fb08b2389979c36" +checksum = "3819bf6794d25f679d42c3f2b168e12cae08c56bb41d393cb6249b55e6d5933e" dependencies = [ "alloy-consensus", "alloy-eips", @@ -239,7 +252,7 @@ dependencies = [ [[package]] name = "alloy-op-evm" version = "0.32.0" -source = "git+https://github.com/ethereum-optimism/optimism?rev=96ffbb2a94f19886fe7e27c45f3310e64ccd18b3#96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" +source = "git+https://github.com/ethereum-optimism/optimism?rev=da6d3252491754837a778061db0cc47236ec13c6#da6d3252491754837a778061db0cc47236ec13c6" dependencies = [ "alloy-consensus", "alloy-eips", @@ -256,7 +269,7 @@ dependencies = [ [[package]] name = "alloy-op-hardforks" version = "0.5.0" -source = "git+https://github.com/ethereum-optimism/optimism?rev=96ffbb2a94f19886fe7e27c45f3310e64ccd18b3#96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" +source = "git+https://github.com/ethereum-optimism/optimism?rev=da6d3252491754837a778061db0cc47236ec13c6#da6d3252491754837a778061db0cc47236ec13c6" dependencies = [ "alloy-chains", "alloy-hardforks", @@ -267,16 +280,17 @@ dependencies = [ [[package]] name = "alloy-primitives" -version = "1.6.0" +version = "1.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4885c1409b6936c4898e646ef58baf6ec54edaf6d8179f79df805a7b85b7cf3e" +checksum = "d5e9dbd49258ac3ab893a481d46be29b58be7f734dcac46cd80b6b13ee36566c" dependencies = [ "alloy-rlp", "bytes", "cfg-if", "const-hex", "derive_more", - "foldhash 0.2.0", + "fixed-cache", + "foldhash", "hashbrown 0.17.1", "indexmap", "itoa", @@ -317,9 +331,9 @@ dependencies = [ [[package]] name = "alloy-rpc-types-engine" -version = "2.1.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b1f682c4881aa7000ac7cc86d7aeeb3b09836a77a90b329820140233651aeea" +checksum = "77b967576e97165fed3fae1cf6adad964e192293e4ee61d9187afe3ecaa12323" dependencies = [ "alloy-consensus", "alloy-eips", @@ -334,9 +348,9 @@ dependencies = [ [[package]] name = "alloy-rpc-types-eth" -version = "2.1.1" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e1bd19904581ee2075b61faabab1a4cefa8b96d8f2c85343adeae8ecf615e2b" +checksum = "32c475e21fe8a8caa02166b326ed22207a1a0597fc9b0dcdfb46e2fe6f80dadf" dependencies = [ "alloy-consensus", "alloy-consensus-any", @@ -346,7 +360,8 @@ dependencies = [ "alloy-rlp", "alloy-serde", "alloy-sol-types", - "itertools 0.13.0", + "alloy-trie", + "itertools 0.14.0", "serde", "serde_json", "thiserror", @@ -354,9 +369,9 @@ dependencies = [ [[package]] name = "alloy-serde" -version = "2.3.0" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ad7efdd5e8fe92f5bab87956d6d3f717d1614c4ab6ad0d1f869b16e83b0dff9" +checksum = "4f44f297d3b9e3ca2c3039e3c0ed69acde9b35edda15381cf78f725b7263fbe2" dependencies = [ "alloy-primitives", "serde", @@ -365,13 +380,13 @@ dependencies = [ [[package]] name = "alloy-sol-macro" -version = "1.6.0" +version = "1.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "840128ed2b2971d6d4668a553fe403a82683d3acc646c73e75887e7157408033" +checksum = "60dd79f578c3912f1fc2a150dbeb8110b8cfb976c60f98ebf6de9d5da5965a2b" dependencies = [ "alloy-sol-macro-expander", "alloy-sol-macro-input", - "proc-macro-error2", + "proc-macro-error3", "proc-macro2", "quote", "syn 2.0.117", @@ -379,15 +394,15 @@ dependencies = [ [[package]] name = "alloy-sol-macro-expander" -version = "1.6.0" +version = "1.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "63ec265e5d65d725175f6ca7711c970824c90ef9c0d1f1973711d4150ee612dd" +checksum = "9edb8520f2f94275e1caa73c85207dcc78ec402a9a4c429240f9a0783a8f16c0" dependencies = [ "alloy-sol-macro-input", "const-hex", "heck", "indexmap", - "proc-macro-error2", + "proc-macro-error3", "proc-macro2", "quote", "sha3", @@ -397,9 +412,9 @@ dependencies = [ [[package]] name = "alloy-sol-macro-input" -version = "1.6.0" +version = "1.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89bf01077f18650876cfa682eb1f949967b5cde03f1a51c955c469d2c9b4aa67" +checksum = "66af2d9344882172993be5f5cbfd349fdfa52cb548f7af8715b446fb35ef6001" dependencies = [ "const-hex", "dunce", @@ -413,9 +428,9 @@ dependencies = [ [[package]] name = "alloy-sol-type-parser" -version = "1.6.0" +version = "1.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "857b470ecdd2ed38beaf82ad1a38c516a8ff75266750f38b9eeed001d575241b" +checksum = "77c2a8abc3334044013b23d5e438cc5dc802e5544cc42b713d0840d5185967cc" dependencies = [ "serde", "winnow 1.0.3", @@ -423,9 +438,9 @@ dependencies = [ [[package]] name = "alloy-sol-types" -version = "1.6.0" +version = "1.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "384cf252de0db2dec52821eac037a7f57e2aa33fe5b900ce6fe39973402341f1" +checksum = "3e6f87cf007caa54e95455875fbd25879b008d0d9c7c340a2c258b3a3400a28c" dependencies = [ "alloy-json-abi", "alloy-primitives", @@ -435,9 +450,9 @@ dependencies = [ [[package]] name = "alloy-trie" -version = "0.9.5" +version = "0.9.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f14b5d9b2c2173980202c6ff470d96e7c5e202c65a9f67884ad565226df7fbb" +checksum = "b94e3e0a88f8db47250ac8a95fb825d020719f833eb1dc661bd3609c3bbece7d" dependencies = [ "alloy-primitives", "alloy-rlp", @@ -451,9 +466,9 @@ dependencies = [ [[package]] name = "alloy-tx-macros" -version = "2.3.0" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b3e2386593cef5b12c7d439dbcf62d7d51c3a50dc943909b42ae34b48f1b69dc" +checksum = "60fa90c57738ace5b38106c9f743f3d6d47de09a82e82ecfc42702c1acf116ee" dependencies = [ "darling", "proc-macro2", @@ -485,21 +500,33 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3df4dcc01ff89867cd86b0da835f23c3f02738353aaee7dde7495af71363b8d5" dependencies = [ - "ark-ec", + "ark-ec 0.5.0", "ark-ff 0.5.0", "ark-serialize 0.5.0", "ark-std 0.5.0", ] +[[package]] +name = "ark-bls12-381" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be2ede2c0c96fa37d5d3484e8a59fec566c4a52b8c84bf993eaa6c67d7225a4c" +dependencies = [ + "ark-ec 0.6.0", + "ark-ff 0.6.0", + "ark-serialize 0.6.0", + "ark-std 0.6.0", +] + [[package]] name = "ark-bn254" -version = "0.5.0" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d69eab57e8d2663efa5c63135b2af4f396d66424f88954c21104125ab6b3e6bc" +checksum = "6bc66f96ebe2a17a499475b4f94791d379817592ef494171586967ffdc6f95db" dependencies = [ - "ark-ec", - "ark-ff 0.5.0", - "ark-std 0.5.0", + "ark-ec 0.6.0", + "ark-ff 0.6.0", + "ark-std 0.6.0", ] [[package]] @@ -510,7 +537,7 @@ checksum = "43d68f2d516162846c1238e755a7c4d131b892b70cc70c471a8e3ca3ed818fce" dependencies = [ "ahash", "ark-ff 0.5.0", - "ark-poly", + "ark-poly 0.5.0", "ark-serialize 0.5.0", "ark-std 0.5.0", "educe", @@ -523,6 +550,27 @@ dependencies = [ "zeroize", ] +[[package]] +name = "ark-ec" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8352a2b2aedf6ba2cc38f7520fc51191d518dde96175c729af19f2d059f191c4" +dependencies = [ + "ahash", + "ark-ff 0.6.0", + "ark-poly 0.6.0", + "ark-serialize 0.6.0", + "ark-std 0.6.0", + "educe", + "fnv", + "hashbrown 0.17.1", + "itertools 0.14.0", + "num-bigint 0.4.6", + "num-integer", + "num-traits", + "zeroize", +] + [[package]] name = "ark-ff" version = "0.3.0" @@ -581,6 +629,23 @@ dependencies = [ "zeroize", ] +[[package]] +name = "ark-ff" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7a806ac6c8307b929df4645776290a50ee2aac754ad09d8bdf73391309e43af" +dependencies = [ + "ark-ff-asm 0.6.0", + "ark-ff-macros 0.6.0", + "ark-serialize 0.6.0", + "ark-std 0.6.0", + "digest 0.10.7", + "educe", + "num-bigint 0.4.6", + "num-traits", + "zeroize", +] + [[package]] name = "ark-ff-asm" version = "0.3.0" @@ -611,6 +676,16 @@ dependencies = [ "syn 2.0.117", ] +[[package]] +name = "ark-ff-asm" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1479009684adc073dff49a1025d3a7065b317a9ead25aaaca38cdc70058ba8a2" +dependencies = [ + "quote", + "syn 2.0.117", +] + [[package]] name = "ark-ff-macros" version = "0.3.0" @@ -649,6 +724,19 @@ dependencies = [ "syn 2.0.117", ] +[[package]] +name = "ark-ff-macros" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a0691ed21ef00ef89c1e9bda832eba493dda3ec2f8d892fb25b705f73f06bb8" +dependencies = [ + "num-bigint 0.4.6", + "num-traits", + "proc-macro2", + "quote", + "syn 2.0.117", +] + [[package]] name = "ark-poly" version = "0.5.0" @@ -664,6 +752,21 @@ dependencies = [ "hashbrown 0.15.5", ] +[[package]] +name = "ark-poly" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75f55af10b672002b8d953e230282c51206842e20e5791a94432219b4201de5c" +dependencies = [ + "ahash", + "ark-ff 0.6.0", + "ark-serialize 0.6.0", + "ark-std 0.6.0", + "educe", + "fnv", + "hashbrown 0.17.1", +] + [[package]] name = "ark-serialize" version = "0.3.0" @@ -691,13 +794,25 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f4d068aaf107ebcd7dfb52bc748f8030e0fc930ac8e360146ca54c1203088f7" dependencies = [ - "ark-serialize-derive", + "ark-serialize-derive 0.5.0", "ark-std 0.5.0", "arrayvec", "digest 0.10.7", "num-bigint 0.4.6", ] +[[package]] +name = "ark-serialize" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a74dd304fd536fb95d0a328e72be759209cc496a9da094c5bc56e5fea4f9e86b" +dependencies = [ + "ark-serialize-derive 0.6.0", + "ark-std 0.6.0", + "digest 0.10.7", + "num-bigint 0.4.6", +] + [[package]] name = "ark-serialize-derive" version = "0.5.0" @@ -709,6 +824,17 @@ dependencies = [ "syn 2.0.117", ] +[[package]] +name = "ark-serialize-derive" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f153690697a2b91e5e1251ff98411ee5371500a111a0fd317a70e588eb300f9" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + [[package]] name = "ark-std" version = "0.3.0" @@ -739,6 +865,16 @@ dependencies = [ "rand 0.8.6", ] +[[package]] +name = "ark-std" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "367c9c827ed431bff6868b7aa926e05b16eb46603cc8b6e768e4a5553fa1d155" +dependencies = [ + "num-traits", + "rand 0.8.6", +] + [[package]] name = "arrayref" version = "0.3.9" @@ -816,21 +952,6 @@ dependencies = [ "serde", ] -[[package]] -name = "bit-set" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3" -dependencies = [ - "bit-vec", -] - -[[package]] -name = "bit-vec" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7" - [[package]] name = "bitcoin-io" version = "0.1.4" @@ -953,6 +1074,26 @@ dependencies = [ "syn 2.0.117", ] +[[package]] +name = "bytemuck" +version = "1.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" +dependencies = [ + "bytemuck_derive", +] + +[[package]] +name = "bytemuck_derive" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc0e56a716f1e132ff6bf4bdac1c944a3fcdc1cae65f70a4a2a1ac3b401d2d1f" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.5", +] + [[package]] name = "byteorder" version = "1.5.0" @@ -1279,7 +1420,19 @@ dependencies = [ "der", "digest 0.10.7", "elliptic-curve", - "rfc6979", + "rfc6979 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "signature", +] + +[[package]] +name = "ecdsa" +version = "0.16.9" +source = "git+https://github.com/sp1-patches/signatures?tag=sp1-skip-verify-on-recovery#1880299a48fe7ef249edaa616fd411239fb5daf1" +dependencies = [ + "der", + "digest 0.10.7", + "elliptic-curve", + "rfc6979 0.4.0 (git+https://github.com/sp1-patches/signatures?tag=sp1-skip-verify-on-recovery)", "serdect", "signature", "spki", @@ -1371,22 +1524,6 @@ version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" -[[package]] -name = "errno" -version = "0.3.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" -dependencies = [ - "libc", - "windows-sys", -] - -[[package]] -name = "fastrand" -version = "2.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6" - [[package]] name = "fastrlp" version = "0.3.1" @@ -1443,6 +1580,16 @@ version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" +[[package]] +name = "fixed-cache" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2fe63500644ef0269fe6b744e7e5dc5c20b5eebf3d881bc2be53f194636f6583" +dependencies = [ + "equivalent", + "rapidhash", +] + [[package]] name = "fixed-hash" version = "0.8.0" @@ -1461,12 +1608,6 @@ version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" -[[package]] -name = "foldhash" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" - [[package]] name = "foldhash" version = "0.2.0" @@ -1479,71 +1620,12 @@ version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c" -[[package]] -name = "futures" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b147ee9d1f6d097cef9ce628cd2ee62288d963e16fb287bd9286455b241382d" -dependencies = [ - "futures-channel", - "futures-core", - "futures-executor", - "futures-io", - "futures-sink", - "futures-task", - "futures-util", -] - -[[package]] -name = "futures-channel" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d" -dependencies = [ - "futures-core", - "futures-sink", -] - [[package]] name = "futures-core" version = "0.3.32" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d" -[[package]] -name = "futures-executor" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baf29c38818342a3b26b5b923639e7b1f4a61fc5e76102d4b1981c6dc7a7579d" -dependencies = [ - "futures-core", - "futures-task", - "futures-util", -] - -[[package]] -name = "futures-io" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718" - -[[package]] -name = "futures-macro" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e835b70203e41293343137df5c0664546da5745f82ec9b84d40be8336958447b" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.117", -] - -[[package]] -name = "futures-sink" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c39754e157331b013978ec91992bde1ac089843443c49cbc7f46150b0fad0893" - [[package]] name = "futures-task" version = "0.3.32" @@ -1556,13 +1638,8 @@ version = "0.3.32" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6" dependencies = [ - "futures-channel", "futures-core", - "futures-io", - "futures-macro", - "futures-sink", "futures-task", - "memchr", "pin-project-lite", "slab", ] @@ -1603,21 +1680,8 @@ checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" dependencies = [ "cfg-if", "libc", - "r-efi 5.3.0", - "wasip2", -] - -[[package]] -name = "getrandom" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555" -dependencies = [ - "cfg-if", - "libc", - "r-efi 6.0.0", + "r-efi", "wasip2", - "wasip3", ] [[package]] @@ -1650,7 +1714,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" dependencies = [ "allocator-api2", - "foldhash 0.1.5", ] [[package]] @@ -1661,7 +1724,7 @@ checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" dependencies = [ "allocator-api2", "equivalent", - "foldhash 0.2.0", + "foldhash", "serde", "serde_core", ] @@ -1720,12 +1783,6 @@ dependencies = [ "typenum", ] -[[package]] -name = "id-arena" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" - [[package]] name = "ident_case" version = "1.0.1" @@ -1831,15 +1888,16 @@ dependencies = [ [[package]] name = "k256" version = "0.13.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6e3919bbaa2945715f0bb6d3934a173d1e9a59ac23767fbaaef277265a7411b" +source = "git+https://github.com/sp1-patches/elliptic-curves?tag=patch-k256-13.4-sp1-6.0.0#476243d31d3ffd9d882d0e5da1f6adaa2a204b62" dependencies = [ "cfg-if", - "ecdsa", + "ecdsa 0.16.9 (git+https://github.com/sp1-patches/signatures?tag=sp1-skip-verify-on-recovery)", "elliptic-curve", + "hex", "once_cell", "serdect", - "sha2", + "sha2 0.10.9", + "sp1-lib", ] [[package]] @@ -1865,7 +1923,7 @@ dependencies = [ [[package]] name = "kona-derive" version = "0.4.5" -source = "git+https://github.com/ethereum-optimism/optimism?rev=96ffbb2a94f19886fe7e27c45f3310e64ccd18b3#96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" +source = "git+https://github.com/ethereum-optimism/optimism?rev=da6d3252491754837a778061db0cc47236ec13c6#da6d3252491754837a778061db0cc47236ec13c6" dependencies = [ "alloy-consensus", "alloy-eips", @@ -1887,7 +1945,7 @@ dependencies = [ [[package]] name = "kona-driver" version = "0.4.0" -source = "git+https://github.com/ethereum-optimism/optimism?rev=96ffbb2a94f19886fe7e27c45f3310e64ccd18b3#96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" +source = "git+https://github.com/ethereum-optimism/optimism?rev=da6d3252491754837a778061db0cc47236ec13c6#da6d3252491754837a778061db0cc47236ec13c6" dependencies = [ "alloy-consensus", "alloy-evm", @@ -1907,7 +1965,7 @@ dependencies = [ [[package]] name = "kona-executor" version = "0.4.0" -source = "git+https://github.com/ethereum-optimism/optimism?rev=96ffbb2a94f19886fe7e27c45f3310e64ccd18b3#96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" +source = "git+https://github.com/ethereum-optimism/optimism?rev=da6d3252491754837a778061db0cc47236ec13c6#da6d3252491754837a778061db0cc47236ec13c6" dependencies = [ "alloy-consensus", "alloy-eips", @@ -1931,7 +1989,7 @@ dependencies = [ [[package]] name = "kona-genesis" version = "0.4.5" -source = "git+https://github.com/ethereum-optimism/optimism?rev=96ffbb2a94f19886fe7e27c45f3310e64ccd18b3#96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" +source = "git+https://github.com/ethereum-optimism/optimism?rev=da6d3252491754837a778061db0cc47236ec13c6#da6d3252491754837a778061db0cc47236ec13c6" dependencies = [ "alloy-chains", "alloy-consensus", @@ -1949,7 +2007,7 @@ dependencies = [ [[package]] name = "kona-hardforks" version = "0.4.5" -source = "git+https://github.com/ethereum-optimism/optimism?rev=96ffbb2a94f19886fe7e27c45f3310e64ccd18b3#96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" +source = "git+https://github.com/ethereum-optimism/optimism?rev=da6d3252491754837a778061db0cc47236ec13c6#da6d3252491754837a778061db0cc47236ec13c6" dependencies = [ "alloy-eips", "alloy-primitives", @@ -1964,19 +2022,20 @@ dependencies = [ [[package]] name = "kona-interop" version = "0.4.5" -source = "git+https://github.com/ethereum-optimism/optimism?rev=96ffbb2a94f19886fe7e27c45f3310e64ccd18b3#96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" +source = "git+https://github.com/ethereum-optimism/optimism?rev=da6d3252491754837a778061db0cc47236ec13c6#da6d3252491754837a778061db0cc47236ec13c6" dependencies = [ "alloy-consensus", "alloy-eips", "alloy-primitives", "alloy-rlp", + "alloy-serde", "alloy-sol-types", "async-trait", "derive_more", "kona-genesis", - "kona-protocol", "kona-registry", "op-alloy-consensus", + "serde", "thiserror", "tracing", ] @@ -1984,12 +2043,12 @@ dependencies = [ [[package]] name = "kona-macros" version = "0.1.2" -source = "git+https://github.com/ethereum-optimism/optimism?rev=96ffbb2a94f19886fe7e27c45f3310e64ccd18b3#96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" +source = "git+https://github.com/ethereum-optimism/optimism?rev=da6d3252491754837a778061db0cc47236ec13c6#da6d3252491754837a778061db0cc47236ec13c6" [[package]] name = "kona-mpt" version = "0.3.0" -source = "git+https://github.com/ethereum-optimism/optimism?rev=96ffbb2a94f19886fe7e27c45f3310e64ccd18b3#96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" +source = "git+https://github.com/ethereum-optimism/optimism?rev=da6d3252491754837a778061db0cc47236ec13c6#da6d3252491754837a778061db0cc47236ec13c6" dependencies = [ "alloy-primitives", "alloy-rlp", @@ -2001,7 +2060,7 @@ dependencies = [ [[package]] name = "kona-preimage" version = "0.3.0" -source = "git+https://github.com/ethereum-optimism/optimism?rev=96ffbb2a94f19886fe7e27c45f3310e64ccd18b3#96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" +source = "git+https://github.com/ethereum-optimism/optimism?rev=da6d3252491754837a778061db0cc47236ec13c6#da6d3252491754837a778061db0cc47236ec13c6" dependencies = [ "alloy-primitives", "async-trait", @@ -2014,7 +2073,7 @@ dependencies = [ [[package]] name = "kona-proof" version = "0.3.0" -source = "git+https://github.com/ethereum-optimism/optimism?rev=96ffbb2a94f19886fe7e27c45f3310e64ccd18b3#96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" +source = "git+https://github.com/ethereum-optimism/optimism?rev=da6d3252491754837a778061db0cc47236ec13c6#da6d3252491754837a778061db0cc47236ec13c6" dependencies = [ "alloy-consensus", "alloy-eips", @@ -2023,7 +2082,7 @@ dependencies = [ "alloy-primitives", "alloy-rlp", "alloy-trie", - "ark-bls12-381", + "ark-bls12-381 0.5.0", "ark-ff 0.5.0", "async-trait", "kona-derive", @@ -2050,7 +2109,7 @@ dependencies = [ [[package]] name = "kona-protocol" version = "0.4.5" -source = "git+https://github.com/ethereum-optimism/optimism?rev=96ffbb2a94f19886fe7e27c45f3310e64ccd18b3#96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" +source = "git+https://github.com/ethereum-optimism/optimism?rev=da6d3252491754837a778061db0cc47236ec13c6#da6d3252491754837a778061db0cc47236ec13c6" dependencies = [ "alloc-no-stdlib", "alloy-consensus", @@ -2079,7 +2138,7 @@ dependencies = [ [[package]] name = "kona-registry" version = "0.4.5" -source = "git+https://github.com/ethereum-optimism/optimism?rev=96ffbb2a94f19886fe7e27c45f3310e64ccd18b3#96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" +source = "git+https://github.com/ethereum-optimism/optimism?rev=da6d3252491754837a778061db0cc47236ec13c6#da6d3252491754837a778061db0cc47236ec13c6" dependencies = [ "alloy-chains", "alloy-eips", @@ -2094,6 +2153,41 @@ dependencies = [ "toml", ] +[[package]] +name = "kona-sp1-client-utils" +version = "0.0.1" +source = "git+https://github.com/ethereum-optimism/optimism?rev=da6d3252491754837a778061db0cc47236ec13c6#da6d3252491754837a778061db0cc47236ec13c6" +dependencies = [ + "alloy-consensus", + "alloy-eips", + "alloy-evm", + "alloy-op-evm", + "alloy-primitives", + "alloy-rlp", + "alloy-sol-types", + "anyhow", + "async-trait", + "cfg-if", + "kona-derive", + "kona-driver", + "kona-executor", + "kona-genesis", + "kona-interop", + "kona-preimage", + "kona-proof", + "kona-protocol", + "kzg-rs", + "op-alloy-consensus", + "op-revm", + "revm", + "rkyv", + "serde", + "serde_json", + "sha2 0.10.9", + "spin 0.10.0", + "tracing", +] + [[package]] name = "konst" version = "0.2.20" @@ -2120,7 +2214,7 @@ dependencies = [ "rkyv", "serde", "serde_arrays", - "sha2", + "sha2 0.10.9", "sp1_bls12_381", "spin 0.9.8", ] @@ -2134,12 +2228,6 @@ dependencies = [ "spin 0.9.8", ] -[[package]] -name = "leb128fmt" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" - [[package]] name = "libc" version = "0.2.186" @@ -2158,12 +2246,6 @@ version = "0.10.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2b23ac50abb8261cb38c6e2a7192d3302e0836dac1628f6a93b82b4fad185897" -[[package]] -name = "linux-raw-sys" -version = "0.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" - [[package]] name = "lock_api" version = "0.4.14" @@ -2411,7 +2493,7 @@ dependencies = [ [[package]] name = "op-alloy" version = "2.0.0" -source = "git+https://github.com/ethereum-optimism/optimism?rev=96ffbb2a94f19886fe7e27c45f3310e64ccd18b3#96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" +source = "git+https://github.com/ethereum-optimism/optimism?rev=da6d3252491754837a778061db0cc47236ec13c6#da6d3252491754837a778061db0cc47236ec13c6" dependencies = [ "op-alloy-consensus", ] @@ -2419,7 +2501,7 @@ dependencies = [ [[package]] name = "op-alloy-consensus" version = "2.0.0" -source = "git+https://github.com/ethereum-optimism/optimism?rev=96ffbb2a94f19886fe7e27c45f3310e64ccd18b3#96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" +source = "git+https://github.com/ethereum-optimism/optimism?rev=da6d3252491754837a778061db0cc47236ec13c6#da6d3252491754837a778061db0cc47236ec13c6" dependencies = [ "alloy-consensus", "alloy-eips", @@ -2437,7 +2519,7 @@ dependencies = [ [[package]] name = "op-alloy-rpc-types" version = "2.0.0" -source = "git+https://github.com/ethereum-optimism/optimism?rev=96ffbb2a94f19886fe7e27c45f3310e64ccd18b3#96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" +source = "git+https://github.com/ethereum-optimism/optimism?rev=da6d3252491754837a778061db0cc47236ec13c6#da6d3252491754837a778061db0cc47236ec13c6" dependencies = [ "alloy-consensus", "alloy-eips", @@ -2455,7 +2537,7 @@ dependencies = [ [[package]] name = "op-alloy-rpc-types-engine" version = "2.0.0" -source = "git+https://github.com/ethereum-optimism/optimism?rev=96ffbb2a94f19886fe7e27c45f3310e64ccd18b3#96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" +source = "git+https://github.com/ethereum-optimism/optimism?rev=da6d3252491754837a778061db0cc47236ec13c6#da6d3252491754837a778061db0cc47236ec13c6" dependencies = [ "alloy-consensus", "alloy-eips", @@ -2465,14 +2547,14 @@ dependencies = [ "alloy-serde", "op-alloy-consensus", "serde", - "sha2", + "sha2 0.10.9", "thiserror", ] [[package]] name = "op-revm" version = "20.0.0" -source = "git+https://github.com/ethereum-optimism/optimism?rev=96ffbb2a94f19886fe7e27c45f3310e64ccd18b3#96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" +source = "git+https://github.com/ethereum-optimism/optimism?rev=da6d3252491754837a778061db0cc47236ec13c6#da6d3252491754837a778061db0cc47236ec13c6" dependencies = [ "alloy-eips", "auto_impl", @@ -2483,13 +2565,14 @@ dependencies = [ [[package]] name = "p256" version = "0.13.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b" +source = "git+https://github.com/sp1-patches/elliptic-curves?tag=patch-p256-13.2-sp1-6.0.0#923794180d3d7716ba3eed94459d4b434f844090" dependencies = [ - "ecdsa", + "ecdsa 0.16.9 (registry+https://github.com/rust-lang/crates.io-index)", "elliptic-curve", + "hex", "primeorder", - "sha2", + "sha2 0.10.9", + "sp1-lib", ] [[package]] @@ -2725,21 +2808,10 @@ dependencies = [ "zerocopy", ] -[[package]] -name = "prettyplease" -version = "0.2.37" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" -dependencies = [ - "proc-macro2", - "syn 2.0.117", -] - [[package]] name = "primeorder" -version = "0.13.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "353e1ca18966c16d9deb1c69278edbc5f194139612772bd9537af60ac231e1e6" +version = "0.13.1" +source = "git+https://github.com/sp1-patches/elliptic-curves?tag=patch-p256-13.2-sp1-6.0.0#923794180d3d7716ba3eed94459d4b434f844090" dependencies = [ "elliptic-curve", ] @@ -2765,22 +2837,22 @@ dependencies = [ ] [[package]] -name = "proc-macro-error-attr2" -version = "2.0.0" +name = "proc-macro-error-attr3" +version = "3.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96de42df36bb9bba5542fe9f1a054b8cc87e172759a1868aa05c1f3acc89dfc5" +checksum = "82366fd7d8b7a440d66d13418820c69df9b3908bcb1a0476d7f5ce5d12f5a04d" dependencies = [ "proc-macro2", "quote", ] [[package]] -name = "proc-macro-error2" -version = "2.0.1" +name = "proc-macro-error3" +version = "3.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11ec05c52be0a07b08061f7dd003e7d7092e0472bc731b4af7bb1ef876109802" +checksum = "b511283ea8a74b4b39447b128c5d00f03a356b7424554b13e298a5550100d9ac" dependencies = [ - "proc-macro-error-attr2", + "proc-macro-error-attr3", "proc-macro2", "quote", "syn 2.0.117", @@ -2801,16 +2873,12 @@ version = "1.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4b45fcc2344c680f5025fe57779faef368840d0bd1f42f216291f0dc4ace4744" dependencies = [ - "bit-set", - "bit-vec", "bitflags", "num-traits", "rand 0.9.4", "rand_chacha 0.9.0", "rand_xorshift", "regex-syntax", - "rusty-fork", - "tempfile", "unarray", ] @@ -2834,12 +2902,6 @@ dependencies = [ "syn 2.0.117", ] -[[package]] -name = "quick-error" -version = "1.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0" - [[package]] name = "quote" version = "1.0.45" @@ -2855,12 +2917,6 @@ version = "5.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" -[[package]] -name = "r-efi" -version = "6.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" - [[package]] name = "radium" version = "0.7.0" @@ -2973,9 +3029,9 @@ dependencies = [ [[package]] name = "reth-codecs" -version = "0.5.2" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb43f4858fef4e3b42b80954d2edf1ff67c8ad7498347083cdc7d0f6eff2f081" +checksum = "1f0dd7f542fbcae0e490ebe13f3eababcc05547375246ff7f62700b533cf3f01" dependencies = [ "alloy-consensus", "alloy-eips", @@ -2991,9 +3047,9 @@ dependencies = [ [[package]] name = "reth-codecs-derive" -version = "0.5.2" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5798ae4d6b264764bc0d742468bd32c7fb515e774645d4930f95ff6311f3ae14" +checksum = "e7e508fcbb8cb775639dbbb56b81b62756d4322f28e76c60a52aa32575f993fe" dependencies = [ "proc-macro2", "quote", @@ -3002,18 +3058,18 @@ dependencies = [ [[package]] name = "reth-zstd-compressors" -version = "0.5.2" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e1bd4ae4f54a2ba813eef082910bc646bd31cab8ed134308fa71f1068331fb84" +checksum = "80addacffc5df9398c55919f8993922d2b688f2aa5753708fdd658ca3cc63e39" dependencies = [ "zstd", ] [[package]] name = "revm" -version = "41.0.0" +version = "42.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d51c254839fb36357d0b02d02e46ba57e683d7b017e2da33b47ae74685a9e59" +checksum = "b7c7fcd426beab3b91300a6d0d5eb8d583c0fad0fba451126e19fd51443eca62" dependencies = [ "revm-bytecode", "revm-context", @@ -3030,9 +3086,9 @@ dependencies = [ [[package]] name = "revm-bytecode" -version = "41.0.0" +version = "42.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e33493cf6d996e9242db4f2002caef48ec9aa8c4f3fff3b18aed10ef3942eec7" +checksum = "537356bdec80dbc04e4e6bb688b3441ff7cf18eecdcf3cac23150633c46467f1" dependencies = [ "bitvec", "revm-primitives", @@ -3040,9 +3096,9 @@ dependencies = [ [[package]] name = "revm-context" -version = "41.0.0" +version = "42.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "86e48fc736d9542c082ea5305be44b6a14b53a615f0147ad57f62189fd813068" +checksum = "cc6512f05f83378e29b2b016fa5bd7f5a533e3625548be4113732e1a536c2564" dependencies = [ "bitvec", "cfg-if", @@ -3056,9 +3112,9 @@ dependencies = [ [[package]] name = "revm-context-interface" -version = "41.0.0" +version = "42.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac68282a454318246817486835a446519291dd0a8167d09de14c7e96f2147696" +checksum = "103fff818b10311034c0c11ff8760294ee0e3c320daab3c5717990fe8ee2617b" dependencies = [ "alloy-eip2930", "alloy-eip7702", @@ -3071,9 +3127,9 @@ dependencies = [ [[package]] name = "revm-database" -version = "41.0.0" +version = "42.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d761681a43e48408ea23f7f66ff56ff7b6128cadb8f9135d1b94787d0c0fc6b4" +checksum = "df72760eab0852100e748c7cb03ce0221626d60ac14534118c84c5cc894fb4c9" dependencies = [ "derive_more", "either", @@ -3085,9 +3141,9 @@ dependencies = [ [[package]] name = "revm-database-interface" -version = "41.0.0" +version = "42.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b96e37d62fa60b45987b408486c84ebef4af4e7ddf1b3b96b4955a7263fd4e92" +checksum = "d9286c059a11be1dee814cafdc3a3ade57521c8caa050785a52c19a9d894f400" dependencies = [ "auto_impl", "either", @@ -3098,9 +3154,9 @@ dependencies = [ [[package]] name = "revm-handler" -version = "41.0.0" +version = "42.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f5e043ebfc0899c435e44475796285898e4f822e637bd67856da79cc170bd9df" +checksum = "09126175c3fa482e71e80cc28c6bb17e681911e472b94d4f7f73dd6780411798" dependencies = [ "auto_impl", "derive-where", @@ -3116,9 +3172,9 @@ dependencies = [ [[package]] name = "revm-inspector" -version = "41.0.0" +version = "42.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e470b2a5e177918944d8cd26174455b61b8fbfbbe7fe411d28b4097e410d11e" +checksum = "4aa55b208b52f0c083ea68147c78866eeecadd7c0071a614f477de316b60648e" dependencies = [ "auto_impl", "either", @@ -3132,9 +3188,9 @@ dependencies = [ [[package]] name = "revm-interpreter" -version = "41.0.0" +version = "42.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa5547f653f9e4c47b4f9a9075a0b7c0faea5fa29b7873f392733a943837825d" +checksum = "fd310927437752ce4bac6997b385772823b84843f04c82e151993bec1265a5ed" dependencies = [ "revm-bytecode", "revm-context-interface", @@ -3144,15 +3200,15 @@ dependencies = [ [[package]] name = "revm-precompile" -version = "41.0.0" +version = "42.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6d785931e4b8750cf9d79c808c22f05979c8d191baafc8badd4651db82584c1c" +checksum = "f2431091420999795df6a200b9f7933defe3d654710560a895e6bcabbd9954a5" dependencies = [ - "ark-bls12-381", + "ark-bls12-381 0.6.0", "ark-bn254", - "ark-ec", - "ark-ff 0.5.0", - "ark-serialize 0.5.0", + "ark-ec 0.6.0", + "ark-ff 0.6.0", + "ark-serialize 0.6.0", "arrayref", "aurora-engine-modexp", "cfg-if", @@ -3161,14 +3217,15 @@ dependencies = [ "revm-context-interface", "revm-primitives", "ripemd", - "sha2", + "sha2 0.11.0", + "substrate-bn", ] [[package]] name = "revm-primitives" -version = "41.0.0" +version = "42.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "66f39151a31afe93d97f7ac894dd9dcc989368d5ccba19ce079bfc1d73b77452" +checksum = "2ef5564c1bce219fd08beca43d4f39fdcbc19193fa4f604c0c6b58950a13194a" dependencies = [ "alloy-primitives", "once_cell", @@ -3176,9 +3233,9 @@ dependencies = [ [[package]] name = "revm-state" -version = "41.0.0" +version = "42.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73ef2fffc28acc41e8ef7525f2b1d16288a10f80579a1b33e7e62abc9892314a" +checksum = "2c4ae66db3abfcb565854dbfc95513bfa440b3dc390ddf8e50b0363d12a6fa79" dependencies = [ "alloy-eip7928", "bitflags", @@ -3197,13 +3254,22 @@ dependencies = [ "subtle", ] +[[package]] +name = "rfc6979" +version = "0.4.0" +source = "git+https://github.com/sp1-patches/signatures?tag=sp1-skip-verify-on-recovery#1880299a48fe7ef249edaa616fd411239fb5daf1" +dependencies = [ + "hmac", + "subtle", +] + [[package]] name = "ripemd" -version = "0.1.3" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd124222d17ad93a644ed9d011a40f4fb64aa54275c08cc216524a9ea82fb09f" +checksum = "4dd4211456b4172d7e44261920c25acf07367c4f04bb5f5d54fc21b090d9b159" dependencies = [ - "digest 0.10.7", + "digest 0.11.3", ] [[package]] @@ -3324,37 +3390,12 @@ dependencies = [ "semver 1.0.28", ] -[[package]] -name = "rustix" -version = "1.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" -dependencies = [ - "bitflags", - "errno", - "libc", - "linux-raw-sys", - "windows-sys", -] - [[package]] name = "rustversion" version = "1.0.22" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" -[[package]] -name = "rusty-fork" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc6bf79ff24e648f6da1f8d1f011e9cac26491b619e6b9280f2b47f1774e6ee2" -dependencies = [ - "fnv", - "quick-error", - "tempfile", - "wait-timeout", -] - [[package]] name = "scopeguard" version = "1.2.0" @@ -3547,8 +3588,7 @@ dependencies = [ [[package]] name = "sha2" version = "0.10.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +source = "git+https://github.com/sp1-patches/RustCrypto-hashes?tag=patch-sha2-0.10.9-sp1-6.0.0#e48b656ebc806117554bb33c2f8687e4637e37ff" dependencies = [ "cfg-if", "cpufeatures 0.2.17", @@ -3556,10 +3596,20 @@ dependencies = [ ] [[package]] -name = "sha3" +name = "sha2" version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be176f1a57ce4e3d31c1a166222d9768de5954f811601fb7ca06fc8203905ce1" +checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.0", + "digest 0.11.3", +] + +[[package]] +name = "sha3" +version = "0.11.0" +source = "git+https://github.com/sp1-patches/RustCrypto-hashes?tag=patch-sha3-0.11.0-sp1-6.0.0#540d99e46fbe7aab00caf83c4144cb4eaaf62a17" dependencies = [ "digest 0.11.3", "keccak", @@ -3614,9 +3664,9 @@ checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" [[package]] name = "slop-algebra" -version = "6.3.1" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8c112cafd4c5c374d267a48c8976d12fca3b0f2cc2e44e6fb1343808310b4fc6" +checksum = "733d477823f02646fa8025c5e2d4227ed806ca33a469def68994f63122f9f106" dependencies = [ "itertools 0.14.0", "p3-field", @@ -3625,9 +3675,9 @@ dependencies = [ [[package]] name = "slop-bn254" -version = "6.3.1" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea991a652ea2e55f0523649f5c9efbfb32cf9fdcc2bf3b3580b4343a94379503" +checksum = "0207095beb89a56e3875a0ca43e5782a2efc8637124b43ce453df42410e12a4c" dependencies = [ "ff", "p3-bn254-fr", @@ -3640,11 +3690,10 @@ dependencies = [ [[package]] name = "slop-challenger" -version = "6.3.1" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33b33f1eaadcd4159157758b0edcf1c14f470915f85c648e660e4740ff83e921" +checksum = "cfc4121b9b84df835c8a6677a90dc9935562172a4a370758987407c793633334" dependencies = [ - "futures", "p3-challenger", "serde", "slop-algebra", @@ -3653,9 +3702,9 @@ dependencies = [ [[package]] name = "slop-koala-bear" -version = "6.3.1" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8795ee9a92ecf0a604c0e3ed20e80bbc38772310c0622f94a2e1b66ca2455cb8" +checksum = "b27fec4aae6811dbf6a384cc7993e74621aede443356ef67c301c19c1f302865" dependencies = [ "lazy_static", "p3-koala-bear", @@ -3668,27 +3717,24 @@ dependencies = [ [[package]] name = "slop-poseidon2" -version = "6.3.1" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25561d9ecf4bcf1aa2e800560ac557bff6dad943b9dc5cd0e8427fceca1e8c65" +checksum = "13388d3c92bac6214ef7585869b968cf895d2715ebbb8b1a0e1464dd2ada30b2" dependencies = [ "p3-poseidon2", ] [[package]] name = "slop-primitives" -version = "6.3.1" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6b24ad70b49f40d6acfe7b1ccf042db25820abe305a4c2232f15204f63f0227" -dependencies = [ - "slop-algebra", -] +checksum = "93f569cac42b24e672f6b06ffde272d4086c2c2620f16d31c1d1ce88cddff681" [[package]] name = "slop-symmetric" -version = "6.3.1" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94e580d03bb5383aca1c12579a8a24b838afb12eb356439e740cba34904b6864" +checksum = "693b50b55c3f5a2bb20dd3b975da79b80e4bf15b839b90f82e5dc7ba7262d3dc" dependencies = [ "p3-symmetric", ] @@ -3704,9 +3750,9 @@ dependencies = [ [[package]] name = "sp1-lib" -version = "6.3.1" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "629b673d6aa3c666b41e14d699323413fa90195c906365ba8c49d1b8e4531151" +checksum = "1d4bc4b2a4b6e5fd3105912c722f51de9d66e2440a44e4ddffaad04bfba42bdf" dependencies = [ "bincode", "elliptic-curve", @@ -3716,9 +3762,9 @@ dependencies = [ [[package]] name = "sp1-primitives" -version = "6.3.1" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "421b4590a89bf7c263f8a64844a4034ee8cb73c351498911ce0acd18da6b5ed2" +checksum = "d387e4babbee68d30774ef52aad88aad3607eda8145a0badfa823e1759187c0c" dependencies = [ "bincode", "blake3", @@ -3728,7 +3774,7 @@ dependencies = [ "lazy_static", "num-bigint 0.4.6", "serde", - "sha2", + "sha2 0.10.9", "slop-algebra", "slop-bn254", "slop-challenger", @@ -3740,19 +3786,18 @@ dependencies = [ [[package]] name = "sp1-zkvm" -version = "6.3.1" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f18fbc79e5a1cc499d3ae3904771104a854493ea12c317ff1407137d86153c26" +checksum = "38ba654f5bcc242a388a82a9a2ab3578b73093b4f460357a1e255e9defe3abf9" dependencies = [ "cfg-if", "critical-section", "embedded-alloc", "getrandom 0.2.17", "getrandom 0.3.4", - "lazy_static", "libm", "rand 0.8.6", - "sha2", + "sha2 0.10.9", "slop-algebra", "sp1-lib", "sp1-primitives", @@ -3831,6 +3876,22 @@ dependencies = [ "syn 2.0.117", ] +[[package]] +name = "substrate-bn" +version = "0.6.0" +source = "git+https://github.com/sp1-patches/bn?tag=patch-0.6.0-sp1-6.0.0-substrate-bn#13747d255e00c158afbb6d4a4a94275edd804bbf" +dependencies = [ + "bytemuck", + "byteorder", + "cfg-if", + "crunchy", + "lazy_static", + "num-bigint 0.4.6", + "rand 0.8.6", + "rustc-hex", + "sp1-lib", +] + [[package]] name = "subtle" version = "2.6.1" @@ -3872,11 +3933,22 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "syn" +version = "3.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12df2e0110f65b775f769bb17ef989067a1d931b2eb822bd4346631eeada89f9" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + [[package]] name = "syn-solidity" -version = "1.6.0" +version = "1.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec005042c7d952febc1a3ef5b0f6674e9054aa836877a31c90b20e25b3d31744" +checksum = "eb6a2e3c7f7a3e4e83d1752cec5d1e357ced0cf96e85419b6a07f227db3def3a" dependencies = [ "paste", "proc-macro2", @@ -3890,19 +3962,6 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" -[[package]] -name = "tempfile" -version = "3.27.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" -dependencies = [ - "fastrand", - "getrandom 0.4.2", - "once_cell", - "rustix", - "windows-sys", -] - [[package]] name = "thiserror" version = "2.0.18" @@ -4147,15 +4206,6 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" -[[package]] -name = "wait-timeout" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11" -dependencies = [ - "libc", -] - [[package]] name = "wasi" version = "0.11.1+wasi-snapshot-preview1" @@ -4168,16 +4218,7 @@ version = "1.0.3+wasi-0.2.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "20064672db26d7cdc89c7798c48a0fdfac8213434a1186e5ef29fd560ae223d6" dependencies = [ - "wit-bindgen 0.57.1", -] - -[[package]] -name = "wasip3" -version = "0.4.0+wasi-0.3.0-rc-2026-01-06" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5" -dependencies = [ - "wit-bindgen 0.51.0", + "wit-bindgen", ] [[package]] @@ -4225,40 +4266,6 @@ dependencies = [ "unicode-ident", ] -[[package]] -name = "wasm-encoder" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "990065f2fe63003fe337b932cfb5e3b80e0b4d0f5ff650e6985b1048f62c8319" -dependencies = [ - "leb128fmt", - "wasmparser", -] - -[[package]] -name = "wasm-metadata" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909" -dependencies = [ - "anyhow", - "indexmap", - "wasm-encoder", - "wasmparser", -] - -[[package]] -name = "wasmparser" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe" -dependencies = [ - "bitflags", - "hashbrown 0.15.5", - "indexmap", - "semver 1.0.28", -] - [[package]] name = "windows-link" version = "0.2.1" @@ -4289,129 +4296,33 @@ dependencies = [ "memchr", ] -[[package]] -name = "wit-bindgen" -version = "0.51.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5" -dependencies = [ - "wit-bindgen-rust-macro", -] - [[package]] name = "wit-bindgen" version = "0.57.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" -[[package]] -name = "wit-bindgen-core" -version = "0.51.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc" -dependencies = [ - "anyhow", - "heck", - "wit-parser", -] - -[[package]] -name = "wit-bindgen-rust" -version = "0.51.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21" -dependencies = [ - "anyhow", - "heck", - "indexmap", - "prettyplease", - "syn 2.0.117", - "wasm-metadata", - "wit-bindgen-core", - "wit-component", -] - -[[package]] -name = "wit-bindgen-rust-macro" -version = "0.51.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c0f9bfd77e6a48eccf51359e3ae77140a7f50b1e2ebfe62422d8afdaffab17a" -dependencies = [ - "anyhow", - "prettyplease", - "proc-macro2", - "quote", - "syn 2.0.117", - "wit-bindgen-core", - "wit-bindgen-rust", -] - -[[package]] -name = "wit-component" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2" -dependencies = [ - "anyhow", - "bitflags", - "indexmap", - "log", - "serde", - "serde_derive", - "serde_json", - "wasm-encoder", - "wasm-metadata", - "wasmparser", - "wit-parser", -] - -[[package]] -name = "wit-parser" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736" -dependencies = [ - "anyhow", - "id-arena", - "indexmap", - "log", - "semver 1.0.28", - "serde", - "serde_derive", - "serde_json", - "unicode-xid", - "wasmparser", -] - [[package]] name = "world-chain-proof-core" -version = "1.0.0-rc.1" +version = "1.0.0-rc.5" dependencies = [ - "alloy-consensus", - "alloy-eips", "alloy-primitives", "alloy-sol-types", - "anyhow", - "async-trait", - "kona-derive", "kona-genesis", - "kona-preimage", "kona-proof", - "kona-protocol", - "kzg-rs", + "kona-sp1-client-utils", "rkyv", "serde", "serde_json", - "sha2", + "sha2 0.10.9", "thiserror", ] [[package]] name = "world-chain-proof-kona-client" -version = "1.0.0-rc.1" +version = "1.0.0-rc.5" dependencies = [ "alloy-consensus", - "alloy-eips", "alloy-evm", "alloy-op-evm", "alloy-primitives", @@ -4420,17 +4331,12 @@ dependencies = [ "async-trait", "kona-derive", "kona-driver", - "kona-executor", "kona-genesis", "kona-preimage", "kona-proof", - "kona-protocol", - "kzg-rs", - "op-alloy-consensus", + "kona-sp1-client-utils", "op-revm", "revm", - "revm-precompile", - "serde", "spin 0.10.0", "tracing", "world-chain-proof-core", @@ -4438,14 +4344,14 @@ dependencies = [ [[package]] name = "world-chain-proof-succinct-aggregation" -version = "1.0.0-rc.1" +version = "1.0.0-rc.5" dependencies = [ "alloy-consensus", "alloy-primitives", "alloy-sol-types", "bincode", "serde_cbor", - "sha2", + "sha2 0.10.9", "sp1-lib", "sp1-zkvm", "world-chain-proof-core", @@ -4453,7 +4359,7 @@ dependencies = [ [[package]] name = "world-chain-proof-succinct-range-ethereum" -version = "1.0.0-rc.1" +version = "1.0.0-rc.5" dependencies = [ "kona-proof", "rkyv", @@ -4465,11 +4371,10 @@ dependencies = [ [[package]] name = "world-chain-proof-succinct-range-utils" -version = "1.0.0-rc.1" +version = "1.0.0-rc.5" dependencies = [ "anyhow", "kona-proof", - "sp1-zkvm", "tracing", "tracing-subscriber", "world-chain-proof-core", @@ -4558,3 +4463,8 @@ dependencies = [ "cc", "pkg-config", ] + +[[patch.unused]] +name = "tiny-keccak" +version = "2.0.2" +source = "git+https://github.com/sp1-patches/tiny-keccak?tag=patch-2.0.2-sp1-6.0.0#957430a459f7a2332ab5bab4a12f9b473bb95c87" diff --git a/proofs/measured/sp1-programs/Cargo.toml b/proofs/measured/sp1-programs/Cargo.toml index 5a742bf65..318965b62 100644 --- a/proofs/measured/sp1-programs/Cargo.toml +++ b/proofs/measured/sp1-programs/Cargo.toml @@ -7,28 +7,42 @@ members = [ ] [workspace.package] -version = "1.0.0-rc.1" +version = "1.0.0-rc.5" edition = "2024" license = "MIT" homepage = "https://world.org/world-chain" repository = "https://github.com/worldcoin/world-chain/" [workspace.dependencies] -alloy-consensus = { version = "=2.1.1", default-features = false, features = ["serde"] } -alloy-primitives = { version = "1.6.0", default-features = false, features = ["serde", "std"] } -alloy-sol-types = "1.6.0" +alloy-consensus = { version = "2.3.0", default-features = false, features = ["serde"] } +alloy-primitives = { version = "1.6.1", default-features = false, features = ["serde", "std"] } +alloy-sol-types = "1.6.1" anyhow = { version = "1.0.86", default-features = false } bincode = "1" -kona-proof = { git = "https://github.com/ethereum-optimism/optimism", rev = "96ffbb2a94f19886fe7e27c45f3310e64ccd18b3" } +kona-proof = { git = "https://github.com/ethereum-optimism/optimism", rev = "da6d3252491754837a778061db0cc47236ec13c6" } rkyv = { version = "0.8", features = ["hashbrown-0_15", "std"] } serde = { version = "1", features = ["derive"] } serde_cbor = "0.11" sha2 = "0.10.9" -sp1-lib = { version = "=6.3.1", features = ["verify"] } -sp1-zkvm = { version = "=6.3.1", features = ["verify"] } +sp1-lib = { version = "=6.8.1", features = ["verify"] } +sp1-zkvm = { version = "=6.8.1", features = ["verify"] } thiserror = "2" tracing = { version = "0.1", default-features = false } tracing-subscriber = { version = "0.3.18", features = ["fmt"] } world-chain-proof-core = { path = "../core", default-features = false } world-chain-proof-kona-client = { path = "../kona-client" } world-chain-proof-succinct-range-utils = { path = "range-utils", default-features = false } + +[profile.release] +panic = "abort" + +# Use SP1-accelerated hashing and curve arithmetic to reduce guest RISC-V cycles. +# Cargo requires these patches at the guest workspace root to apply them to Kona. +[patch.crates-io] +sha2 = { git = "https://github.com/sp1-patches/RustCrypto-hashes", tag = "patch-sha2-0.10.9-sp1-6.0.0" } +sha3 = { git = "https://github.com/sp1-patches/RustCrypto-hashes", tag = "patch-sha3-0.11.0-sp1-6.0.0" } +k256 = { git = "https://github.com/sp1-patches/elliptic-curves", tag = "patch-k256-13.4-sp1-6.0.0" } +p256 = { git = "https://github.com/sp1-patches/elliptic-curves", tag = "patch-p256-13.2-sp1-6.0.0" } +substrate-bn = { git = "https://github.com/sp1-patches/bn", tag = "patch-0.6.0-sp1-6.0.0-substrate-bn" } +# Currently unused: guest Keccak hashing uses the patched sha3 crate. +tiny-keccak = { git = "https://github.com/sp1-patches/tiny-keccak", tag = "patch-2.0.2-sp1-6.0.0" } diff --git a/proofs/measured/sp1-programs/aggregation/src/main.rs b/proofs/measured/sp1-programs/aggregation/src/main.rs index ccdf8aab8..b741f552a 100644 --- a/proofs/measured/sp1-programs/aggregation/src/main.rs +++ b/proofs/measured/sp1-programs/aggregation/src/main.rs @@ -13,7 +13,7 @@ use alloy_sol_types::SolValue; use sha2::{Digest, Sha256}; use world_chain_proof_core::{ boot::TransitionPublicValues, - types::{AggregationInputs, AggregationPublicValues, u32_to_u8}, + types::{AggregationInputs, AggregationPublicValues}, }; pub fn main() { @@ -67,8 +67,7 @@ pub fn main() { } let first = &agg_inputs.transition_public_values[0]; - let last = - &agg_inputs.transition_public_values[agg_inputs.transition_public_values.len() - 1]; + let last = &agg_inputs.transition_public_values[agg_inputs.transition_public_values.len() - 1]; let aggregated_transition_public_values = TransitionPublicValues { l1Head: agg_inputs.latest_l1_checkpoint_head, l2PreRoot: first.l2PreRoot, @@ -78,7 +77,12 @@ pub fn main() { rollupConfigHash: last.rollupConfigHash, }; - let multi_block_vkey_b256 = B256::from(u32_to_u8(agg_inputs.multi_block_vkey)); + let multi_block_vkey_b256 = B256::from_slice( + agg_inputs + .multi_block_vkey + .map(u32::to_be_bytes) + .as_flattened(), + ); let aggregation_public_values = AggregationPublicValues { transitionPublicValues: aggregated_transition_public_values, multiBlockVKey: multi_block_vkey_b256, diff --git a/proofs/measured/sp1-programs/range-ethereum/Cargo.toml b/proofs/measured/sp1-programs/range-ethereum/Cargo.toml index 7a05fd4d1..de1775d2a 100644 --- a/proofs/measured/sp1-programs/range-ethereum/Cargo.toml +++ b/proofs/measured/sp1-programs/range-ethereum/Cargo.toml @@ -11,7 +11,7 @@ kona-proof.workspace = true rkyv.workspace = true sp1-zkvm.workspace = true world-chain-proof-core.workspace = true -world-chain-proof-kona-client.workspace = true +world-chain-proof-kona-client = { workspace = true, features = ["bn"] } world-chain-proof-succinct-range-utils.workspace = true [features] diff --git a/proofs/measured/sp1-programs/range-utils/Cargo.toml b/proofs/measured/sp1-programs/range-utils/Cargo.toml index 181e8c2bf..1b51ef878 100644 --- a/proofs/measured/sp1-programs/range-utils/Cargo.toml +++ b/proofs/measured/sp1-programs/range-utils/Cargo.toml @@ -8,7 +8,6 @@ repository.workspace = true [dependencies] kona-proof.workspace = true -sp1-zkvm.workspace = true world-chain-proof-core.workspace = true world-chain-proof-kona-client.workspace = true diff --git a/proofs/measurements.json b/proofs/measurements.json index 34f9d7e9b..366c4a2f0 100644 --- a/proofs/measurements.json +++ b/proofs/measurements.json @@ -1,19 +1,19 @@ { "nitro": { - "pcr0": "0x1047a9abb6fdfc70f1e4df56faf857fba33b7c2643833e0845060d21133a1812d31c113af3ff4582dfcb5ee5af3a5477", + "pcr0": "0x12b7a925016388b033de982d704ebfd88803f6ea23fedde78462076469a05de008feaec3ecf69d39649644dda4a049cf", "pcr1": "0xab92a79f22cbca162b415c97f3406327ab858f9a73ffd4f7720710529eee87f085d21c3dd2819ef63263b0dad0b4a9d6", - "pcr2": "0x94bc876bd0dfc0f5c8d8f1c34cbdbc0c4e6f2521428805901b660c85391afca77b435b1b1cace64aba01313ae91d2c3b" + "pcr2": "0x1bd6b11e70e48d3f85362ae77dfbd485e755f725879ca11970d6048dcb1bc0d5ca4e98e2361f2322974f7b896e2fe5b2" }, "sp1": { - "aggregation_vkey": "0x00e9ee2c9771b4a3596809af947148b803be6c9989bc98dded1c185ebffe18c9", + "aggregation_vkey": "0x00c5ca08abcb709079fb5b643ae0123e901729706282716a2556488171676b14", "elfs": { "world-chain-aggregation": { - "sha256": "0147dc683e64a75b9ecb869042bb3db3c946a258be3b8f66fa9f5ae497210c0c" + "sha256": "0be7df52cd333efd6c76a30f4684f90670d2c2ce7d68e5621afa289941694458" }, "world-chain-range-ethereum": { - "sha256": "ca68d1f513e81bff7b0977f5425152f445b6e0c14733acec1b03ecceeef4ddb0" + "sha256": "6d4c3894e093946a8b9627c7ce708640b806b893b905545df193c98dc5395237" } }, - "range_vkey_commitment": "0x729e953b5968b34c75ab76a94e819fdb4000c24422f695181a1e29e522d13fa0" + "range_vkey_commitment": "0x58d32b3603ce4ffc79d0a29e1775499d079d68d73b7b9b9a3cdfb968794122ce" } } diff --git a/proofs/metrics/Cargo.toml b/proofs/metrics/Cargo.toml index 8858c892c..24371b21a 100644 --- a/proofs/metrics/Cargo.toml +++ b/proofs/metrics/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "world-chain-proof-metrics" -version = "1.0.0-rc.1" +version = "1.0.0-rc.5" edition.workspace = true rust-version.workspace = true license.workspace = true diff --git a/proofs/metrics/src/lib.rs b/proofs/metrics/src/lib.rs index c13d9faa5..7ed8ed1eb 100644 --- a/proofs/metrics/src/lib.rs +++ b/proofs/metrics/src/lib.rs @@ -8,30 +8,40 @@ use std::{ use alloy_json_rpc::{RequestPacket, ResponsePacket}; use alloy_primitives::{Address, utils::format_ether}; use alloy_provider::Provider; -use alloy_rpc_client::{ClientBuilder, RpcClient}; -use alloy_transport::{BoxFuture, TransportError}; +use alloy_rpc_client::RpcClient; +use alloy_transport::{BoxFuture, TransportError, layers::FallbackService}; use telemetry_batteries::reexports::metrics; use tower::{Layer, Service}; -use tracing::warn; +use tracing::{info, warn}; use url::Url; /// Ethereum L1 execution RPC target label. pub const RPC_TARGET_L1_EXECUTION: &str = "l1_execution"; /// OP consensus-client RPC target label. pub const RPC_TARGET_L2_CONSENSUS: &str = "l2_consensus"; +/// Primary RPC endpoint role label. +pub const RPC_ENDPOINT_PRIMARY: &str = "primary"; +/// Fallback RPC endpoint role label. +pub const RPC_ENDPOINT_FALLBACK: &str = "fallback"; +/// Verifying RPC endpoint role label. +pub const RPC_ENDPOINT_VERIFYING: &str = "verifying"; /// Current transaction-sending wallet balance in ETH. pub const METRICS_WALLET_BALANCE_ETH: &str = "wallet.balance_eth"; /// Latest finalized L2 block reported by the OP consensus client. pub const METRICS_L2_FINALIZED_BLOCK_NUMBER: &str = "l2.finalized_block_number"; +/// Whether lineage selection is using the configured recovery parent. +pub const METRICS_LINEAGE_RECOVERY_ACTIVE: &str = "lineage.recovery_active"; /// Completed outbound RPC requests. pub const METRICS_RPC_CLIENT_REQUESTS: &str = "rpc.client.requests"; /// Confirmed challenge transactions. pub const METRICS_CHALLENGES_SUBMITTED: &str = "challenges.submitted"; -/// ETH bonded by proposer and challenger transactions. -pub const METRICS_BONDS_POSTED_ETH: &str = "bonds.posted_eth"; -/// ETH transferred back to proposer and challenger wallets after bond settlement. -pub const METRICS_BONDS_WITHDRAWN_ETH: &str = "bonds.withdrawn_eth"; +/// Bond-token base units locked by proposer and challenger transactions. +pub const METRICS_BONDS_LOCKED_BASE_UNITS: &str = "bonds.locked_base_units"; +/// Bond-token base units immediately reusable by a proof-system participant. +pub const METRICS_VAULT_AVAILABLE_BALANCE_BASE_UNITS: &str = "vault.available_balance_base_units"; +/// Games processed by a bond settlement manager. +pub const METRICS_GAMES_CLOSED: &str = "games.closed"; /// Confirmed on-chain proof-lane submissions. pub const METRICS_PROOF_LANES_SUBMITTED: &str = "proof_lanes.submitted"; /// Newly created durable proof requests. @@ -42,6 +52,13 @@ pub const METRICS_PROOF_JOBS_CLAIMED: &str = "proof_jobs.claimed"; pub const METRICS_PROOF_JOBS_COMPLETED: &str = "proof_jobs.completed"; /// End-to-end worker proof-job attempt duration. pub const METRICS_PROOF_JOB_DURATION_SECONDS: &str = "proof_job.duration_seconds"; +pub const METRICS_PROOF_SUBMISSION_INCLUSION_SECONDS: &str = "proof_submission.inclusion_seconds"; +/// Completed witness-collection attempts. +pub const METRICS_WITNESS_COLLECTIONS_COMPLETED: &str = "witness_collection.completed"; +/// Witness-collection duration. +pub const METRICS_WITNESS_COLLECTION_DURATION_SECONDS: &str = "witness_collection.duration_seconds"; +/// Duration of a proof-worker phase. +pub const METRICS_PROOF_PHASE_DURATION_SECONDS: &str = "proof_phase.duration_seconds"; /// Whether this worker's enclave signing key is registered on-chain. pub const METRICS_ENCLAVE_KEY_REGISTERED: &str = "enclave_key.registered"; /// Enclave key registration attempts, by outcome. @@ -55,6 +72,11 @@ pub const METRICS_SP1_NETWORK_BALANCE_SUFFICIENT: &str = "sp1_network_balance_su /// Registers shared metric descriptions. pub fn describe_metrics() { + metrics::describe_gauge!( + METRICS_LINEAGE_RECOVERY_ACTIVE, + metrics::Unit::Count, + "Whether lineage selection is using the configured recovery parent." + ); metrics::describe_gauge!( METRICS_WALLET_BALANCE_ETH, metrics::Unit::Count, @@ -68,7 +90,7 @@ pub fn describe_metrics() { metrics::describe_counter!( METRICS_RPC_CLIENT_REQUESTS, metrics::Unit::Count, - "Completed outbound RPC requests by target, method, and outcome." + "Completed outbound RPC requests by target, endpoint role, method, and outcome." ); metrics::describe_counter!( METRICS_CHALLENGES_SUBMITTED, @@ -76,14 +98,19 @@ pub fn describe_metrics() { "Number of challenge transactions successfully confirmed on L1." ); metrics::describe_histogram!( - METRICS_BONDS_POSTED_ETH, + METRICS_BONDS_LOCKED_BASE_UNITS, metrics::Unit::Count, - "ETH bonded by successfully confirmed proposer and challenger transactions." + "Bond-token base units locked by successfully confirmed proposer and challenger transactions." ); - metrics::describe_histogram!( - METRICS_BONDS_WITHDRAWN_ETH, + metrics::describe_gauge!( + METRICS_VAULT_AVAILABLE_BALANCE_BASE_UNITS, + metrics::Unit::Count, + "Bond-token base units immediately reusable by the participant in the proof-system staking vault." + ); + metrics::describe_counter!( + METRICS_GAMES_CLOSED, metrics::Unit::Count, - "ETH transferred after successfully confirmed proposer and challenger bond withdrawals." + "Games submitted for settlement or observed as already settled." ); metrics::describe_counter!( METRICS_PROOF_LANES_SUBMITTED, @@ -110,6 +137,26 @@ pub fn describe_metrics() { metrics::Unit::Seconds, "End-to-end worker proof-job attempt duration by backend and outcome." ); + metrics::describe_histogram!( + METRICS_PROOF_SUBMISSION_INCLUSION_SECONDS, + metrics::Unit::Seconds, + "Time from proof submission attempt to first observed inclusion, excluding confirmations." + ); + metrics::describe_counter!( + METRICS_WITNESS_COLLECTIONS_COMPLETED, + metrics::Unit::Count, + "Completed Kona witness-collection attempts by backend and outcome." + ); + metrics::describe_histogram!( + METRICS_WITNESS_COLLECTION_DURATION_SECONDS, + metrics::Unit::Seconds, + "Kona witness-collection duration by backend and outcome." + ); + metrics::describe_histogram!( + METRICS_PROOF_PHASE_DURATION_SECONDS, + metrics::Unit::Seconds, + "Proof-worker phase duration by backend, phase, and outcome." + ); metrics::describe_gauge!( METRICS_ENCLAVE_KEY_REGISTERED, metrics::Unit::Count, @@ -139,6 +186,11 @@ pub fn describe_metrics() { ); } +/// Records whether the service is selecting a lineage from its recovery parent. +pub fn record_lineage_recovery_active(active: bool) { + metrics::gauge!(METRICS_LINEAGE_RECOVERY_ACTIVE).set(if active { 1.0 } else { 0.0 }); +} + /// Records one bisection of an unexecutable SP1 range proof. pub fn increment_sp1_range_bisections() { metrics::counter!(METRICS_SP1_RANGE_BISECTIONS).increment(1); @@ -178,20 +230,42 @@ pub fn increment_challenges_submitted() { metrics::counter!(METRICS_CHALLENGES_SUBMITTED).increment(1); } -/// Records ETH posted by a successfully confirmed bond transaction. -pub fn record_bond_posted(role: &'static str, amount: alloy_primitives::U256) { - record_bond_amount(METRICS_BONDS_POSTED_ETH, role, amount); +/// Records bond-token base units locked by a successfully confirmed bond transaction. +pub fn record_bond_locked(role: &'static str, amount: alloy_primitives::U256) { + match amount.to_string().parse::() { + Ok(amount_base_units) => { + metrics::histogram!(METRICS_BONDS_LOCKED_BASE_UNITS, "role" => role) + .record(amount_base_units); + } + Err(error) => warn!(%error, %role, ?amount, "failed to convert bond-token base units"), + } } -/// Records ETH transferred by a successfully confirmed bond withdrawal. -pub fn record_bond_withdrawn(role: &'static str, amount: alloy_primitives::U256) { - record_bond_amount(METRICS_BONDS_WITHDRAWN_ETH, role, amount); +/// Records a game handled by a bond settlement manager. +pub fn increment_games_closed(role: &'static str, result: &'static str) { + metrics::counter!(METRICS_GAMES_CLOSED, "role" => role, "result" => result).increment(1); } -fn record_bond_amount(metric: &'static str, role: &'static str, amount: alloy_primitives::U256) { - match format_ether(amount).parse::() { - Ok(amount_eth) => metrics::histogram!(metric, "role" => role).record(amount_eth), - Err(error) => warn!(%error, %role, ?amount, "failed to convert bond amount to ETH"), +/// Records and logs an account's immediately reusable bond-token balance in base units. +pub fn record_vault_balance( + vault_address: Address, + account: Address, + role: &'static str, + balance: alloy_primitives::U256, +) { + let gauge = metrics::gauge!( + METRICS_VAULT_AVAILABLE_BALANCE_BASE_UNITS, + "role" => role, + "address" => account.to_string(), + ); + match balance.to_string().parse::() { + Ok(balance_base_units) => { + gauge.set(balance_base_units); + info!(%role, %account, %vault_address, %balance, balance_base_units, "refreshed available ERC-20 vault balance"); + } + Err(error) => { + warn!(%account, %error, ?balance, "failed to convert vault balance base units") + } } } @@ -210,6 +284,11 @@ pub fn increment_proof_jobs_claimed(backend: &'static str) { metrics::counter!(METRICS_PROOF_JOBS_CLAIMED, "backend" => backend).increment(1); } +/// Records first observed inclusion, including reverted transactions. +pub fn record_proof_submission_inclusion(duration: Duration) { + metrics::histogram!(METRICS_PROOF_SUBMISSION_INCLUSION_SECONDS).record(duration.as_secs_f64()); +} + /// Records a completed worker proof-job attempt and its duration. pub fn record_proof_job_completed( backend: &'static str, @@ -230,6 +309,43 @@ pub fn record_proof_job_completed( .record(duration.as_secs_f64()); } +/// Records one Kona witness-collection attempt. +/// +/// `outcome` is limited to `success`, `timeout`, or `error`. +pub fn record_witness_collection(backend: &'static str, outcome: &'static str, duration: Duration) { + metrics::counter!( + METRICS_WITNESS_COLLECTIONS_COMPLETED, + "backend" => backend, + "outcome" => outcome, + ) + .increment(1); + metrics::histogram!( + METRICS_WITNESS_COLLECTION_DURATION_SECONDS, + "backend" => backend, + "outcome" => outcome, + ) + .record(duration.as_secs_f64()); +} + +/// Records one proof-worker phase. +/// +/// Labels are intentionally low-cardinality: backend, phase, and outcome only. Query-specific +/// identifiers and range bounds remain in structured logs. +pub fn record_proof_phase_duration( + backend: &'static str, + phase: &'static str, + outcome: &'static str, + duration: Duration, +) { + metrics::histogram!( + METRICS_PROOF_PHASE_DURATION_SECONDS, + "backend" => backend, + "phase" => phase, + "outcome" => outcome, + ) + .record(duration.as_secs_f64()); +} + /// Refreshes a transaction-sending wallet's balance gauge. pub async fn refresh_wallet_balance

(provider: &P, address: Address) where @@ -257,18 +373,28 @@ pub const DEFAULT_RPC_REQUEST_TIMEOUT_SECONDS: u64 = 10; /// /// `request_timeout` bounds each individual request so a hung connection cannot stall a /// service's poll loop indefinitely. It is per request, not per operation: a confirmation wait -/// polls with fresh requests and so is not capped by this value. +/// polls with fresh requests and so is not capped by this value. When `fallback_url` is set, read +/// requests use both endpoints concurrently while transaction submission remains sequential. pub fn metered_http_client( url: Url, + fallback_url: Option, target: &'static str, request_timeout: Duration, ) -> Result { let client = alloy_transport_http::reqwest::Client::builder() .timeout(request_timeout) .build()?; - Ok(ClientBuilder::default() - .layer(RpcMetricsLayer { target }) - .http_with_client(client, url)) + let transports = std::iter::once((RPC_ENDPOINT_PRIMARY, url)) + .chain(fallback_url.map(|url| (RPC_ENDPOINT_FALLBACK, url))) + .map(|(endpoint, url)| { + RpcMetricsLayer { target, endpoint } + .layer(alloy_transport_http::Http::with_client(client.clone(), url)) + }) + .collect(); + let fallback = FallbackService::new(transports, 3) + .append_sequential_method("eth_sendRawTransaction") + .append_sequential_method("eth_sendTransaction"); + Ok(RpcClient::new(fallback, false)) } /// Renders an RPC endpoint for logs with any embedded credential removed. @@ -294,6 +420,7 @@ pub fn redact_endpoint(url: &str) -> String { #[derive(Debug, Clone, Copy)] struct RpcMetricsLayer { target: &'static str, + endpoint: &'static str, } impl Layer for RpcMetricsLayer { @@ -302,6 +429,7 @@ impl Layer for RpcMetricsLayer { fn layer(&self, inner: S) -> Self::Service { RpcMetricsService { target: self.target, + endpoint: self.endpoint, inner, } } @@ -310,6 +438,7 @@ impl Layer for RpcMetricsLayer { #[derive(Debug, Clone)] struct RpcMetricsService { target: &'static str, + endpoint: &'static str, inner: S, } @@ -332,6 +461,7 @@ where fn call(&mut self, request: RequestPacket) -> Self::Future { let target = self.target; + let endpoint = self.endpoint; let method = request .as_single() .map_or_else(|| "batch".to_owned(), |request| request.method().to_owned()); @@ -340,7 +470,7 @@ where Box::pin(async move { let result = inner.call(request).await; let success = matches!(&result, Ok(response) if response.is_success()); - record_rpc_request(target, method, success); + record_rpc_request(target, endpoint, method, success); result }) } @@ -349,12 +479,14 @@ where /// Records the outcome of a completed chain RPC request. pub fn record_rpc_request( target: &'static str, + endpoint: &'static str, method: impl Into, success: bool, ) { metrics::counter!( METRICS_RPC_CLIENT_REQUESTS, "target" => target, + "endpoint" => endpoint, "method" => method.into(), "outcome" => if success { "success" } else { "error" }, ) diff --git a/proofs/protocol/Cargo.toml b/proofs/protocol/Cargo.toml index b6cc5d625..b16c780d1 100644 --- a/proofs/protocol/Cargo.toml +++ b/proofs/protocol/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "world-chain-proof-protocol" -version = "1.0.0-rc.1" +version = "1.0.0-rc.5" edition.workspace = true rust-version.workspace = true license.workspace = true diff --git a/proofs/protocol/src/bindings.rs b/proofs/protocol/src/bindings.rs index b9a76cc37..67b81d95f 100644 --- a/proofs/protocol/src/bindings.rs +++ b/proofs/protocol/src/bindings.rs @@ -63,7 +63,7 @@ sol! { function protocolFeeRecipient() external view returns (address); function disputeGameFactory() external view returns (address); function anchorStateRegistry() external view returns (address); - function weth() external view returns (address); + function bondVault() external view returns (address); // Proposal context. function rootId() external view returns (bytes32); @@ -102,19 +102,31 @@ sol! { returns (bool resolvable, uint8 outcome, uint8 reason); // Mutating entry points. - function challenge() external payable returns (uint8 proposalStatus); + function challenge() external returns (uint8 proposalStatus); /// `proof` is the compact payload built by `encode_compact_proof`. function submitProofLane(bytes calldata proof) external returns (uint8 proposalStatus); function resolve() external returns (uint8 status); function closeGame() external; - function claimCredit(address recipient) external; // Bond settlement. function bondDistributionMode() external view returns (uint8); function totalBonds() external view returns (uint256); function normalModeCredit(address recipient) external view returns (uint256); function refundModeCredit(address recipient) external view returns (uint256); - function credit(address recipient) external view returns (uint256); + } + + /// Singleton ERC-20 vault that locks and settles WIP-1006 proposal and challenge bonds. + #[sol(rpc)] + interface IERC20StakingVault { + event ProposerBondLocked(address indexed game, address indexed proposer, uint256 amount); + function disputeGameFactory() external view returns (address); + function token() external view returns (address); + function availableBalance(address account) external view returns (uint256 amount); + function gameBonds(address game) + external + view + returns (uint256 proposerBond, uint256 challengerBond, bool settled); + function deposit(address account, uint256 amount) external; } /// Stock OP Stack `AnchorStateRegistry`. @@ -127,20 +139,11 @@ sol! { function isGameBlacklisted(address game) external view returns (bool); function isGameRetired(address game) external view returns (bool); function isGameProper(address game) external view returns (bool); + function isGameRespected(address game) external view returns (bool); function isGameResolved(address game) external view returns (bool); function isGameFinalized(address game) external view returns (bool); function isGameClaimValid(address game) external view returns (bool); function setAnchorState(address game) external; function paused() external view returns (bool); } - - /// Stock OP Stack `DelayedWETH`, the bond custody contract behind every game. - #[sol(rpc)] - interface IDelayedWETH { - function delay() external view returns (uint256); - function withdrawals(address owner, address recipient) - external - view - returns (uint256 amount, uint256 timestamp); - } } diff --git a/proofs/protocol/src/consensus_provider.rs b/proofs/protocol/src/consensus_provider.rs index 12a920e7f..380b4acc1 100644 --- a/proofs/protocol/src/consensus_provider.rs +++ b/proofs/protocol/src/consensus_provider.rs @@ -4,7 +4,7 @@ use serde::{Deserialize, de::DeserializeOwned}; use serde_json::Value; use thiserror::Error; use world_chain_proof_metrics::{ - RPC_TARGET_L2_CONSENSUS, record_l2_finalized_block, record_rpc_request, + RPC_ENDPOINT_PRIMARY, RPC_TARGET_L2_CONSENSUS, record_l2_finalized_block, record_rpc_request, }; /// Source for all consensus clients requests. @@ -59,6 +59,7 @@ impl ConsensusError { pub struct OptimismConsensusClient { client: reqwest::Client, rpc_url: String, + endpoint: &'static str, } impl OptimismConsensusClient { @@ -67,9 +68,16 @@ impl OptimismConsensusClient { Self { client: reqwest::Client::new(), rpc_url: rpc_url.into(), + endpoint: RPC_ENDPOINT_PRIMARY, } } + /// Assigns the stable metric role for this endpoint. + pub const fn with_endpoint(mut self, endpoint: &'static str) -> Self { + self.endpoint = endpoint; + self + } + async fn request( &self, method: &'static str, @@ -80,7 +88,12 @@ impl OptimismConsensusClient { T: DeserializeOwned, { let result = self.request_inner(method, params, missing_result).await; - record_rpc_request(RPC_TARGET_L2_CONSENSUS, method, result.is_ok()); + record_rpc_request( + RPC_TARGET_L2_CONSENSUS, + self.endpoint, + method, + result.is_ok(), + ); result } diff --git a/proofs/protocol/src/lib.rs b/proofs/protocol/src/lib.rs index 05d8ffe12..1787779e9 100644 --- a/proofs/protocol/src/lib.rs +++ b/proofs/protocol/src/lib.rs @@ -14,15 +14,18 @@ mod proof_game; mod types; // re-exports -pub use bindings::{IAnchorStateRegistry, IDelayedWETH, IDisputeGameFactory, IMultiProofGame}; +pub use bindings::{ + IAnchorStateRegistry, IDisputeGameFactory, IERC20StakingVault, IMultiProofGame, +}; pub use consensus_provider::{ ConsensusError, ConsensusProvider, OptimismConsensusClient, VerifyingConsensusProvider, }; pub use lineage::{ LineageAnchor, LineageError, LineageGame, LineageProvider, LineageStop, LineageTransition, - RegisteredLineageConfig, SelectedLineage, SelectedLineageGame, read_game_for_transition, - read_lineage_anchor, read_lineage_resolution_status, read_registered_lineage_config, - select_lineage, + RecoveryParent, RegisteredLineageConfig, SelectedLineage, SelectedLineageGame, + read_game_for_transition, read_game_has_retry, read_lineage_anchor, + read_lineage_resolution_status, read_recovery_parent, read_registered_bond_vault, + read_registered_lineage_config, select_lineage, }; pub use proof_game::{ AlloyProofGameProvider, ProofGameContext, ProofGameContextError, ProofGameProvider, diff --git a/proofs/protocol/src/lineage.rs b/proofs/protocol/src/lineage.rs index 110f60cd0..0eff1e22e 100644 --- a/proofs/protocol/src/lineage.rs +++ b/proofs/protocol/src/lineage.rs @@ -3,8 +3,9 @@ use crate::{ IDisputeGameFactory, IMultiProofGame, InvalidationReasonError, MAX_ATTEMPT_SCAN, MULTI_PROOF_GAME_TYPE, ProposalCommitment, ResolutionStatus, }; -use alloy_primitives::{Address, B256}; +use alloy_primitives::{Address, B256, U256}; use alloy_provider::Provider; +use alloy_sol_types::SolValue; use async_trait::async_trait; use thiserror::Error; @@ -17,6 +18,15 @@ pub struct LineageAnchor { pub l2_block_number: u64, } +/// Registry eligibility and claim of an operator-selected recovery parent. +#[derive(Debug, Clone, Copy)] +pub struct RecoveryParent { + pub anchor: LineageAnchor, + pub root_claim: B256, + /// Registered, proper, respected, and resolved with `DEFENDER_WINS`. + pub eligible: bool, +} + /// Expected state transition at one proposal interval. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct LineageTransition { @@ -103,6 +113,10 @@ impl SelectedLineage { /// Failure while reading or reconstructing the selected proposal lineage. #[derive(Debug, Error)] pub enum LineageError { + #[error("recovery parent {0} must be a registered, proper, respected defender-winning game")] + InvalidRecoveryParent(Address), + #[error("recovery parent {0} does not match the canonical finalized L2 root")] + NonCanonicalRecoveryParent(Address), #[error("contract error: {0}")] Contract(String), #[error("l2 block number overflow: parent {parent_block} + interval {block_interval}")] @@ -128,6 +142,11 @@ pub trait LineageProvider: Send + Sync { async fn lineage_anchor(&self) -> Result; + /// Reads the claim and registry eligibility of a recovery parent. + async fn recovery_parent(&self, game: Address) -> Result; + + async fn lineage_anchor_claim_valid(&self, game: Address) -> Result; + async fn game_for_transition( &self, transition: LineageTransition, @@ -143,6 +162,7 @@ pub trait LineageProvider: Send + Sync { pub async fn select_lineage( execution: &E, consensus: &C, + recovery_parent: Option

, ) -> Result where E: LineageProvider, @@ -153,8 +173,32 @@ where return Err(LineageError::ZeroBlockInterval); } - let anchor = execution.lineage_anchor().await?; + let mut anchor = execution.lineage_anchor().await?; let finalized_block = consensus.latest_l2_finalized_block().await?; + world_chain_proof_metrics::record_lineage_recovery_active(false); + if let Some(address) = recovery_parent { + if address == Address::ZERO { + return Err(LineageError::InvalidRecoveryParent(address)); + } + let recovery = execution.recovery_parent(address).await?; + let recovered = anchor.l2_block_number > recovery.anchor.l2_block_number + && execution.lineage_anchor_claim_valid(anchor.address).await?; + if !recovered { + world_chain_proof_metrics::record_lineage_recovery_active(true); + if !recovery.eligible { + return Err(LineageError::InvalidRecoveryParent(address)); + } + if recovery.anchor.l2_block_number > finalized_block + || consensus + .output_root_at_block(recovery.anchor.l2_block_number) + .await? + != recovery.root_claim + { + return Err(LineageError::NonCanonicalRecoveryParent(address)); + } + anchor = recovery.anchor; + } + } let mut parent = anchor; let mut games = Vec::new(); @@ -208,6 +252,45 @@ where } } +/// Reads recovery eligibility using only the standard dispute-game ABI, including legacy parents. +pub async fn read_recovery_parent

( + provider: &P, + registry: &IAnchorStateRegistry::IAnchorStateRegistryInstance

, + address: Address, +) -> Result +where + P: Provider + Clone, +{ + if address == Address::ZERO || address == *registry.address() { + return Err(LineageError::InvalidRecoveryParent(address)); + } + let game = IMultiProofGame::IMultiProofGameInstance::new(address, provider.clone()); + let (proper, respected, status, root_claim, block_number) = provider + .multicall() + .add(registry.isGameProper(address)) + .add(registry.isGameRespected(address)) + .add(game.status()) + .add(game.rootClaim()) + .add(game.l2SequenceNumber()) + .aggregate() + .await + .map_err(|error| { + LineageError::Contract(format!("read recovery parent {address}: {error}")) + })?; + Ok(RecoveryParent { + anchor: LineageAnchor { + address, + l2_block_number: block_number.try_into().map_err(|_| { + LineageError::Contract(format!( + "recovery parent {address} block number overflows u64" + )) + })?, + }, + root_claim, + eligible: proper && respected && GameStatus::try_from(status)? == GameStatus::DefenderWins, + }) +} + /// Reads the current game-or-registry anchor sentinel. pub async fn read_lineage_anchor

( provider: &P, @@ -246,20 +329,7 @@ pub async fn read_registered_lineage_config

( where P: Provider + Clone, { - let implementation_address = factory - .gameImpls(MULTI_PROOF_GAME_TYPE) - .call() - .await - .map_err(|error| LineageError::Contract(error.to_string()))?; - if implementation_address == Address::ZERO { - return Err(LineageError::Contract(format!( - "dispute-game factory {} has no implementation for game type {MULTI_PROOF_GAME_TYPE}", - factory.address() - ))); - } - - let implementation = - IMultiProofGame::IMultiProofGameInstance::new(implementation_address, provider.clone()); + let implementation = read_registered_game_implementation(provider, factory).await?; let (domain_hash, anchor_registry, block_interval) = provider .multicall() .add(implementation.domainHash()) @@ -287,6 +357,52 @@ where }) } +/// Discovers the singleton bond vault from the factory's registered WIP-1006 implementation. +pub async fn read_registered_bond_vault

( + provider: &P, + factory: &IDisputeGameFactory::IDisputeGameFactoryInstance

, +) -> Result +where + P: Provider + Clone, +{ + let implementation = read_registered_game_implementation(provider, factory).await?; + let bond_vault = implementation + .bondVault() + .call() + .await + .map_err(|error| LineageError::Contract(error.to_string()))?; + if bond_vault == Address::ZERO { + return Err(LineageError::Contract( + "registered game implementation has no bond vault".into(), + )); + } + Ok(bond_vault) +} + +async fn read_registered_game_implementation

( + provider: &P, + factory: &IDisputeGameFactory::IDisputeGameFactoryInstance

, +) -> Result, LineageError> +where + P: Provider + Clone, +{ + let implementation_address = factory + .gameImpls(MULTI_PROOF_GAME_TYPE) + .call() + .await + .map_err(|error| LineageError::Contract(error.to_string()))?; + if implementation_address == Address::ZERO { + return Err(LineageError::Contract(format!( + "dispute-game factory {} has no implementation for game type {MULTI_PROOF_GAME_TYPE}", + factory.address() + ))); + } + Ok(IMultiProofGame::IMultiProofGameInstance::new( + implementation_address, + provider.clone(), + )) +} + /// Looks up the highest sequential retry attempt for a transition. pub async fn read_game_for_transition

( factory: &IDisputeGameFactory::IDisputeGameFactoryInstance

, @@ -324,20 +440,69 @@ where Ok(latest) } -/// Reads and decodes a game's current resolution evaluation. +/// Returns whether the factory contains the next attempt for this exact transition. +/// Attempts are sequential, so finding the immediate successor establishes supersession. +pub async fn read_game_has_retry

( + factory: &IDisputeGameFactory::IDisputeGameFactoryInstance

, + game: &IMultiProofGame::IMultiProofGameInstance

, +) -> Result +where + P: Provider + Clone, +{ + let (domain, block_number, parent, attempt, root) = game + .provider() + .multicall() + .add(game.proposalDomainHash()) + .add(game.l2SequenceNumber()) + .add(game.parentRef()) + .add(game.attempt()) + .add(game.rootClaim()) + .aggregate() + .await + .map_err(|error| { + LineageError::Contract(format!( + "read retry context for {}: {error}", + game.address() + )) + })?; + let Some(next_attempt) = attempt.checked_add(U256::from(1)) else { + return Ok(false); + }; + let extra_data = (domain, block_number, parent, next_attempt).abi_encode(); + let entry = factory + .games(MULTI_PROOF_GAME_TYPE, root, extra_data.into()) + .call() + .await + .map_err(|error| { + LineageError::Contract(format!("look up retry for {}: {error}", game.address())) + })?; + Ok(entry.proxy != Address::ZERO) +} + +/// Reads the stored status and resolution evaluation atomically so resolution between +/// separate RPC calls cannot produce an inconsistent snapshot. pub async fn read_lineage_resolution_status

( game: &IMultiProofGame::IMultiProofGameInstance

, ) -> Result where P: Provider + Clone, { - let result = game - .resolutionStatus() - .call() + let (status, result) = game + .provider() + .multicall() + .add(game.status()) + .add(game.resolutionStatus()) + .aggregate() .await - .map_err(|error| LineageError::Contract(error.to_string()))?; + .map_err(|error| { + LineageError::Contract(format!( + "read resolution status for {}: {error}", + game.address() + )) + })?; Ok(ResolutionStatus { + status: status.try_into()?, resolvable: result.resolvable, outcome: result.outcome.try_into()?, invalidation_reason: result.reason.try_into()?, diff --git a/proofs/protocol/src/types.rs b/proofs/protocol/src/types.rs index 237784541..06768e494 100644 --- a/proofs/protocol/src/types.rs +++ b/proofs/protocol/src/types.rs @@ -85,6 +85,16 @@ pub enum ProposalStatus { } impl ProposalStatus { + /// Whether the contract has accepted enough proof lanes for the current proposal state. + /// A later challenge can reset this, requiring additional support. + #[must_use] + pub const fn has_sufficient_proof_support(self) -> bool { + matches!( + self, + Self::UnchallengedAndValidProofProvided | Self::ChallengedAndValidProofProvided + ) + } + /// Whether a challenger can still dispute this proposal. /// /// A proven proposal stays challengeable until its window closes: an accepted lane only @@ -318,12 +328,17 @@ impl TryFrom for InvalidationReason { } } -/// Decoded `MultiProofGame.resolutionStatus()`: what a resolve call would do right now. +/// A game's stored status and its current resolution evaluation, read at the same block. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct ResolutionStatus { + /// Actual on-chain `status()`, which only becomes terminal after `resolve()` succeeds. + pub status: GameStatus, + /// Whether `resolve()` can succeed now. pub resolvable: bool, - /// The outcome a resolve call would produce, or the outcome already reached. + /// Predicted or resolved outcome. A local proof timeout can be terminal while the + /// stored status is still `InProgress` and resolution is waiting for the parent. pub outcome: GameStatus, + /// Current invalidation reason; a local timeout may later become `InvalidParent`. pub invalidation_reason: InvalidationReason, } @@ -342,10 +357,9 @@ impl ResolutionStatus { /// Returns whether the game has already reached a terminal state. /// - /// `outcome` describes the expected result while a game is still resolvable, so a terminal - /// outcome only means resolved once `resolvable` is false. + /// Neither the predicted outcome nor `resolvable` establishes actual resolution. pub fn is_resolved(&self) -> bool { - !self.resolvable && self.outcome != GameStatus::InProgress + self.status != GameStatus::InProgress } } @@ -419,6 +433,7 @@ mod tests { #[test] fn resolution_status_reads_outcomes_not_proposal_states() { let finalized = ResolutionStatus { + status: GameStatus::InProgress, resolvable: true, outcome: GameStatus::DefenderWins, invalidation_reason: InvalidationReason::None, @@ -427,6 +442,7 @@ mod tests { assert!(!finalized.is_resolved()); let live = ResolutionStatus { + status: GameStatus::InProgress, resolvable: false, outcome: GameStatus::InProgress, invalidation_reason: InvalidationReason::None, @@ -435,6 +451,7 @@ mod tests { assert!(!live.is_resolved()); let bad_parent = ResolutionStatus { + status: GameStatus::InProgress, resolvable: true, outcome: GameStatus::ChallengerWins, invalidation_reason: InvalidationReason::InvalidParent, @@ -442,6 +459,37 @@ mod tests { assert!(bad_parent.invalid_parent_resolvable()); } + #[test] + fn local_timeout_is_not_resolved_until_the_stored_status_changes() { + let waiting = ResolutionStatus { + status: GameStatus::InProgress, + resolvable: false, + outcome: GameStatus::ChallengerWins, + invalidation_reason: InvalidationReason::ProofTimeout, + }; + assert!(!waiting.is_resolved()); + assert!(!waiting.positive_resolvable()); + assert!(!waiting.invalid_parent_resolvable()); + + let ready = ResolutionStatus { + resolvable: true, + ..waiting + }; + assert!(!ready.is_resolved()); + let resolved = ResolutionStatus { + status: GameStatus::ChallengerWins, + ..waiting + }; + assert!(resolved.is_resolved()); + let defender_wins = ResolutionStatus { + status: GameStatus::DefenderWins, + outcome: GameStatus::DefenderWins, + invalidation_reason: InvalidationReason::None, + ..waiting + }; + assert!(defender_wins.is_resolved()); + } + #[test] fn compact_proof_matches_lib_proof_header_layout() { let recipient = address!("00000000000000000000000000000000000000aa"); diff --git a/proofs/services/challenger/Cargo.toml b/proofs/services/challenger/Cargo.toml index 035f5999b..1b535b39e 100644 --- a/proofs/services/challenger/Cargo.toml +++ b/proofs/services/challenger/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "world-chain-challenger" -version = "1.0.0-rc.1" +version = "1.0.0-rc.5" edition.workspace = true rust-version.workspace = true license.workspace = true diff --git a/proofs/services/challenger/src/alloy.rs b/proofs/services/challenger/src/alloy.rs index ec3cfef13..1b06980fd 100644 --- a/proofs/services/challenger/src/alloy.rs +++ b/proofs/services/challenger/src/alloy.rs @@ -1,21 +1,19 @@ use crate::{ error::ChallengerError, traits::{BondManagerClient, ChallengerClient, ResolutionManagerClient}, - types::{ - ChallengeSubmission, ClaimSubmission, GameMetadata, PendingWithdrawal, ResolveSubmission, - }, + types::{ChallengeSubmission, CloseGameSubmission, GameMetadata, ResolveSubmission}, }; -use alloy_consensus::BlockHeader; -use alloy_eips::BlockNumberOrTag; use alloy_primitives::{Address, U256}; use alloy_provider::{Provider, WalletProvider}; use alloy_rpc_types_eth::BlockId; use async_trait::async_trait; use std::{sync::Arc, time::Duration}; use tokio::sync::Semaphore; +use tracing::warn; use world_chain_proof_protocol::{ - IAnchorStateRegistry, IDelayedWETH, IDisputeGameFactory, IMultiProofGame, - MULTI_PROOF_GAME_TYPE, ProposalStatus, ResolutionStatus, + IAnchorStateRegistry, IDisputeGameFactory, IERC20StakingVault, IMultiProofGame, + MULTI_PROOF_GAME_TYPE, ProposalStatus, ResolutionStatus, read_lineage_resolution_status, + read_registered_bond_vault, read_registered_lineage_config, }; /// Alloy-backed implementation of the challenger contract clients. @@ -25,6 +23,7 @@ use world_chain_proof_protocol::{ #[derive(Debug, Clone)] pub struct AlloyChallengerClient

{ factory: IDisputeGameFactory::IDisputeGameFactoryInstance

, + bond_vault: IERC20StakingVault::IERC20StakingVaultInstance

, confirmations: u64, receipt_timeout: Duration, semaphore: Arc, @@ -36,30 +35,76 @@ where P: Provider + Clone, { /// Creates an Alloy-backed contract client. - pub fn new( + pub async fn new( provider: P, factory_address: Address, confirmations: u64, receipt_timeout: Duration, - ) -> Self { + ) -> Result { let factory = IDisputeGameFactory::IDisputeGameFactoryInstance::new( factory_address, provider.clone(), ); + read_registered_lineage_config(&provider, &factory).await?; + let bond_vault = read_registered_bond_vault(&provider, &factory).await?; + let init_bond = factory.initBonds(MULTI_PROOF_GAME_TYPE).call().await?; + if !init_bond.is_zero() { + return Err(ChallengerError::NonZeroFactoryBond(init_bond)); + } + let vault = + IERC20StakingVault::IERC20StakingVaultInstance::new(bond_vault, provider.clone()); + let configured_factory = vault.disputeGameFactory().call().await?; + if configured_factory != factory_address { + return Err(ChallengerError::VaultFactoryMismatch { + vault: bond_vault, + expected: factory_address, + actual: configured_factory, + }); + } let semaphore = Arc::new(Semaphore::new(1)); - Self { + Ok(Self { factory, + bond_vault: vault, confirmations, receipt_timeout, semaphore, provider, - } + }) } fn game(&self, address: Address) -> IMultiProofGame::IMultiProofGameInstance

{ IMultiProofGame::IMultiProofGameInstance::new(address, self.provider.clone()) } + /// Refreshes the managed challenger's reusable bond-token balance metric. + pub async fn refresh_vault_balance(&self) + where + P: WalletProvider, + { + self.refresh_vault_balance_for(self.provider.default_signer_address()) + .await; + } + + /// Returns the singleton ERC-20 vault discovered from the active implementation. + #[must_use] + pub fn bond_vault_address(&self) -> Address { + *self.bond_vault.address() + } + + async fn refresh_vault_balance_for(&self, account: Address) { + match self.bond_vault.availableBalance(account).call().await { + Ok(balance) => world_chain_proof_metrics::record_vault_balance( + self.bond_vault_address(), + account, + "challenger", + balance, + ), + Err(error) => { + warn!(%error, %account, "failed to fetch challenger ERC-20 vault balance") + } + } + } + async fn read_game_count(&self) -> Result { let count = self .factory @@ -86,47 +131,9 @@ where &self, address: Address, ) -> Result { - let result = self.game(address).resolutionStatus().call().await?; - Ok(ResolutionStatus { - resolvable: result.resolvable, - outcome: result.outcome.try_into()?, - invalidation_reason: result.reason.try_into()?, - }) - } - - async fn read_credit( - &self, - address: Address, - recipient: Address, - ) -> Result { - Ok(self.game(address).credit(recipient).call().await?) - } - - async fn read_pending_withdrawal( - &self, - address: Address, - recipient: Address, - ) -> Result { - let weth_address = self.game(address).weth().call().await?; - let weth = IDelayedWETH::IDelayedWETHInstance::new(weth_address, self.provider.clone()); - - let (pending, delay) = tokio::try_join!( - async { weth.withdrawals(address, recipient).call().await }, - async { weth.delay().call().await }, - )?; - - if pending.amount.is_zero() { - return Ok(PendingWithdrawal::default()); - } - let unlock_at = pending - .timestamp - .checked_add(delay) - .ok_or(ChallengerError::Overflow)?; - - Ok(PendingWithdrawal { - amount: pending.amount, - unlock_at: u256_to_u64(unlock_at)?, - }) + read_lineage_resolution_status(&self.game(address)) + .await + .map_err(Into::into) } } @@ -171,13 +178,11 @@ where address: Address, ) -> Result { let _permit = self.semaphore.acquire().await?; - // The bond is an immutable of whichever implementation this clone was created from, so - // it is read per game: a re-registered implementation would otherwise make every - // challenge revert with `IncorrectBondAmount`. + // Read the game-pinned amount so the submission and telemetry report the actual lock. let game = self.game(address); let challenger_bond = game.challengerBond().call().await?; - let pending = game.challenge().value(challenger_bond).send().await?; + let pending = game.challenge().send().await?; let tx_hash = *pending.tx_hash(); let receipt = pending .with_required_confirmations(self.confirmations) @@ -188,7 +193,8 @@ where if !receipt.status() { return Err(ChallengerError::Revert(tx_hash)); } - world_chain_proof_metrics::record_bond_posted("challenger", challenger_bond); + world_chain_proof_metrics::record_bond_locked("challenger", challenger_bond); + self.refresh_vault_balance_for(receipt.from).await; Ok(ChallengeSubmission { tx_hash, bond: challenger_bond, @@ -253,39 +259,13 @@ where Ok(anchor.isGameFinalized(address).call().await?) } - async fn credit(&self, address: Address) -> Result { - self.read_credit(address, self.challenger_address()).await + async fn is_game_settled(&self, address: Address) -> Result { + Ok(self.bond_vault.gameBonds(address).call().await?.settled) } - async fn pending_withdrawal( - &self, - address: Address, - ) -> Result { - self.read_pending_withdrawal(address, self.challenger_address()) - .await - } - - async fn latest_l1_timestamp(&self) -> Result { - self.provider - .get_block_by_number(BlockNumberOrTag::Latest) - .await? - .map(|block| block.header.timestamp()) - .ok_or(ChallengerError::UnavailableLatestL1Block) - } - - async fn claim_credit(&self, address: Address) -> Result { + async fn close_game(&self, address: Address) -> Result { let _permit = self.semaphore.acquire().await?; - let recipient = self.challenger_address(); - // Read both phases up front so the submission can report what the call moved; the - // receipt carries no amount of its own. - let credit = self.read_credit(address, recipient).await?; - let pending = if credit.is_zero() { - self.read_pending_withdrawal(address, recipient).await? - } else { - PendingWithdrawal::default() - }; - - let pending_tx = self.game(address).claimCredit(recipient).send().await?; + let pending_tx = self.game(address).closeGame().send().await?; let tx_hash = *pending_tx.tx_hash(); let receipt = pending_tx .with_required_confirmations(self.confirmations) @@ -298,20 +278,9 @@ where return Err(ChallengerError::Revert(tx_hash)); } - Ok(if credit.is_zero() { - world_chain_proof_metrics::record_bond_withdrawn("challenger", pending.amount); - ClaimSubmission { - tx_hash, - amount: pending.amount, - withdrawn: true, - } - } else { - ClaimSubmission { - tx_hash, - amount: credit, - withdrawn: false, - } - }) + self.refresh_vault_balance_for(receipt.from).await; + + Ok(CloseGameSubmission { tx_hash }) } } diff --git a/proofs/services/challenger/src/bond_manager.rs b/proofs/services/challenger/src/bond_manager.rs index 30e1af2b4..a2fd6eafc 100644 --- a/proofs/services/challenger/src/bond_manager.rs +++ b/proofs/services/challenger/src/bond_manager.rs @@ -1,9 +1,8 @@ -use alloy_primitives::U256; use tracing::{info, warn}; use crate::{BondManagerClient, BondManagerConfig, ChallengerError, OwnedGames}; -/// Discovers challenger-owned games and withdraws their resolved bond credits. +/// Discovers challenger-owned games and settles their resolved bond pots. #[derive(Debug)] pub struct BondManager { config: BondManagerConfig, @@ -13,7 +12,7 @@ pub struct BondManager { } impl BondManager { - /// Creates an empty bond manager. Its bounded recovery window is scanned on the first pass. + /// Creates an empty bond manager. Its bounded lookback window is scanned on the first pass. pub const fn new( config: BondManagerConfig, execution_provider: E, @@ -75,55 +74,33 @@ where Ok(()) } - /// Advances the two-phase bond claim on owned games and prunes fully settled ones. - /// - /// `MultiProofGame.claimCredit` first unlocks the credit in `DelayedWETH` and only - /// transfers it on a second call after the WETH delay, so a game stays owned until its - /// pending withdrawal is drained. Dropping it after the unlock would strand the bond. - pub async fn withdraw_credits(&self) -> Result<(), ChallengerError> { + /// Settles finalized owned games and prunes games whose complete pot is settled. + pub async fn settle_games(&self) -> Result<(), ChallengerError> { let games = self.owned_games.snapshot(); - let now = self.execution_provider.latest_l1_timestamp().await?; for game in games { let result: Result = async { + if self.execution_provider.is_game_settled(game).await? { + world_chain_proof_metrics::increment_games_closed( + "challenger", + "already_settled", + ); + return Ok(true); + } let status = self.execution_provider.resolution_status(game).await?; if !status.is_resolved() { return Ok(false); } - // `claimCredit` calls `closeGame`, which reverts until the registry's finality - // airgap has elapsed. if !self.execution_provider.is_game_finalized(game).await? { return Ok(false); } - let credit = self.execution_provider.credit(game).await?; - if credit > U256::ZERO { - let submission = self.execution_provider.claim_credit(game).await?; - info!( - game_address = %game, - tx_hash = ?submission.tx_hash, - amount = ?submission.amount, - "unlocked challenger bond credits in DelayedWETH" - ); - // Keep tracking: the unlocked amount still needs the second claim. - return Ok(false); - } - - let pending = self.execution_provider.pending_withdrawal(game).await?; - if pending.amount.is_zero() { - // Nothing owed on this game; stop tracking it. - return Ok(true); - } - if now < pending.unlock_at { - return Ok(false); - } - - let submission = self.execution_provider.claim_credit(game).await?; + let submission = self.execution_provider.close_game(game).await?; + world_chain_proof_metrics::increment_games_closed("challenger", "submitted"); info!( game_address = %game, tx_hash = ?submission.tx_hash, - amount = ?submission.amount, - "withdrew challenger bond credits" + "settled challenger-owned game into reusable vault balances" ); Ok(true) } @@ -133,7 +110,7 @@ where Ok(true) => self.owned_games.remove(game), Ok(false) => {} Err(error) => { - warn!(%error, game_address = %game, "failed to process challenger bond credits"); + warn!(%error, game_address = %game, "failed to process challenger bond settlement"); } } } @@ -141,7 +118,7 @@ where Ok(()) } - /// Runs recent-game discovery and withdrawals forever. + /// Runs recent-game discovery and settlement forever. pub async fn run_forever(&mut self) -> Result<(), ChallengerError> { self.config.validate()?; @@ -151,8 +128,8 @@ where if let Err(error) = self.scan_games().await { warn!(%error, "bond-manager game scan failed; retrying on next tick"); } - if let Err(error) = self.withdraw_credits().await { - warn!(%error, "bond-manager withdrawal pass failed; retrying on next tick"); + if let Err(error) = self.settle_games().await { + warn!(%error, "bond-manager settlement pass failed; retrying on next tick"); } } } diff --git a/proofs/services/challenger/src/config.rs b/proofs/services/challenger/src/config.rs index a3066b394..f3cf3e1ae 100644 --- a/proofs/services/challenger/src/config.rs +++ b/proofs/services/challenger/src/config.rs @@ -13,7 +13,7 @@ pub const DEFAULT_GAME_SCAN_LOOKBACK: u64 = 100; pub const DEFAULT_RESOLUTION_POLL_INTERVAL: Duration = Duration::from_secs(30); /// Default maximum number of resolution transactions submitted per pass. pub const DEFAULT_MAX_RESOLUTIONS_PER_TICK: usize = 1; -/// Default delay between challenger-bond discovery and withdrawal passes. +/// Default delay between challenger-bond discovery and settlement passes. pub const DEFAULT_BOND_MANAGER_POLL_INTERVAL: Duration = Duration::from_secs(5 * 60); /// Default number of recent factory games inspected for challenger ownership. pub const DEFAULT_BOND_MANAGER_INITIAL_SCAN_LIMIT: u64 = 1_000; @@ -104,7 +104,7 @@ impl Default for ResolutionManagerConfig { /// Configuration for asynchronous challenger-bond management. #[derive(Debug, Clone)] pub struct BondManagerConfig { - /// Delay between factory scans and withdrawal attempts. + /// Delay between factory scans and settlement attempts. pub poll_interval: Duration, /// Number of most recently created games scanned on startup. pub initial_scan_limit: u64, diff --git a/proofs/services/challenger/src/error.rs b/proofs/services/challenger/src/error.rs index 3b695e98d..7e23bc617 100644 --- a/proofs/services/challenger/src/error.rs +++ b/proofs/services/challenger/src/error.rs @@ -1,4 +1,4 @@ -use alloy_primitives::{Address, TxHash}; +use alloy_primitives::{Address, TxHash, U256}; use alloy_provider::{PendingTransactionError, transport::RpcError}; use alloy_transport::TransportErrorKind; use thiserror::Error; @@ -13,6 +13,14 @@ pub enum ChallengerError { /// Invalid challenger configuration. #[error("invalid challenger config: {0}")] InvalidConfig(&'static str), + #[error("WIP-1006 factory init bond must be zero, got {0}")] + NonZeroFactoryBond(U256), + #[error("vault {vault} is wired to factory {actual}, expected {expected}")] + VaultFactoryMismatch { + vault: Address, + expected: Address, + actual: Address, + }, /// Adding `block_interval` overflowed `u64`. #[error("l2 block number overflow: parent {parent_block} + interval {block_interval}")] BlockNumberOverflow { @@ -36,8 +44,6 @@ pub enum ChallengerError { NotExistingInvalidReason(#[from] InvalidationReasonError), #[error(transparent)] PendingTransaction(#[from] PendingTransactionError), - #[error("Latest L1 block is unavailable.")] - UnavailableLatestL1Block, #[error("Overflow error.")] Overflow, #[error(transparent)] @@ -57,6 +63,8 @@ pub enum ChallengerError { }, #[error(transparent)] Permit(#[from] AcquireError), + #[error(transparent)] + Lineage(#[from] world_chain_proof_protocol::LineageError), } impl From for ChallengerError { diff --git a/proofs/services/challenger/src/lib.rs b/proofs/services/challenger/src/lib.rs index 97855c1d7..75c7ef1d2 100644 --- a/proofs/services/challenger/src/lib.rs +++ b/proofs/services/challenger/src/lib.rs @@ -23,8 +23,7 @@ pub use error::ChallengerError; pub use resolution_manager::ResolutionManager; pub use traits::{BondManagerClient, ChallengerClient, ResolutionManagerClient}; pub use types::{ - ChallengeSubmission, ClaimSubmission, GameMetadata, OwnedGames, PendingWithdrawal, - ResolveSubmission, + ChallengeSubmission, CloseGameSubmission, GameMetadata, OwnedGames, ResolveSubmission, }; #[cfg(test)] diff --git a/proofs/services/challenger/src/main.rs b/proofs/services/challenger/src/main.rs index c84fc563f..782acaaf6 100644 --- a/proofs/services/challenger/src/main.rs +++ b/proofs/services/challenger/src/main.rs @@ -19,6 +19,7 @@ use world_chain_challenger::{ DEFAULT_GAME_SCAN_LOOKBACK, DEFAULT_L1_TX_CONFIRMATIONS, OwnedGames, ResolutionManager, ResolutionManagerConfig, WorldChainChallenger, }; +use world_chain_proof_metrics::RPC_ENDPOINT_VERIFYING; use world_chain_proof_protocol::{OptimismConsensusClient, VerifyingConsensusProvider}; use world_chain_proof_tx_signer::build_transaction_signer; @@ -36,6 +37,10 @@ struct Cli { #[arg(long, env = "L1_RPC_URL")] l1_rpc: String, + /// Optional Ethereum L1 execution RPC URL used after the primary endpoint fails. + #[arg(long, env = "L1_FALLBACK_RPC_URL")] + l1_fallback_rpc: Option, + /// op-node rollup RPC URL used to read canonical L2 output roots. #[arg(long, env = "OUTPUT_ROOT_RPC_URL")] output_root_rpc: String, @@ -106,7 +111,7 @@ struct Cli { #[arg(long, env = "MAX_RESOLUTIONS_PER_TICK", default_value_t = 1)] max_resolutions_per_tick: usize, - /// Seconds between challenger-bond discovery and withdrawal passes. + /// Seconds between challenger-bond discovery and settlement passes. #[arg( long, env = "BOND_MANAGER_POLL_INTERVAL_SECONDS", @@ -144,8 +149,15 @@ async fn main() -> Result<()> { .context("failed to initialize challenger signer")? .wallet(); let challenger_address = wallet.default_signer().address(); + let l1_fallback_rpc_url = cli + .l1_fallback_rpc + .as_deref() + .map(Url::parse) + .transpose() + .context("invalid L1 fallback RPC URL")?; let l1_rpc_client = world_chain_proof_metrics::metered_http_client( l1_rpc_url, + l1_fallback_rpc_url, world_chain_proof_metrics::RPC_TARGET_L1_EXECUTION, Duration::from_secs(cli.l1_rpc_timeout_seconds), ) @@ -165,7 +177,10 @@ async fn main() -> Result<()> { cli.factory_address, cli.l1_tx_confirmations, Duration::from_secs(cli.l1_tx_receipt_timeout_seconds), - ); + ) + .await + .context("failed to bind the World Chain proof system")?; + client.refresh_vault_balance().await; // Preflight the factory index before entering the scan loop. Crash instead of reporting the // process alive while every scan tick fails. @@ -184,7 +199,7 @@ async fn main() -> Result<()> { OptimismConsensusClient::new(cli.output_root_rpc.clone()), cli.verifying_output_root_rpc .clone() - .map(OptimismConsensusClient::new), + .map(|url| OptimismConsensusClient::new(url).with_endpoint(RPC_ENDPOINT_VERIFYING)), ); let config = ChallengerConfig { poll_interval: Duration::from_secs(cli.poll_interval_seconds), @@ -200,6 +215,7 @@ async fn main() -> Result<()> { poll_interval: Duration::from_secs(cli.bond_manager_poll_interval_seconds), initial_scan_limit: cli.bond_manager_initial_scan_limit, }; + let bond_vault = client.bond_vault_address(); let owned_games = OwnedGames::default(); let mut challenger = WorldChainChallenger::with_owned_games( config, @@ -213,9 +229,11 @@ async fn main() -> Result<()> { info!( l1_rpc_url = world_chain_proof_metrics::redact_endpoint(&cli.l1_rpc), + l1_fallback_rpc_configured = cli.l1_fallback_rpc.is_some(), output_root_rpc_url = world_chain_proof_metrics::redact_endpoint(&cli.output_root_rpc), verifying_output_root_rpc_configured = cli.verifying_output_root_rpc.is_some(), dispute_game_factory = %cli.factory_address, + bond_vault = %bond_vault, factory_game_count = game_count, challenger = %challenger_address, max_games_per_tick = cli.max_games_per_tick, diff --git a/proofs/services/challenger/src/tests.rs b/proofs/services/challenger/src/tests.rs index 544119412..048d7e618 100644 --- a/proofs/services/challenger/src/tests.rs +++ b/proofs/services/challenger/src/tests.rs @@ -1,8 +1,8 @@ use crate::{ BondManager, BondManagerClient, BondManagerConfig, ChallengeSubmission, ChallengerClient, - ChallengerConfig, ChallengerError, ClaimSubmission, GameMetadata, OwnedGames, - PendingWithdrawal, ResolutionManager, ResolutionManagerClient, ResolutionManagerConfig, - ResolveSubmission, challenger::WorldChainChallenger, + ChallengerConfig, ChallengerError, CloseGameSubmission, GameMetadata, OwnedGames, + ResolutionManager, ResolutionManagerClient, ResolutionManagerConfig, ResolveSubmission, + challenger::WorldChainChallenger, }; use alloy_primitives::{Address, B256, BlockNumber, U256, address}; use async_trait::async_trait; @@ -37,8 +37,7 @@ struct MockGame { resolvable: bool, resolution_outcome: GameStatus, resolution_reason: u8, - credit: U256, - pending: PendingWithdrawal, + settled: bool, /// Whether the registry's finality airgap has elapsed for this game. finalized: bool, } @@ -57,11 +56,7 @@ impl MockGame { resolvable: false, resolution_outcome: GameStatus::InProgress, resolution_reason: REASON_NONE, - credit: U256::ZERO, - pending: PendingWithdrawal { - amount: U256::ZERO, - unlock_at: 0, - }, + settled: false, finalized: true, } } @@ -74,10 +69,8 @@ struct MockState { requested_indices: Vec, challenges: Vec

, resolutions: Vec
, - unlocks: Vec
, - withdrawals: Vec
, - fail_claim_once: HashSet
, - latest_l1_timestamp: u64, + closes: Vec
, + fail_close_once: HashSet
, /// Factory indices holding a game of a different type. foreign_indices: HashSet, } @@ -111,8 +104,8 @@ impl MockClient { self.state.lock().expect("not poisoned").resolutions.clone() } - fn withdrawals(&self) -> Vec
{ - self.state.lock().expect("not poisoned").withdrawals.clone() + fn closes(&self) -> Vec
{ + self.state.lock().expect("not poisoned").closes.clone() } } @@ -198,6 +191,11 @@ impl ResolutionManagerClient for MockClient { .copied() .ok_or_else(|| ChallengerError::message(format!("unknown game {game}")))?; Ok(ResolutionStatus { + status: if record.proposal_status == ProposalStatus::Resolved { + record.resolution_outcome + } else { + GameStatus::InProgress + }, resolvable: record.resolvable, outcome: record.resolution_outcome, invalidation_reason: InvalidationReason::try_from(record.resolution_reason)?, @@ -253,67 +251,29 @@ impl BondManagerClient for MockClient { .ok_or_else(|| ChallengerError::message(format!("unknown game {game}"))) } - async fn credit(&self, game: Address) -> Result { - self.state - .lock() - .expect("not poisoned") - .games - .get(&game) - .map(|game| game.credit) - .ok_or_else(|| ChallengerError::message(format!("unknown game {game}"))) - } - - async fn pending_withdrawal( - &self, - game: Address, - ) -> Result { + async fn is_game_settled(&self, game: Address) -> Result { self.state .lock() .expect("not poisoned") .games .get(&game) - .map(|game| game.pending) + .map(|game| game.settled) .ok_or_else(|| ChallengerError::message(format!("unknown game {game}"))) } - async fn latest_l1_timestamp(&self) -> Result { - Ok(self.state.lock().expect("not poisoned").latest_l1_timestamp) - } - - /// Mirrors `MultiProofGame.claimCredit`: the first call unlocks credit into a pending - /// `DelayedWETH` withdrawal, the second drains it. - async fn claim_credit(&self, game: Address) -> Result { + async fn close_game(&self, game: Address) -> Result { let mut state = self.state.lock().expect("not poisoned"); - if state.fail_claim_once.remove(&game) { - return Err(ChallengerError::message("injected claim failure")); + if state.fail_close_once.remove(&game) { + return Err(ChallengerError::message("injected close failure")); } let record = state .games .get_mut(&game) .ok_or_else(|| ChallengerError::message(format!("unknown game {game}")))?; - - if record.credit > U256::ZERO { - let amount = record.credit; - record.credit = U256::ZERO; - record.pending = PendingWithdrawal { - amount, - unlock_at: 0, - }; - state.unlocks.push(game); - return Ok(ClaimSubmission { - tx_hash: B256::with_last_byte(state.unlocks.len() as u8), - amount, - withdrawn: false, - }); - } - - let amount = record.pending.amount; - record.pending = PendingWithdrawal::default(); - state.withdrawals.push(game); - Ok(ClaimSubmission { - tx_hash: B256::with_last_byte(state.withdrawals.len() as u8), - amount, - withdrawn: true, + record.settled = true; + state.closes.push(game); + Ok(CloseGameSubmission { + tx_hash: B256::with_last_byte(state.closes.len() as u8), }) } } @@ -591,22 +551,21 @@ async fn bond_manager_scans_games_appended_after_recovery() { } #[tokio::test] -async fn bond_manager_completes_two_phase_claim_and_prunes_terminal_games() { - let mut claimable = MockGame::proposed(GAME_1, B256::ZERO, L2_BLOCK); - claimable.proposal_status = ProposalStatus::Resolved; - claimable.resolution_outcome = GameStatus::ChallengerWins; - claimable.resolution_reason = REASON_PROOF_TIMEOUT; - claimable.credit = U256::from(10); - let mut zero_credit = MockGame::proposed(GAME_2, B256::ZERO, L2_BLOCK); - zero_credit.proposal_status = ProposalStatus::Resolved; - zero_credit.resolution_outcome = GameStatus::DefenderWins; +async fn bond_manager_settles_finalized_games_and_prunes_terminal_games() { + let mut closable = MockGame::proposed(GAME_1, B256::ZERO, L2_BLOCK); + closable.proposal_status = ProposalStatus::Resolved; + closable.resolution_outcome = GameStatus::ChallengerWins; + closable.resolution_reason = REASON_PROOF_TIMEOUT; + let mut already_settled = MockGame::proposed(GAME_2, B256::ZERO, L2_BLOCK); + already_settled.proposal_status = ProposalStatus::Resolved; + already_settled.resolution_outcome = GameStatus::DefenderWins; + already_settled.settled = true; // Resolved but still inside the registry's finality airgap: `closeGame` would revert. let mut awaiting_airgap = MockGame::proposed(GAME_3, B256::ZERO, L2_BLOCK); awaiting_airgap.proposal_status = ProposalStatus::Resolved; awaiting_airgap.resolution_outcome = GameStatus::DefenderWins; - awaiting_airgap.credit = U256::from(5); awaiting_airgap.finalized = false; - let client = MockClient::new(vec![claimable, zero_credit, awaiting_airgap]); + let client = MockClient::new(vec![closable, already_settled, awaiting_airgap]); let owned_games = OwnedGames::default(); owned_games.insert(GAME_1); owned_games.insert(GAME_2); @@ -617,40 +576,29 @@ async fn bond_manager_completes_two_phase_claim_and_prunes_terminal_games() { owned_games.clone(), ); - // Pass 1 unlocks the credit in DelayedWETH; the bond is not paid out yet. - manager.withdraw_credits().await.unwrap(); + manager.settle_games().await.unwrap(); - assert!(client.withdrawals().is_empty()); - assert!( - owned_games.contains(GAME_1), - "an unlocked bond must stay owned until it is withdrawn" - ); + assert_eq!(client.closes(), vec![GAME_1]); + assert!(!owned_games.contains(GAME_1)); assert!(!owned_games.contains(GAME_2)); assert!( owned_games.contains(GAME_3), "a game inside the finality airgap must stay owned" ); - - // Pass 2 drains the pending withdrawal and drops the game. - manager.withdraw_credits().await.unwrap(); - - assert_eq!(client.withdrawals(), vec![GAME_1]); - assert!(!owned_games.contains(GAME_1)); } #[tokio::test] -async fn bond_manager_retries_failed_claim() { +async fn bond_manager_retries_failed_close() { let mut game = MockGame::proposed(GAME_1, B256::ZERO, L2_BLOCK); game.proposal_status = ProposalStatus::Resolved; game.resolution_outcome = GameStatus::ChallengerWins; game.resolution_reason = REASON_PROOF_TIMEOUT; - game.credit = U256::from(10); let client = MockClient::new(vec![game]); client .state .lock() .expect("not poisoned") - .fail_claim_once + .fail_close_once .insert(GAME_1); let owned_games = OwnedGames::default(); owned_games.insert(GAME_1); @@ -660,32 +608,21 @@ async fn bond_manager_retries_failed_claim() { owned_games.clone(), ); - // Injected failure on the unlock, then unlock, then withdraw. - for _ in 0..2 { - manager.withdraw_credits().await.unwrap(); - assert!(owned_games.contains(GAME_1)); - } + manager.settle_games().await.unwrap(); + assert!(owned_games.contains(GAME_1)); - manager.withdraw_credits().await.unwrap(); + manager.settle_games().await.unwrap(); assert!(!owned_games.contains(GAME_1)); - assert_eq!(client.withdrawals(), vec![GAME_1]); + assert_eq!(client.closes(), vec![GAME_1]); } #[tokio::test] -async fn bond_manager_uses_l1_timestamp_for_delayed_withdrawal() { +async fn bond_manager_prunes_already_settled_game_without_closing_again() { let mut game = MockGame::proposed(GAME_1, B256::ZERO, L2_BLOCK); game.proposal_status = ProposalStatus::Resolved; game.resolution_outcome = GameStatus::DefenderWins; - game.pending = PendingWithdrawal { - amount: U256::from(10), - unlock_at: 100, - }; + game.settled = true; let client = MockClient::new(vec![game]); - client - .state - .lock() - .expect("not poisoned") - .latest_l1_timestamp = 99; let owned_games = OwnedGames::default(); owned_games.insert(GAME_1); let manager = BondManager::new( @@ -694,18 +631,9 @@ async fn bond_manager_uses_l1_timestamp_for_delayed_withdrawal() { owned_games.clone(), ); - manager.withdraw_credits().await.unwrap(); - assert!(owned_games.contains(GAME_1)); - assert!(client.withdrawals().is_empty()); - - client - .state - .lock() - .expect("not poisoned") - .latest_l1_timestamp = 100; - manager.withdraw_credits().await.unwrap(); + manager.settle_games().await.unwrap(); assert!(!owned_games.contains(GAME_1)); - assert_eq!(client.withdrawals(), vec![GAME_1]); + assert!(client.closes().is_empty()); } #[tokio::test] diff --git a/proofs/services/challenger/src/traits.rs b/proofs/services/challenger/src/traits.rs index 40abe0ec7..c5db6eebe 100644 --- a/proofs/services/challenger/src/traits.rs +++ b/proofs/services/challenger/src/traits.rs @@ -1,10 +1,8 @@ use crate::{ ChallengerError, - types::{ - ChallengeSubmission, ClaimSubmission, GameMetadata, PendingWithdrawal, ResolveSubmission, - }, + types::{ChallengeSubmission, CloseGameSubmission, GameMetadata, ResolveSubmission}, }; -use alloy_primitives::{Address, U256}; +use alloy_primitives::Address; use async_trait::async_trait; use world_chain_proof_protocol::{ProposalStatus, ResolutionStatus}; @@ -52,16 +50,9 @@ pub trait BondManagerClient: ResolutionManagerClient { /// Returns the challenger recorded by the provided game. async fn game_challenger(&self, game: Address) -> Result; /// Returns whether the registry's finality airgap has elapsed for the provided game. - /// - /// `claimCredit` calls `closeGame`, which reverts until this holds. async fn is_game_finalized(&self, game: Address) -> Result; - /// Returns the credit the managed challenger can unlock from the provided game. - async fn credit(&self, game: Address) -> Result; - /// Returns the managed challenger's pending `DelayedWETH` withdrawal for the game. - async fn pending_withdrawal(&self, game: Address) - -> Result; - /// Returns the latest L1 block timestamp used by `DelayedWETH`. - async fn latest_l1_timestamp(&self) -> Result; - /// Advances the managed challenger's two-phase bond claim on the provided game. - async fn claim_credit(&self, game: Address) -> Result; + /// Returns whether the game's complete bond pot has already been settled. + async fn is_game_settled(&self, game: Address) -> Result; + /// Settles the game's complete bond pot into reusable vault balances. + async fn close_game(&self, game: Address) -> Result; } diff --git a/proofs/services/challenger/src/types.rs b/proofs/services/challenger/src/types.rs index 6212bb188..09d5f407f 100644 --- a/proofs/services/challenger/src/types.rs +++ b/proofs/services/challenger/src/types.rs @@ -18,7 +18,7 @@ pub struct GameMetadata { pub struct ChallengeSubmission { /// Transaction hash for the challenge submission. pub tx_hash: TxHash, - /// Bond posted with the challenge, read from the game itself. + /// ERC-20 bond locked by the challenge, read from the game itself. pub bond: U256, } @@ -29,27 +29,11 @@ pub struct ResolveSubmission { pub tx_hash: TxHash, } -/// Result of a `claimCredit` transaction. -/// -/// Bond payout is two-phase: the first call unlocks the credit in `DelayedWETH`, the second -/// (after the WETH delay) withdraws and transfers it. +/// Result of a closeGame transaction. #[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct ClaimSubmission { - /// Transaction hash for the claim. +pub struct CloseGameSubmission { + /// Transaction hash for the closeGame submission. pub tx_hash: TxHash, - /// Amount moved by this phase. - pub amount: U256, - /// Whether this call finalized the withdrawal and transferred funds. - pub withdrawn: bool, -} - -/// A pending `DelayedWETH` withdrawal opened by the first `claimCredit` call. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] -pub struct PendingWithdrawal { - /// Amount unlocked in `DelayedWETH` and awaiting the withdrawal delay. - pub amount: U256, - /// Unix timestamp at which the unlocked amount becomes withdrawable. - pub unlock_at: u64, } /// Challenger-owned games shared by scanning, resolution, and bond-management loops. diff --git a/proofs/services/defender/Cargo.toml b/proofs/services/defender/Cargo.toml index e3e9e26c7..ac86fbf9e 100644 --- a/proofs/services/defender/Cargo.toml +++ b/proofs/services/defender/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "world-chain-defender" -version = "1.0.0-rc.1" +version = "1.0.0-rc.5" edition.workspace = true rust-version.workspace = true license.workspace = true @@ -43,6 +43,9 @@ tracing.workspace = true telemetry-batteries.workspace = true url.workspace = true +[dev-dependencies] +tracing-subscriber.workspace = true + # Proofs release train: cargo-release bumps every shared-version member in lockstep. [package.metadata.release] shared-version = "proofs" diff --git a/proofs/services/defender/README.md b/proofs/services/defender/README.md index 208936413..f263a9314 100644 --- a/proofs/services/defender/README.md +++ b/proofs/services/defender/README.md @@ -13,3 +13,27 @@ Only asynchronous proof progress is retained between ticks. Each tick reconstruc drops proof workflows for games that are no longer selected. A proof-timeout retry therefore moves the defender to the replacement attempt. Descendants of the invalidated attempt need no further proof support: the proposer bond manager resolves them as `INVALID_PARENT` and claims their refunds. + +## Recovering from an unusable anchor + +Restart with the same `--recovery-parent

` (or `RECOVERY_PARENT=

`) as the proposer. +The defender then proves the replacement lineage selected from P in the active domain. +Both services validate P and its canonical finalized root, and resume normal selection once +the ASR has a claim-valid anchor above P. Remove the flag after recovery. +See the [proposer recovery procedure](../proposer/README.md#recovering-from-an-unusable-anchor) +for governance prerequisites and onchain limitations. `lineage.recovery_active` reports +whether recovery selection is active. + +## Private proof submission + +Set `L1_SUBMISSION_RPC_URL` to a private relay RPC for proof estimation and submission, +with no public fallback. Reads and receipt checks use the existing L1 RPCs. +If unset, submissions use the normal L1 RPC. + +Private submission mitigates reward theft. Residual relay/builder trust and reorg risks +are acknowledged and accepted. + +Already-proven lanes are skipped before submission. Subsequent failures emit +`proof_submission_failed` for investigation. Inclusion and confirmations each may block up to +`L1_TX_RECEIPT_TIMEOUT_SECONDS` (default 300); inclusion timeouts retry on the next tick. +`proof_submission.inclusion_seconds` measures time to first observed inclusion, excluding confirmations. diff --git a/proofs/services/defender/src/alloy.rs b/proofs/services/defender/src/alloy.rs index 90442e76c..f9901dab0 100644 --- a/proofs/services/defender/src/alloy.rs +++ b/proofs/services/defender/src/alloy.rs @@ -4,16 +4,20 @@ use crate::{ types::{DefenderSubmission, GameMetadata}, }; use alloy_primitives::{Address, Bytes, U256}; -use alloy_provider::Provider; -use alloy_sol_types::SolInterface; +use alloy_provider::{PendingTransactionBuilder, Provider}; use async_trait::async_trait; -use std::{sync::Arc, time::Duration}; +use std::{ + sync::Arc, + time::{Duration, Instant}, +}; use tokio::sync::Semaphore; +use tracing::warn; use world_chain_proof_protocol::{ ClaimData, IAnchorStateRegistry, IDisputeGameFactory, IMultiProofGame, LineageAnchor, LineageError, LineageGame, LineageProvider, LineageTransition, PROOF_LANE_COUNT, ProofLane, - RegisteredLineageConfig, ResolutionStatus, encode_compact_proof, read_game_for_transition, - read_lineage_anchor, read_lineage_resolution_status, read_registered_lineage_config, + RecoveryParent, RegisteredLineageConfig, ResolutionStatus, encode_compact_proof, + read_game_for_transition, read_lineage_anchor, read_lineage_resolution_status, + read_recovery_parent, read_registered_lineage_config, }; /// Alloy-backed implementation of [`DefenderClient`]. @@ -31,6 +35,7 @@ pub struct AlloyDefenderClient

{ reward_recipient: Address, semaphore: Arc, provider: P, + submission_provider: P, } impl

AlloyDefenderClient

@@ -64,10 +69,18 @@ where receipt_timeout, reward_recipient, semaphore, + submission_provider: provider.clone(), provider, }) } + /// Uses a separate provider for proof estimation and submission, without read-RPC fallback. + /// It must use the same chain and signer as the read provider. + pub fn with_submission_provider(mut self, provider: P) -> Self { + self.submission_provider = provider; + self + } + fn game(&self, address: Address) -> IMultiProofGame::IMultiProofGameInstance

{ IMultiProofGame::IMultiProofGameInstance::new(address, self.provider.clone()) } @@ -86,6 +99,20 @@ where read_lineage_anchor(&self.provider, &self.anchor).await } + async fn recovery_parent(&self, game: Address) -> Result { + read_recovery_parent(&self.provider, &self.anchor, game).await + } + + async fn lineage_anchor_claim_valid(&self, game: Address) -> Result { + self.anchor + .isGameClaimValid(game) + .call() + .await + .map_err(|error| { + LineageError::Contract(format!("read anchor eligibility for {game}: {error}")) + }) + } + async fn game_for_transition( &self, transition: LineageTransition, @@ -180,29 +207,48 @@ where proof: Bytes, ) -> Result { let _permit = self.semaphore.acquire().await?; + if self.game(game).claimData().call().await?.proofBitmap & lane.mask() != 0 { + return Err(DefenderError::LaneAlreadyProven { game, lane }); + } + let started = Instant::now(); let compact = encode_compact_proof(lane, self.reward_recipient, &proof); - let pending = self - .game(game) - .submitProofLane(compact) - .send() - .await - .map_err(|error| { - if is_duplicate_lane(&error) { - DefenderError::LaneAlreadyProven { game, lane } - } else { - error.into() - } - })?; + // Gas estimation also carries the proof, so it must use the submission provider. + let pending = + IMultiProofGame::IMultiProofGameInstance::new(game, self.submission_provider.clone()) + .submitProofLane(compact) + .send() + .await + .map_err(|error| { + warn!(lifecycle_event = "proof_submission_failed", game_address = %game, + ?lane, %error, "proof submission failed after an empty-lane check; possible competing proof or frontrun if the lane changed"); + DefenderError::from(error) + })?; let tx_hash = *pending.tx_hash(); - let receipt = pending - .with_required_confirmations(self.confirmations) - .with_timeout(Some(self.receipt_timeout)) - .get_receipt() - .await?; - world_chain_proof_metrics::refresh_wallet_balance(&self.provider, receipt.from).await; + let wait_for_receipt = |confirmations| { + PendingTransactionBuilder::new(self.provider.root().clone(), tx_hash) + .with_required_confirmations(confirmations) + .with_timeout(Some(self.receipt_timeout)) + .get_receipt() + }; + let warn_failure = |error| { + warn!(lifecycle_event = "proof_submission_failed", game_address = %game, + ?lane, %tx_hash, %error, + "proof confirmation failed; possible competing proof or frontrun, but timeout/RPC errors are inconclusive"); + error + }; + let mut receipt = wait_for_receipt(1) + .await + .map_err(|error| warn_failure(DefenderError::from(error)))?; + world_chain_proof_metrics::record_proof_submission_inclusion(started.elapsed()); + if self.confirmations > 1 { + receipt = wait_for_receipt(self.confirmations) + .await + .map_err(|error| warn_failure(DefenderError::from(error)))?; + } if !receipt.status() { - return Err(DefenderError::Revert(tx_hash)); + return Err(warn_failure(DefenderError::Revert(tx_hash))); } + world_chain_proof_metrics::refresh_wallet_balance(&self.provider, receipt.from).await; Ok(DefenderSubmission { tx_hash }) } } @@ -211,17 +257,207 @@ fn u256_to_u64(value: U256) -> Result { value.try_into().map_err(|_| DefenderError::Overflow) } -/// Whether the game rejected the submission because the lane already counts toward its threshold. -/// -/// `submitProofLane` reverts on a duplicate lane rather than no-opping, so a racing prover or a -/// retry of a submission that actually landed surfaces here instead of succeeding. -fn is_duplicate_lane(error: &alloy_contract::Error) -> bool { - error.as_revert_data().is_some_and(|data| { - matches!( - IMultiProofGame::IMultiProofGameErrors::abi_decode(&data), - Ok(IMultiProofGame::IMultiProofGameErrors::DuplicateProofLane( - _ - )) - ) - }) +#[cfg(test)] +mod tests { + use super::*; + use alloy_primitives::B256; + use alloy_provider::ProviderBuilder; + use alloy_sol_types::SolValue; + use alloy_transport::mock::Asserter; + + #[derive(Clone, Default)] + struct LogWriter(Arc>>); + + impl std::io::Write for LogWriter { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + self.0.lock().unwrap().extend_from_slice(bytes); + Ok(bytes.len()) + } + + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + + fn push_claim(reads: &Asserter, status: u8, bitmap: u8) { + reads.push_success(&Bytes::from( + ( + U256::from(status), + Address::ZERO, + U256::from(100), + U256::from(bitmap), + U256::ZERO, + ) + .abi_encode(), + )); + } + + #[tokio::test] + async fn already_proven_lane_skips_submission_without_warning() { + let logs = LogWriter::default(); + let writer = logs.clone(); + let subscriber = tracing_subscriber::fmt() + .without_time() + .with_ansi(false) + .with_writer(move || writer.clone()) + .finish(); + let _guard = tracing::subscriber::set_default(subscriber); + let reads = Asserter::new(); + let submissions = Asserter::new(); + let lane = ProofLane::TeeAttestation; + push_claim(&reads, 0, lane.mask()); + submissions.push_failure_msg("must not submit"); + let provider = |asserter| { + ProviderBuilder::new() + .disable_recommended_fillers() + .connect_mocked_client(asserter) + }; + let client = + client(provider(reads.clone())).with_submission_provider(provider(submissions.clone())); + assert!(matches!( + client.submit_proof(Address::ZERO, lane, Bytes::new()).await, + Err(DefenderError::LaneAlreadyProven { .. }) + )); + assert_eq!(submissions.read_q().len(), 1); + assert!(reads.read_q().is_empty()); + assert!(logs.0.lock().unwrap().is_empty()); + } + + fn client(provider: P) -> AlloyDefenderClient

{ + AlloyDefenderClient { + factory: IDisputeGameFactory::IDisputeGameFactoryInstance::new( + Address::ZERO, + provider.clone(), + ), + anchor: IAnchorStateRegistry::IAnchorStateRegistryInstance::new( + Address::ZERO, + provider.clone(), + ), + registered: RegisteredLineageConfig { + domain_hash: B256::ZERO, + block_interval: 1, + anchor_registry: Address::ZERO, + }, + confirmations: 1, + receipt_timeout: Duration::from_secs(1), + reward_recipient: Address::repeat_byte(1), + semaphore: Arc::new(Semaphore::new(1)), + submission_provider: provider.clone(), + provider, + } + } + + #[tokio::test] + async fn submission_failure_never_falls_back_to_read_provider() { + let reads = Asserter::new(); + push_claim(&reads, 0, 0); + reads.push_failure_msg("public RPC must not receive proof"); + let submissions = Asserter::new(); + submissions.push_failure_msg("private submission unavailable"); + let provider = |asserter| { + ProviderBuilder::new() + .disable_recommended_fillers() + .connect_mocked_client(asserter) + }; + let client = + client(provider(reads.clone())).with_submission_provider(provider(submissions.clone())); + + let error = client + .submit_proof(Address::ZERO, ProofLane::TeeAttestation, Bytes::new()) + .await + .unwrap_err(); + + assert!(error.to_string().contains("private submission unavailable")); + assert_eq!(reads.read_q().len(), 1); + assert!(submissions.read_q().is_empty()); + } + + #[tokio::test] + async fn gas_estimation_failure_never_uses_read_provider() { + let reads = Asserter::new(); + push_claim(&reads, 0, 0); + reads.push_failure_msg("public RPC must not receive proof"); + let submissions = Asserter::new(); + for _ in 0..4 { + submissions.push_failure_msg("private estimation unavailable"); + } + let provider = |asserter| { + ProviderBuilder::new() + .disable_recommended_fillers() + .with_gas_estimation() + .connect_mocked_client(asserter) + }; + let client = + client(provider(reads.clone())).with_submission_provider(provider(submissions)); + + let error = client + .submit_proof(Address::ZERO, ProofLane::TeeAttestation, Bytes::new()) + .await + .unwrap_err(); + + assert!(error.to_string().contains("private estimation unavailable")); + assert_eq!(reads.read_q().len(), 1); + } + + #[tokio::test] + async fn receipt_is_checked_on_read_provider_after_private_submission() { + let logs = LogWriter::default(); + let writer = logs.clone(); + let subscriber = tracing_subscriber::fmt() + .without_time() + .with_ansi(false) + .with_writer(move || writer.clone()) + .finish(); + let _guard = tracing::subscriber::set_default(subscriber); + let reads = Asserter::new(); + push_claim(&reads, 0, 0); + reads.push_failure_msg("read RPC receipt check"); + let submissions = Asserter::new(); + submissions.push_success(&B256::repeat_byte(2)); + let provider = |asserter| { + ProviderBuilder::new() + .disable_recommended_fillers() + .connect_mocked_client(asserter) + }; + let client = + client(provider(reads.clone())).with_submission_provider(provider(submissions.clone())); + + let error = client + .submit_proof(Address::ZERO, ProofLane::TeeAttestation, Bytes::new()) + .await + .unwrap_err(); + + assert!(error.to_string().contains("read RPC receipt check")); + let output = String::from_utf8(logs.0.lock().unwrap().clone()).unwrap(); + assert!(output.contains("proof_submission_failed")); + assert!(output.contains(&B256::repeat_byte(2).to_string())); + assert!(reads.read_q().is_empty()); + assert!(submissions.read_q().is_empty()); + } + + #[tokio::test] + async fn missing_receipt_waits_until_timeout_without_resubmitting() { + let reads = Asserter::new(); + push_claim(&reads, 0, 0); + for _ in 0..10 { + reads.push_success(&Option::::None); + } + let submissions = Asserter::new(); + submissions.push_success(&B256::repeat_byte(2)); + let provider = |asserter| { + ProviderBuilder::new() + .disable_recommended_fillers() + .connect_mocked_client(asserter) + }; + let client = + client(provider(reads)).with_submission_provider(provider(submissions.clone())); + let started = Instant::now(); + let error = client + .submit_proof(Address::ZERO, ProofLane::TeeAttestation, Bytes::new()) + .await + .unwrap_err(); + assert!(matches!(error, DefenderError::PendingTransaction(_))); + assert!(started.elapsed() >= client.receipt_timeout); + assert!(submissions.read_q().is_empty()); + } } diff --git a/proofs/services/defender/src/config.rs b/proofs/services/defender/src/config.rs index 64aaecaee..33ec833a5 100644 --- a/proofs/services/defender/src/config.rs +++ b/proofs/services/defender/src/config.rs @@ -1,4 +1,5 @@ use crate::error::DefenderError; +use alloy_primitives::Address; use std::time::Duration; /// Default number of games processed concurrently. @@ -10,6 +11,8 @@ pub const DEFAULT_L1_TX_CONFIRMATIONS: u64 = 5; /// Configuration for the defender. #[derive(Debug, Clone)] pub struct DefenderConfig { + /// Eligible game to extend while recovering from an unusable ASR anchor. + pub recovery_parent: Option

, /// Delay between periodic scan attempts. pub poll_interval: Duration, /// Maximum number of games to process concurrently. @@ -35,6 +38,7 @@ impl DefenderConfig { impl Default for DefenderConfig { fn default() -> Self { Self { + recovery_parent: None, poll_interval: Duration::from_mins(1), max_game_concurrency: DEFAULT_MAX_GAME_CONCURRENCY, } diff --git a/proofs/services/defender/src/defender.rs b/proofs/services/defender/src/defender.rs index b4e38d524..e182e09f4 100644 --- a/proofs/services/defender/src/defender.rs +++ b/proofs/services/defender/src/defender.rs @@ -110,10 +110,14 @@ where P: ProofRequester + Sync, { /// Reconstructs the valid lineage selected by the same transition rule as the proposer. - // Same-domain implementation rotations keep old games discoverable here. Domain-changing - // cutovers need a separate retirement or legacy-lineage policy before they can be supported. + // Domain-changing recovery uses the same operator-selected parent as the proposer. async fn selected_lineage(&self) -> Result, DefenderError> { - let lineage = select_lineage(&self.execution_provider, &self.consensus_provider).await?; + let lineage = select_lineage( + &self.execution_provider, + &self.consensus_provider, + self.config.recovery_parent, + ) + .await?; let mut games = Vec::with_capacity(lineage.games().len()); for selected in lineage.games() { diff --git a/proofs/services/defender/src/game.rs b/proofs/services/defender/src/game.rs index 2c231539e..c9daa30d9 100644 --- a/proofs/services/defender/src/game.rs +++ b/proofs/services/defender/src/game.rs @@ -1,5 +1,5 @@ use crate::{error::DefenderError, traits::DefenderClient, types::GameMetadata}; -use world_chain_proof_protocol::{GameStatus, InvalidationReason, ProposalStatus, proof_count}; +use world_chain_proof_protocol::{GameStatus, InvalidationReason, ProposalStatus}; /// On-chain state relevant to proof support for one selected game. #[derive(Debug, PartialEq, Eq)] @@ -59,13 +59,13 @@ where ProposalStatus::Unchallenged | ProposalStatus::UnchallengedAndValidProofProvided => { GameObservation::Proposed { proof_bitmap, - has_initial_support: proof_bitmap != 0, + has_initial_support: claim.status.has_sufficient_proof_support(), } } ProposalStatus::Challenged | ProposalStatus::ChallengedAndValidProofProvided => { GameObservation::Challenged { proof_bitmap, - has_required_support: proof_count(proof_bitmap) >= game.proof_threshold, + has_required_support: claim.status.has_sufficient_proof_support(), } } // The game sets `Resolved` and its `GameStatus` in the same call, so this is only diff --git a/proofs/services/defender/src/lane.rs b/proofs/services/defender/src/lane.rs index 63237e7b6..3df68022c 100644 --- a/proofs/services/defender/src/lane.rs +++ b/proofs/services/defender/src/lane.rs @@ -127,7 +127,9 @@ where match status { ProofStatus::Created | ProofStatus::Running => state, ProofStatus::Succeeded => self.submit_succeeded_lane(metadata, lane, id, state).await, - ProofStatus::Failed => self.retry_failed_lane(metadata, lane, backend, state).await, + ProofStatus::Failed | ProofStatus::Cancelled => { + self.retry_lane(metadata, lane, backend, state).await + } } } @@ -204,7 +206,7 @@ where } } - async fn retry_failed_lane( + async fn retry_lane( &self, metadata: &GameMetadata, lane: ProofLane, @@ -212,8 +214,8 @@ where state: LaneState, ) -> LaneState { let game = metadata.address; - // Re-requesting a failed proof re-queues the same deterministic proof id. The - // prover-service owns the durable retry counter and rejects exhausted requests. + // Re-requesting uses the same deterministic id. The prover-service counts failure + // retries, while cancelled jobs can restart if on-chain support is needed again. match self .proof_requester .request_proof(proof_request(metadata, backend)) @@ -227,7 +229,7 @@ where proof_id = %request_proof_response.proof_id, ?backend, ?lane, - "proof failed; re-requested proof" + "re-requested inactive proof" ); LaneState::Requested { id: request_proof_response.proof_id, diff --git a/proofs/services/defender/src/main.rs b/proofs/services/defender/src/main.rs index 3c214a582..97328c023 100644 --- a/proofs/services/defender/src/main.rs +++ b/proofs/services/defender/src/main.rs @@ -8,16 +8,20 @@ use std::time::Duration; use alloy_primitives::Address; -use alloy_provider::ProviderBuilder; +use alloy_provider::{Provider, ProviderBuilder}; use alloy_signer_local::PrivateKeySigner; use anyhow::{Context, Result}; use clap::{ArgGroup, Parser}; -use tracing::info; +use tracing::{info, warn}; use url::Url; use world_chain_defender::{ AlloyDefenderClient, DEFAULT_L1_TX_CONFIRMATIONS, DefenderConfig, WorldChainDefender, }; -use world_chain_proof_protocol::{OptimismConsensusClient, VerifyingConsensusProvider}; +use world_chain_proof_metrics::RPC_ENDPOINT_VERIFYING; +use world_chain_proof_protocol::{ + IDisputeGameFactory, IERC20StakingVault, OptimismConsensusClient, VerifyingConsensusProvider, + read_registered_bond_vault, +}; use world_chain_proof_tx_signer::build_transaction_signer; use world_chain_prover_service::RpcProverServiceClient; @@ -35,6 +39,14 @@ struct Cli { #[arg(long, env = "L1_RPC_URL")] l1_rpc: String, + /// Optional Ethereum L1 execution RPC URL used after the primary endpoint fails. + #[arg(long, env = "L1_FALLBACK_RPC_URL")] + l1_fallback_rpc: Option, + + /// Private L1 RPC for proof estimation and submission. Never falls back to the read RPC. + #[arg(long, env = "L1_SUBMISSION_RPC_URL", hide_env_values = true)] + l1_submission_rpc: Option, + /// op-node rollup RPC URL used to read canonical L2 output roots. #[arg(long, env = "OUTPUT_ROOT_RPC_URL")] output_root_rpc: String, @@ -47,6 +59,10 @@ struct Cli { #[arg(long, env = "PROVER_SERVICE_URL")] prover_service_url: String, + /// Start from this eligible game until a valid ASR anchor advances above it. + #[arg(long, env = "RECOVERY_PARENT")] + recovery_parent: Option
, + /// OP Stack `DisputeGameFactory` address on L1. #[arg(long, env = "FACTORY_ADDRESS")] factory_address: Address, @@ -116,21 +132,71 @@ async fn main() -> Result<()> { .wallet(); let defender_address = wallet.default_signer().address(); let reward_recipient = cli.proof_reward_recipient.unwrap_or(defender_address); + let l1_fallback_rpc_url = cli + .l1_fallback_rpc + .as_deref() + .map(Url::parse) + .transpose() + .context("invalid L1 fallback RPC URL")?; let l1_rpc_client = world_chain_proof_metrics::metered_http_client( l1_rpc_url, + l1_fallback_rpc_url, world_chain_proof_metrics::RPC_TARGET_L1_EXECUTION, Duration::from_secs(cli.l1_rpc_timeout_seconds), ) .context("failed to build the L1 RPC client")?; - let provider = ProviderBuilder::new() - .disable_recommended_fillers() - .with_gas_estimation() - .with_blob_gas_estimation() - .with_simple_nonce_management() - .fetch_chain_id() - .wallet(wallet) - .connect_client(l1_rpc_client); + let build_provider = |rpc_client| { + ProviderBuilder::new() + .disable_recommended_fillers() + .with_gas_estimation() + .with_blob_gas_estimation() + .with_simple_nonce_management() + .fetch_chain_id() + .wallet(wallet.clone()) + .connect_client(rpc_client) + }; + let provider = build_provider(l1_rpc_client); + let submission_provider = if let Some(url) = &cli.l1_submission_rpc { + let rpc_client = world_chain_proof_metrics::metered_http_client( + url.clone(), + None, + "l1_submission", + Duration::from_secs(cli.l1_rpc_timeout_seconds), + ) + .context("failed to build the L1 submission RPC client")?; + let submission_provider = build_provider(rpc_client); + anyhow::ensure!( + provider.get_chain_id().await? == submission_provider.get_chain_id().await?, + "L1 read and submission RPCs must use the same chain" + ); + submission_provider + } else { + warn!("L1_SUBMISSION_RPC_URL is unset; proofs use the normal L1 RPC and its fallback"); + provider.clone() + }; world_chain_proof_metrics::refresh_wallet_balance(&provider, defender_address).await; + let factory = IDisputeGameFactory::IDisputeGameFactoryInstance::new( + cli.factory_address, + provider.clone(), + ); + match read_registered_bond_vault(&provider, &factory).await { + Ok(bond_vault) => { + let vault = + IERC20StakingVault::IERC20StakingVaultInstance::new(bond_vault, provider.clone()); + match vault.availableBalance(reward_recipient).call().await { + Ok(balance) => world_chain_proof_metrics::record_vault_balance( + bond_vault, + reward_recipient, + "defender", + balance, + ), + Err(error) => { + warn!(%error, "failed to fetch defender reward-recipient ERC-20 vault balance") + } + } + } + Err(error) => warn!(%error, "failed to discover ERC-20 vault for defender telemetry"), + } let client = AlloyDefenderClient::new( provider, @@ -140,16 +206,18 @@ async fn main() -> Result<()> { reward_recipient, ) .await - .context("failed to connect defender to the registered proof system")?; + .context("failed to connect defender to the registered proof system")? + .with_submission_provider(submission_provider); let output_roots = VerifyingConsensusProvider::new( OptimismConsensusClient::new(cli.output_root_rpc.clone()), cli.verifying_output_root_rpc .clone() - .map(OptimismConsensusClient::new), + .map(|url| OptimismConsensusClient::new(url).with_endpoint(RPC_ENDPOINT_VERIFYING)), ); let proof_requester = RpcProverServiceClient::new(&cli.prover_service_url) .with_context(|| format!("failed to connect to {}", cli.prover_service_url))?; let config = DefenderConfig { + recovery_parent: cli.recovery_parent, poll_interval: Duration::from_secs(cli.poll_interval_seconds), max_game_concurrency: cli.max_game_concurrency, }; @@ -157,10 +225,13 @@ async fn main() -> Result<()> { info!( l1_rpc_url = world_chain_proof_metrics::redact_endpoint(&cli.l1_rpc), + l1_fallback_rpc_configured = cli.l1_fallback_rpc.is_some(), + private_submission_configured = cli.l1_submission_rpc.is_some(), output_root_rpc_url = world_chain_proof_metrics::redact_endpoint(&cli.output_root_rpc), verifying_output_root_rpc_configured = cli.verifying_output_root_rpc.is_some(), prover_service = %cli.prover_service_url, dispute_game_factory = %cli.factory_address, + recovery_parent = ?cli.recovery_parent, defender = %defender_address, reward_recipient = %reward_recipient, l1_tx_confirmations = cli.l1_tx_confirmations, diff --git a/proofs/services/defender/src/tests.rs b/proofs/services/defender/src/tests.rs index 6a0e05689..59a798d32 100644 --- a/proofs/services/defender/src/tests.rs +++ b/proofs/services/defender/src/tests.rs @@ -20,7 +20,8 @@ use world_chain_proof_core::boot::TransitionPublicValues; use world_chain_proof_protocol::{ ClaimData, ConsensusError, ConsensusProvider, GameStatus, InvalidationReason, LineageAnchor, LineageError, LineageGame, LineageProvider, LineageTransition, MAX_ATTEMPT_SCAN, - PROOF_THRESHOLD, ProofLane, ProposalCommitment, ProposalStatus, ResolutionStatus, proof_count, + PROOF_THRESHOLD, ProofLane, ProposalCommitment, ProposalStatus, RecoveryParent, + ResolutionStatus, proof_count, }; use world_chain_prover_service::{ ProofBackend, ProofData, ProofRequest, ProofRequestError, ProofRequestId, ProofRequester, @@ -197,6 +198,32 @@ impl LineageProvider for MockClient { Ok(self.state.lock().expect("not poisoned").anchor) } + async fn recovery_parent(&self, game: Address) -> Result { + let guard = self.state.lock().expect("not poisoned"); + let record = guard + .games + .get(&game) + .ok_or(LineageError::InvalidRecoveryParent(game))?; + Ok(RecoveryParent { + anchor: LineageAnchor { + address: game, + l2_block_number: record.metadata.l2_block_number, + }, + root_claim: record.metadata.root_claim, + eligible: record.state == GameLifecycle::Finalized, + }) + } + + async fn lineage_anchor_claim_valid(&self, game: Address) -> Result { + Ok(self + .state + .lock() + .expect("not poisoned") + .games + .get(&game) + .is_some_and(|record| record.state == GameLifecycle::Finalized)) + } + async fn game_for_transition( &self, transition: LineageTransition, @@ -237,6 +264,7 @@ impl LineageProvider for MockClient { state => state, }; Ok(ResolutionStatus { + status: record.state.outcome(), resolvable: lifecycle != record.state, outcome: lifecycle.outcome(), invalidation_reason: record.invalidation_reason, @@ -263,7 +291,13 @@ impl DefenderClient for MockClient { .games .get(&game) .map(|record| ClaimData { - status: record.state.proposal_status(record.proof_bitmap != 0), + status: record.state.proposal_status( + if record.state == GameLifecycle::Challenged { + proof_count(record.proof_bitmap) >= record.metadata.proof_threshold + } else { + record.proof_bitmap != 0 + }, + ), challenger: Address::ZERO, deadline: record.metadata.proof_deadline, proof_bitmap: record.proof_bitmap, @@ -321,6 +355,7 @@ fn output_roots(entries: &[(u64, B256)], finalized: u64) -> MockOutputRoots { #[derive(Debug, Clone, Default)] struct MockProver { fail: bool, + status: Option, max_requests_per_proof: Option, requests: Arc>>, request_counts: Arc>>, @@ -378,6 +413,9 @@ impl ProofRequester for MockProver { &self, _proof_id: ProofRequestId, ) -> Result { + if let Some(status) = self.status { + return Ok(status); + } Ok(if self.fail { ProofStatus::Failed } else { @@ -425,6 +463,7 @@ impl ProofRequester for MockProver { fn config() -> DefenderConfig { DefenderConfig { + recovery_parent: None, poll_interval: Duration::from_secs(1), max_game_concurrency: 10, } @@ -552,6 +591,44 @@ async fn selected_challenged_game_with_council_support_only_requests_tee() { assert!(defender.active_defenses().is_empty()); } +#[tokio::test] +async fn cancelled_proof_is_requested_again_when_a_supported_game_is_challenged() { + let root = B256::repeat_byte(0x20); + let client = MockClient::new(); + client.insert_game(GAME_1, ANCHOR, root, L2_BLOCK, 0, GameLifecycle::Proposed); + let prover = MockProver { + status: Some(ProofStatus::Cancelled), + ..Default::default() + }; + let mut defender = WorldChainDefender::new( + config(), + client.clone(), + output_roots(&[(L2_BLOCK, root)], L2_BLOCK), + prover.clone(), + ); + defender.tick().await.unwrap(); + assert_eq!(prover.requests().len(), 1); + + client.set_bitmap(GAME_1, ProofLane::SecurityCouncil.mask()); + defender.tick().await.unwrap(); + assert!(defender.active_defenses().is_empty()); + assert_eq!(prover.requests().len(), 1); + + client.set_state(GAME_1, GameLifecycle::Challenged, InvalidationReason::None); + defender.tick().await.unwrap(); + defender.tick().await.unwrap(); + assert_eq!(prover.requests().len(), 3); + assert!(defender.active_defenses().contains(&GAME_1)); + + client.set_bitmap( + GAME_1, + ProofLane::SecurityCouncil.mask() | ProofLane::TeeAttestation.mask(), + ); + defender.tick().await.unwrap(); + assert!(defender.active_defenses().is_empty()); + assert_eq!(prover.requests().len(), 3); +} + #[tokio::test] async fn selected_descendant_is_defended_before_parent_resolves() { let root_1 = B256::repeat_byte(0x20); @@ -816,8 +893,56 @@ async fn selected_game_deadline_stops_proof_work() { #[test] fn config_rejects_zero_concurrency() { let config = DefenderConfig { + recovery_parent: None, poll_interval: Duration::from_secs(1), max_game_concurrency: 0, }; assert!(config.validate().is_err()); } + +#[tokio::test] +async fn recovery_defends_replacement_branch_instead_of_unusable_anchor() { + let parent = Address::repeat_byte(0x77); + let old_anchor = Address::repeat_byte(0x88); + let parent_root = B256::repeat_byte(0x10); + let root = B256::repeat_byte(0x20); + let client = MockClient::new(); + client.insert_game( + parent, + ANCHOR, + parent_root, + L2_BLOCK - BLOCK_INTERVAL, + 0, + GameLifecycle::Finalized, + ); + client.insert_game( + old_anchor, + parent, + root, + L2_BLOCK, + 0, + GameLifecycle::Invalidated, + ); + client.insert_game(GAME_1, parent, root, L2_BLOCK, 0, GameLifecycle::Proposed); + client.state.lock().expect("not poisoned").anchor = LineageAnchor { + address: old_anchor, + l2_block_number: L2_BLOCK, + }; + let prover = MockProver::default(); + let mut defender = WorldChainDefender::new( + DefenderConfig { + recovery_parent: Some(parent), + ..config() + }, + client.clone(), + output_roots( + &[(L2_BLOCK - BLOCK_INTERVAL, parent_root), (L2_BLOCK, root)], + L2_BLOCK, + ), + prover.clone(), + ); + defender.tick().await.unwrap(); + defender.tick().await.unwrap(); + assert_eq!(prover.requests().len(), 1); + assert_eq!(client.submissions()[0].0, GAME_1); +} diff --git a/proofs/services/proposer/Cargo.toml b/proofs/services/proposer/Cargo.toml index 6e6a4512f..512889411 100644 --- a/proofs/services/proposer/Cargo.toml +++ b/proofs/services/proposer/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "world-chain-proposer" -version = "1.0.0-rc.1" +version = "1.0.0-rc.5" edition.workspace = true rust-version.workspace = true license.workspace = true diff --git a/proofs/services/proposer/README.md b/proofs/services/proposer/README.md index 8697906dd..56ac49f8a 100644 --- a/proofs/services/proposer/README.md +++ b/proofs/services/proposer/README.md @@ -48,9 +48,34 @@ claim is valid according to the registry, allowing it to skip a newer game still The automated services assume proof-timeout retries are exceptional. The proposer creates the next attempt and the defender follows that replacement. Games descending from the abandoned attempt become resolvable as `INVALID_PARENT`; the bond manager keeps proposer-owned games tracked, resolves -those descendants as their parents settle, and claims the refunded bonds. Retry creation remains +those descendants as their parents settle, and closes them to release their bonds. Retry creation remains logged at warn level for operator visibility. +## Recovering from an unusable anchor + +Restart both proposer and defender with `--recovery-parent

` (or `RECOVERY_PARENT=

`), +where P is an eligible ancestor of the unusable anchor. While the ASR anchor is unusable, +both services select the replacement lineage from P using the active implementation's domain. +The proposer creates and resolves replacement games; the defender supplies their proofs. +Existing replacement games are rediscovered across ticks and restarts. + +P must be a registered, proper, respected game resolved with `DEFENDER_WINS`, and its root must +match the canonical finalized L2 root. Eligibility and root checks are repeated while P is used. +Invalid parents or failed RPC reads stop that scan without falling back to the unusable anchor. +The ASR sentinel and zero address cannot be recovery parents. + +Both services automatically resume from the ASR once it has a claim-valid anchor at a block +above P. A replacement at the old anchor's block cannot advance the ASR; a later replacement +must resolve and pass the registry finality delay. Remove the flag after recovery to avoid +reusing P during a subsequent incident. `lineage.recovery_active` reports whether recovery +selection is active, and startup logs include the configured parent. + +The flag does not change onchain state or bypass parent and retry checks. Replacing a blacklisted +successful game with the same root and parent requires a new proof domain to avoid its occupied +factory UUID. Activate that domain through governance before restarting the services. Keep the +block interval unchanged for this recovery procedure; the flag does not reconcile cadence changes. +If P is retired or no eligible game parent exists, onchain recovery is required. + ### `root_claim` - rpc request to a consensus client - i.e. `optimism_outputAtBlock` @@ -61,11 +86,11 @@ logged at warn level for operator visibility. ## Bond settlement -Bonds are custodied in `DelayedWETH` and paid out in two phases. The first `claimCredit(recipient)` -call unlocks the credit; the second, after the WETH delay, withdraws and transfers it. Both are -gated on `AnchorStateRegistry.isGameFinalized`, since `claimCredit` calls `closeGame`, which reverts -until the registry's finality airgap has elapsed. The bond manager keeps every discovered -proposer-owned game tracked until it is resolved and its pending withdrawal is drained. For games +Bonds are locked from the proposer's available balance in the singleton ERC-20 staking vault. +After a game resolves and passes the registry's finality airgap, its permissionless `closeGame()` +call settles the complete bond pot into immediately reusable vault balances. The service never +requests an external bond-token withdrawal. The bond manager keeps every discovered proposer-owned +game tracked until it is resolved and settled. For games whose embedded proposal domain differs from the currently registered domain, it also submits any available positive or negative resolution because those games are no longer visible to the selected lineage proposer. Same-domain outcomes remain with the proposer to avoid racing retry creation. diff --git a/proofs/services/proposer/src/alloy.rs b/proofs/services/proposer/src/alloy.rs index 7d7311212..599b14665 100644 --- a/proofs/services/proposer/src/alloy.rs +++ b/proofs/services/proposer/src/alloy.rs @@ -1,20 +1,20 @@ -use alloy_consensus::BlockHeader; -use alloy_eips::BlockNumberOrTag; use alloy_primitives::{Address, B256, U256}; use alloy_provider::{Provider, WalletProvider}; use async_trait::async_trait; use std::{sync::Arc, time::Duration}; use tokio::sync::Semaphore; +use tracing::warn; use world_chain_proof_protocol::{ - IAnchorStateRegistry, IDelayedWETH, IDisputeGameFactory, IMultiProofGame, LineageAnchor, + IAnchorStateRegistry, IDisputeGameFactory, IERC20StakingVault, IMultiProofGame, LineageAnchor, LineageError, LineageGame, LineageProvider, LineageTransition, MULTI_PROOF_GAME_TYPE, - RegisteredLineageConfig, ResolutionStatus, read_game_for_transition, read_lineage_anchor, - read_lineage_resolution_status, read_registered_lineage_config, + RecoveryParent, RegisteredLineageConfig, ResolutionStatus, read_game_for_transition, + read_game_has_retry, read_lineage_anchor, read_lineage_resolution_status, read_recovery_parent, + read_registered_bond_vault, read_registered_lineage_config, }; use crate::{ BondManagerClient, Proposal, ProposalSubmission, ProposerClient, ProposerError, - types::{ClaimSubmission, CloseGameSubmission, PendingWithdrawal, ResolveSubmission}, + types::{CloseGameSubmission, ResolveSubmission}, }; /// Alloy-backed implementation of the proposer contract clients. @@ -26,6 +26,7 @@ use crate::{ pub struct AlloyProofSystemClient

{ factory: IDisputeGameFactory::IDisputeGameFactoryInstance

, anchor: IAnchorStateRegistry::IAnchorStateRegistryInstance

, + vault: IERC20StakingVault::IERC20StakingVaultInstance

, registered: RegisteredLineageConfig, /// Number of confirmations to require after sending a tx onchain. confirmations: u64, @@ -54,6 +55,21 @@ where provider.clone(), ); let registered = read_registered_lineage_config(&provider, &factory).await?; + let bond_vault = read_registered_bond_vault(&provider, &factory).await?; + let init_bond = factory.initBonds(MULTI_PROOF_GAME_TYPE).call().await?; + if !init_bond.is_zero() { + return Err(ProposerError::NonZeroFactoryBond(init_bond)); + } + let vault = + IERC20StakingVault::IERC20StakingVaultInstance::new(bond_vault, provider.clone()); + let configured_factory = vault.disputeGameFactory().call().await?; + if configured_factory != factory_address { + return Err(ProposerError::VaultFactoryMismatch { + vault: bond_vault, + expected: factory_address, + actual: configured_factory, + }); + } let anchor = IAnchorStateRegistry::IAnchorStateRegistryInstance::new( registered.anchor_registry, provider.clone(), @@ -63,6 +79,7 @@ where Ok(Self { factory, anchor, + vault, registered, confirmations, receipt_timeout, @@ -77,6 +94,33 @@ where self.registered } + /// Returns the singleton ERC-20 vault discovered from the active implementation. + #[must_use] + pub fn bond_vault_address(&self) -> Address { + *self.vault.address() + } + + /// Refreshes the managed proposer's reusable bond-token balance metric. + pub async fn refresh_vault_balance(&self) + where + P: WalletProvider, + { + self.refresh_vault_balance_for(self.provider.default_signer_address()) + .await; + } + + async fn refresh_vault_balance_for(&self, account: Address) { + match self.vault.availableBalance(account).call().await { + Ok(balance) => world_chain_proof_metrics::record_vault_balance( + self.bond_vault_address(), + account, + "proposer", + balance, + ), + Err(error) => warn!(%error, %account, "failed to fetch proposer ERC-20 vault balance"), + } + } + fn game(&self, address: Address) -> IMultiProofGame::IMultiProofGameInstance

{ IMultiProofGame::IMultiProofGameInstance::new(address, self.provider.clone()) } @@ -131,63 +175,9 @@ where Ok(ResolveSubmission { tx_hash }) } - /// Reads the credit `recipient` can unlock from `game`. - async fn read_credit(&self, game: Address, recipient: Address) -> Result { - self.game(game) - .credit(recipient) - .call() - .await - .map_err(Into::into) - } - - /// Reads `recipient`'s pending `DelayedWETH` withdrawal for `game`. - async fn read_pending_withdrawal( - &self, - game: Address, - recipient: Address, - ) -> Result { - let weth_address = self.game(game).weth().call().await?; - let weth = IDelayedWETH::IDelayedWETHInstance::new(weth_address, self.provider.clone()); - - let (pending, delay) = self - .provider - .multicall() - .add(weth.withdrawals(game, recipient)) - .add(weth.delay()) - .aggregate() - .await?; - - if pending.amount.is_zero() { - return Ok(PendingWithdrawal::default()); - } - let unlock_at = pending - .timestamp - .checked_add(delay) - .ok_or(ProposerError::Overflow)?; - - Ok(PendingWithdrawal { - amount: pending.amount, - unlock_at: u256_to_u64(unlock_at)?, - }) - } - - /// Sends `claimCredit(recipient)` and reports which phase of the two-phase flow ran. - async fn send_claim_credit( - &self, - game: Address, - recipient: Address, - ) -> Result { + async fn send_close_game(&self, game: Address) -> Result { let _permit = self.semaphore.acquire().await?; - // Read both phases up front so the submission can report what the call moved; the - // receipt carries no amount of its own. - let credit = self.read_credit(game, recipient).await?; - let pending = if credit.is_zero() { - self.read_pending_withdrawal(game, recipient).await? - } else { - PendingWithdrawal::default() - }; - - let pending_tx = self.game(game).claimCredit(recipient).send().await?; + let pending_tx = self.game(game).closeGame().send().await?; let tx_hash = *pending_tx.tx_hash(); let receipt = pending_tx .with_required_confirmations(self.confirmations) @@ -198,21 +188,9 @@ where if !receipt.status() { return Err(ProposerError::Revert(tx_hash)); } + self.refresh_vault_balance_for(receipt.from).await; - Ok(if credit.is_zero() { - world_chain_proof_metrics::record_bond_withdrawn("proposer", pending.amount); - ClaimSubmission { - tx_hash, - amount: pending.amount, - withdrawn: true, - } - } else { - ClaimSubmission { - tx_hash, - amount: credit, - withdrawn: false, - } - }) + Ok(CloseGameSubmission { tx_hash }) } } @@ -258,6 +236,12 @@ where self.read_resolution_status(game).await } + async fn has_retry(&self, game: Address) -> Result { + read_game_has_retry(&self.factory, &self.game(game)) + .await + .map_err(Into::into) + } + async fn resolve_game(&self, game: Address) -> Result { self.send_resolve_game(game).await } @@ -266,25 +250,12 @@ where self.read_is_game_finalized(game).await } - async fn credit(&self, game: Address) -> Result { - self.read_credit(game, self.proposer_address()).await + async fn is_game_settled(&self, game: Address) -> Result { + Ok(self.vault.gameBonds(game).call().await?.settled) } - async fn pending_withdrawal(&self, game: Address) -> Result { - self.read_pending_withdrawal(game, self.proposer_address()) - .await - } - - async fn latest_l1_timestamp(&self) -> Result { - self.provider - .get_block_by_number(BlockNumberOrTag::Latest) - .await? - .map(|block| block.header.timestamp()) - .ok_or(ProposerError::UnavailableLatestL1Block) - } - - async fn claim_credit(&self, game: Address) -> Result { - self.send_claim_credit(game, self.proposer_address()).await + async fn close_game(&self, game: Address) -> Result { + self.send_close_game(game).await } } @@ -301,6 +272,20 @@ where read_lineage_anchor(&self.provider, &self.anchor).await } + async fn recovery_parent(&self, game: Address) -> Result { + read_recovery_parent(&self.provider, &self.anchor, game).await + } + + async fn lineage_anchor_claim_valid(&self, game: Address) -> Result { + self.anchor + .isGameClaimValid(game) + .call() + .await + .map_err(|error| { + LineageError::Contract(format!("read anchor eligibility for {game}: {error}")) + }) + } + async fn game_for_transition( &self, transition: LineageTransition, @@ -330,21 +315,7 @@ where } async fn close_game(&self, game: Address) -> Result { - let _permit = self.semaphore.acquire().await?; - let pending = self.game(game).closeGame().send().await?; - - let tx_hash = *pending.tx_hash(); - let receipt = pending - .with_required_confirmations(self.confirmations) - .with_timeout(Some(self.receipt_timeout)) - .get_receipt() - .await?; - world_chain_proof_metrics::refresh_wallet_balance(&self.provider, receipt.from).await; - if !receipt.status() { - return Err(ProposerError::Revert(tx_hash)); - } - - Ok(CloseGameSubmission { tx_hash }) + self.send_close_game(game).await } async fn submit_proposal( @@ -352,17 +323,12 @@ where proposal: &Proposal, ) -> Result { let _permit = self.semaphore.acquire().await?; - // `DisputeGameFactory.create` reverts unless `msg.value` matches the configured init - // bond exactly, so it is read per submission rather than cached in configuration. - let init_bond = self.factory.initBonds(MULTI_PROOF_GAME_TYPE).call().await?; - let extra_data = proposal .commitment() .extra_data(self.registered.domain_hash); let pending = self .factory .create(MULTI_PROOF_GAME_TYPE, proposal.root_claim, extra_data) - .value(init_bond) .send() .await?; @@ -376,7 +342,19 @@ where if !receipt.status() { return Err(ProposerError::Revert(tx_hash)); } - world_chain_proof_metrics::record_bond_posted("proposer", init_bond); + let locked = receipt + .logs() + .iter() + .filter(|log| log.address() == *self.vault.address()) + .find_map(|log| { + log.log_decode_validate::() + .ok() + .map(|decoded| decoded.inner.data.amount) + }) + .ok_or(ProposerError::MissingProposerBondLockedEvent(tx_hash))?; + world_chain_proof_metrics::record_bond_locked("proposer", locked); + self.refresh_vault_balance_for(self.proposer_address()) + .await; let game_address = receipt .logs() diff --git a/proofs/services/proposer/src/bond_manager.rs b/proofs/services/proposer/src/bond_manager.rs index 7d0ae585b..e26dd4633 100644 --- a/proofs/services/proposer/src/bond_manager.rs +++ b/proofs/services/proposer/src/bond_manager.rs @@ -1,17 +1,20 @@ use std::collections::HashSet; -use alloy_primitives::{Address, U256}; +use alloy_primitives::Address; use tracing::{info, warn}; +use world_chain_proof_protocol::{GameStatus, InvalidationReason}; use crate::{BondManagerClient, BondManagerConfig, ProposerError}; -/// Discovers proposer-owned games, resolves abandoned games, and recovers bond credits. +/// Discovers proposer-owned games, resolves abandoned games, and settles their bond pots. #[derive(Debug)] pub struct BondManager { config: BondManagerConfig, execution_provider: E, proposed_games: HashSet

, next_game_index: Option, + /// Rotates cleanup work so a failing resolution cannot starve other superseded attempts. + last_retry_resolution: Option
, } impl BondManager { @@ -22,6 +25,7 @@ impl BondManager { execution_provider, proposed_games: HashSet::default(), next_game_index: None, + last_retry_resolution: None, } } @@ -37,7 +41,7 @@ impl BondManager { self.next_game_index } - /// Returns whether a game is currently awaiting resolution or withdrawal. + /// Returns whether a game is currently awaiting resolution or settlement. #[must_use] pub fn tracks_game(&self, game: Address) -> bool { self.proposed_games.contains(&game) @@ -82,28 +86,52 @@ where Ok(()) } - /// Resolves abandoned games, advances bond claims, and prunes fully settled games. - /// - /// `MultiProofGame.claimCredit` first unlocks the credit in `DelayedWETH` and only - /// transfers it on a second call after the WETH delay, so a game stays tracked until its - /// pending withdrawal is drained. Dropping it after the unlock would strand the bond. + /// Resolves abandoned games, settles finalized games, and prunes settled games. pub async fn settle_games(&mut self) -> Result<(), ProposerError> { - let proposed_games: Vec<_> = self.proposed_games.iter().copied().collect(); - let now = self.execution_provider.latest_l1_timestamp().await?; + let mut proposed_games: Vec<_> = self.proposed_games.iter().copied().collect(); + proposed_games.sort_unstable(); + if let Some(last) = self.last_retry_resolution { + let start = proposed_games.partition_point(|game| *game <= last); + proposed_games.rotate_left(start); + } let active_domain_hash = self.execution_provider.active_domain_hash(); + let mut retry_resolutions_attempted = 0; for game in proposed_games { let result: Result = async { + if self.execution_provider.is_game_settled(game).await? { + world_chain_proof_metrics::increment_games_closed( + "proposer", + "already_settled", + ); + return Ok(true); + } let resolution_status = self.execution_provider.resolution_status(game).await?; if !resolution_status.is_resolved() { - // Resolve games abandoned by retries or domain upgrades; active-domain direct - // outcomes stay with the proposer to avoid racing retry creation. + // The lineage proposer only visits the highest attempt. Once a retry exists, + // we own cleanup of the old attempt as well as its invalidated descendants. let obsolete_domain_resolvable = if resolution_status.resolvable { self.execution_provider.game_domain_hash(game).await? != active_domain_hash } else { false }; - if resolution_status.invalid_parent_resolvable() || obsolete_domain_resolvable { + let superseded_retry = resolution_status.resolvable + && resolution_status.outcome == GameStatus::ChallengerWins + && resolution_status.invalidation_reason + == InvalidationReason::ProofTimeout + && !obsolete_domain_resolvable + && retry_resolutions_attempted < self.config.max_retry_resolutions_per_tick + && self.execution_provider.has_retry(game).await?; + if resolution_status.invalid_parent_resolvable() + || obsolete_domain_resolvable + || superseded_retry + { + if superseded_retry { + // Charge failed submissions against the budget too. The next pass + // starts after this game so a persistent failure cannot monopolize it. + retry_resolutions_attempted += 1; + self.last_retry_resolution = Some(game); + } let submission = self.execution_provider.resolve_game(game).await?; info!( lifecycle_event = "game_resolved", @@ -117,40 +145,16 @@ where } return Ok(false); } - // `claimCredit` calls `closeGame`, which reverts until the registry's finality - // airgap has elapsed. if !self.execution_provider.is_game_finalized(game).await? { return Ok(false); } - let credit = self.execution_provider.credit(game).await?; - if credit > U256::ZERO { - let submission = self.execution_provider.claim_credit(game).await?; - info!( - tx_hash = ?submission.tx_hash, - amount = ?submission.amount, - game_address = %game, - "unlocked proposer bond credits in DelayedWETH" - ); - // Keep tracking: the unlocked amount still needs the second claim. - return Ok(false); - } - - let pending = self.execution_provider.pending_withdrawal(game).await?; - if pending.amount.is_zero() { - // Nothing owed on this game; stop tracking it. - return Ok(true); - } - if now < pending.unlock_at { - return Ok(false); - } - - let submission = self.execution_provider.claim_credit(game).await?; + let submission = self.execution_provider.close_game(game).await?; + world_chain_proof_metrics::increment_games_closed("proposer", "submitted"); info!( tx_hash = ?submission.tx_hash, - amount = ?submission.amount, game_address = %game, - "withdrew proposer bond credits" + "settled proposer-owned game into reusable vault balances" ); Ok(true) } @@ -165,7 +169,7 @@ where warn!( %error, game_address = %game, - "failed to process proposer credits" + "failed to process proposer bond settlement" ); } } diff --git a/proofs/services/proposer/src/config.rs b/proofs/services/proposer/src/config.rs index ccc7f410a..fdc046cd8 100644 --- a/proofs/services/proposer/src/config.rs +++ b/proofs/services/proposer/src/config.rs @@ -1,3 +1,4 @@ +use alloy_primitives::Address; use std::time::Duration; use crate::ProposerError; @@ -11,10 +12,13 @@ pub const DEFAULT_BOND_MANAGER_INITIAL_SCAN_LIMIT: u64 = 1_000; /// Configuration for asynchronous proposer-bond management. #[derive(Debug, Clone)] pub struct BondManagerConfig { - /// Delay between factory scans and withdrawal attempts. + /// Delay between factory scans and settlement attempts. pub poll_interval: Duration, /// Number of most recently created games scanned on startup. pub initial_scan_limit: u64, + /// Maximum superseded proof-timeout resolution attempts per settlement pass. + /// Zero disables this cleanup without disabling existing settlement behavior. + pub max_retry_resolutions_per_tick: usize, } impl BondManagerConfig { @@ -38,17 +42,19 @@ impl Default for BondManagerConfig { Self { poll_interval: DEFAULT_BOND_MANAGER_POLL_INTERVAL, initial_scan_limit: DEFAULT_BOND_MANAGER_INITIAL_SCAN_LIMIT, + max_retry_resolutions_per_tick: 1, } } } /// Configuration for the proposer loop. /// -/// The proposal bond is deliberately absent: `DisputeGameFactory.create` reverts unless -/// `msg.value` matches `initBonds(gameType)` exactly, so it is read per submission rather than -/// captured at startup where an owner update would silently break every proposal. +/// The proposal bond is deliberately absent: the vault reads it from the active implementation +/// when creating a game and locking its proposer bond. #[derive(Debug, Clone)] pub struct ProposerConfig { + /// Eligible game to extend while recovering from an unusable ASR anchor. + pub recovery_parent: Option
, /// Delay between periodic proposal attempts. pub poll_interval: Duration, /// Maximum number of game-resolution transactions submitted per proposer tick. @@ -74,6 +80,7 @@ impl ProposerConfig { impl Default for ProposerConfig { fn default() -> Self { Self { + recovery_parent: None, poll_interval: Duration::from_secs(12), max_resolutions_per_tick: 1, } diff --git a/proofs/services/proposer/src/error.rs b/proofs/services/proposer/src/error.rs index 6c4e48b81..35a1a7542 100644 --- a/proofs/services/proposer/src/error.rs +++ b/proofs/services/proposer/src/error.rs @@ -1,4 +1,4 @@ -use alloy_primitives::TxHash; +use alloy_primitives::{Address, TxHash, U256}; use alloy_provider::{MulticallError, PendingTransactionError, transport::RpcError}; use alloy_transport::TransportErrorKind; use thiserror::Error; @@ -11,6 +11,14 @@ pub enum ProposerError { /// Invalid proposer configuration. #[error("invalid proposer config: {0}")] InvalidConfig(&'static str), + #[error("WIP-1006 factory init bond must be zero, got {0}")] + NonZeroFactoryBond(U256), + #[error("vault {vault} is wired to factory {actual}, expected {expected}")] + VaultFactoryMismatch { + vault: Address, + expected: Address, + actual: Address, + }, /// Contract call or transaction failure. #[error(transparent)] Contract(#[from] alloy_contract::Error), @@ -29,10 +37,10 @@ pub enum ProposerError { Revert(TxHash), #[error("Overflow error.")] Overflow, - #[error("Latest L1 block is unavailable.")] - UnavailableLatestL1Block, #[error("DisputeGameCreated event missing from proposal transaction {0}")] MissingProposalEvent(TxHash), + #[error("ProposerBondLocked event missing from proposal transaction {0}")] + MissingProposerBondLockedEvent(TxHash), #[error(transparent)] Permit(#[from] AcquireError), } diff --git a/proofs/services/proposer/src/lib.rs b/proofs/services/proposer/src/lib.rs index 4c3350fd9..0992dc5f9 100644 --- a/proofs/services/proposer/src/lib.rs +++ b/proofs/services/proposer/src/lib.rs @@ -23,8 +23,8 @@ pub use error::ProposerError; pub use proposer::WorldChainProposer; pub use traits::{BondManagerClient, ProposerClient}; pub use types::{ - ClaimSubmission, CloseGameSubmission, NextProposalAction, PendingWithdrawal, Proposal, - ProposalSubmission, ProposerScan, ResolveSubmission, + CloseGameSubmission, NextProposalAction, Proposal, ProposalSubmission, ProposerScan, + ResolveSubmission, }; #[cfg(test)] diff --git a/proofs/services/proposer/src/main.rs b/proofs/services/proposer/src/main.rs index c5256a255..20b6300e5 100644 --- a/proofs/services/proposer/src/main.rs +++ b/proofs/services/proposer/src/main.rs @@ -14,6 +14,7 @@ use anyhow::{Context, Result}; use clap::{ArgGroup, Parser}; use tracing::info; use url::Url; +use world_chain_proof_metrics::RPC_ENDPOINT_VERIFYING; use world_chain_proof_protocol::{OptimismConsensusClient, VerifyingConsensusProvider}; use world_chain_proof_tx_signer::build_transaction_signer; use world_chain_proposer::{ @@ -34,6 +35,10 @@ struct Cli { #[arg(long, env = "L1_RPC_URL")] l1_rpc: String, + /// Optional Ethereum L1 execution RPC URL used after the primary endpoint fails. + #[arg(long, env = "L1_FALLBACK_RPC_URL")] + l1_fallback_rpc: Option, + /// op-node rollup RPC URL used to read canonical L2 output roots. #[arg(long, env = "OUTPUT_ROOT_RPC_URL")] output_root_rpc: String, @@ -42,6 +47,10 @@ struct Cli { #[arg(long, env = "VERIFYING_OUTPUT_ROOT_RPC_URL")] verifying_output_root_rpc: Option, + /// Start from this eligible game until a valid ASR anchor advances above it. + #[arg(long, env = "RECOVERY_PARENT")] + recovery_parent: Option
, + /// OP Stack `DisputeGameFactory` address on L1. #[arg(long, env = "FACTORY_ADDRESS")] factory_address: Address, @@ -62,7 +71,7 @@ struct Cli { #[arg(long, env = "MAX_RESOLUTIONS_PER_TICK", default_value_t = 1)] max_resolutions_per_tick: usize, - /// Seconds between proposer-bond discovery and withdrawal passes. + /// Seconds between proposer-bond discovery and settlement passes. #[arg( long, env = "BOND_MANAGER_POLL_INTERVAL_SECONDS", @@ -74,6 +83,14 @@ struct Cli { #[arg(long, env = "BOND_MANAGER_INITIAL_SCAN_LIMIT", default_value_t = 1_000)] bond_manager_initial_scan_limit: u64, + /// Maximum superseded proof-timeout resolution attempts per bond-manager pass; zero disables them. + #[arg( + long, + env = "BOND_MANAGER_MAX_RETRY_RESOLUTIONS_PER_TICK", + default_value_t = 1 + )] + bond_manager_max_retry_resolutions_per_tick: usize, + /// Number of confirmations to require after sending a tx onchain. #[arg(long, env = "CONFIRMATIONS", default_value_t = 5)] confirmations: u64, @@ -112,8 +129,15 @@ async fn main() -> Result<()> { .context("failed to initialize proposer signer")? .wallet(); let proposer_address = wallet.default_signer().address(); + let l1_fallback_rpc_url = cli + .l1_fallback_rpc + .as_deref() + .map(Url::parse) + .transpose() + .context("invalid L1 fallback RPC URL")?; let l1_rpc_client = world_chain_proof_metrics::metered_http_client( - l1_rpc_url, + l1_rpc_url.clone(), + l1_fallback_rpc_url, world_chain_proof_metrics::RPC_TARGET_L1_EXECUTION, Duration::from_secs(cli.l1_rpc_timeout_seconds), ) @@ -137,19 +161,23 @@ async fn main() -> Result<()> { ) .await .context("failed to bind the World Chain proof system")?; + contracts.refresh_vault_balance().await; let bond_manager_config = BondManagerConfig { poll_interval: Duration::from_secs(cli.bond_manager_poll_interval_seconds), initial_scan_limit: cli.bond_manager_initial_scan_limit, + max_retry_resolutions_per_tick: cli.bond_manager_max_retry_resolutions_per_tick, }; let mut bond_manager = BondManager::new(bond_manager_config, contracts.clone()); let output_roots = VerifyingConsensusProvider::new( OptimismConsensusClient::new(cli.output_root_rpc.clone()), cli.verifying_output_root_rpc .clone() - .map(OptimismConsensusClient::new), + .map(|url| OptimismConsensusClient::new(url).with_endpoint(RPC_ENDPOINT_VERIFYING)), ); let registered = contracts.registered_lineage_config(); + let bond_vault = contracts.bond_vault_address(); let config = ProposerConfig { + recovery_parent: cli.recovery_parent, poll_interval: Duration::from_secs(cli.poll_interval_seconds), max_resolutions_per_tick: cli.max_resolutions_per_tick, }; @@ -157,10 +185,13 @@ async fn main() -> Result<()> { info!( l1_rpc_url = world_chain_proof_metrics::redact_endpoint(&cli.l1_rpc), + l1_fallback_rpc_configured = cli.l1_fallback_rpc.is_some(), output_root_rpc_url = world_chain_proof_metrics::redact_endpoint(&cli.output_root_rpc), verifying_output_root_rpc_configured = cli.verifying_output_root_rpc.is_some(), dispute_game_factory = %cli.factory_address, + recovery_parent = ?cli.recovery_parent, anchor = %registered.anchor_registry, + bond_vault = %bond_vault, proposer = %proposer_address, domain_hash = %registered.domain_hash, block_interval = registered.block_interval, diff --git a/proofs/services/proposer/src/proposer.rs b/proofs/services/proposer/src/proposer.rs index b81aead77..aab811055 100644 --- a/proofs/services/proposer/src/proposer.rs +++ b/proofs/services/proposer/src/proposer.rs @@ -46,7 +46,12 @@ where pub async fn scan_selected_lineage(&self) -> Result { self.config.validate()?; - let lineage = select_lineage(&self.execution_provider, &self.consensus_provider).await?; + let lineage = select_lineage( + &self.execution_provider, + &self.consensus_provider, + self.config.recovery_parent, + ) + .await?; let selected_l2_block_number = lineage .games() .last() diff --git a/proofs/services/proposer/src/tests.rs b/proofs/services/proposer/src/tests.rs index 28b55feb7..273a3838b 100644 --- a/proofs/services/proposer/src/tests.rs +++ b/proofs/services/proposer/src/tests.rs @@ -1,27 +1,21 @@ use std::{ collections::{HashMap, HashSet}, - sync::{ - Arc, Mutex, - atomic::{AtomicU64, Ordering}, - }, + sync::{Arc, Mutex}, time::Duration, }; -use alloy_primitives::{Address, B256, BlockNumber, U256, address, b256}; +use alloy_primitives::{Address, B256, BlockNumber, address, b256}; use async_trait::async_trait; use world_chain_proof_protocol::{ ConsensusError, ConsensusProvider, GameStatus, InvalidationReason, LineageAnchor, LineageError, - LineageGame, LineageProvider, LineageTransition, ProposalCommitment, ResolutionStatus, - SelectedLineageGame, + LineageGame, LineageProvider, LineageTransition, ProposalCommitment, RecoveryParent, + ResolutionStatus, SelectedLineageGame, }; use crate::{ BondManager, BondManagerClient, BondManagerConfig, Proposal, ProposalSubmission, ProposerClient, ProposerConfig, ProposerError, ProposerScan, WorldChainProposer, - types::{ - ClaimSubmission, CloseGameSubmission, NextProposalAction, PendingWithdrawal, - ResolveSubmission, - }, + types::{CloseGameSubmission, NextProposalAction, ResolveSubmission}, }; const DOMAIN_HASH: B256 = b256!("1111111111111111111111111111111111111111111111111111111111111111"); @@ -57,6 +51,25 @@ impl LineageProvider for MockContracts { Ok(self.anchor) } + async fn recovery_parent(&self, game: Address) -> Result { + if game != ANCHOR { + return Err(LineageError::InvalidRecoveryParent(game)); + } + Ok(RecoveryParent { + anchor: anchor_at(0), + root_claim: B256::ZERO, + eligible: true, + }) + } + + async fn lineage_anchor_claim_valid(&self, game: Address) -> Result { + Ok(!self + .unfinalized_games + .lock() + .expect("not poisoned") + .contains(&game)) + } + async fn game_for_transition( &self, transition: LineageTransition, @@ -88,6 +101,7 @@ impl LineageProvider for MockContracts { .expect("not poisoned") .remove(&game) .unwrap_or(ResolutionStatus { + status: GameStatus::InProgress, resolvable: false, outcome: GameStatus::InProgress, invalidation_reason: InvalidationReason::None, @@ -150,8 +164,6 @@ impl ProposerClient for MockContracts { } } -/// Two-phase bond client mirroring `MultiProofGame.claimCredit`: the first claim moves credit -/// into a pending `DelayedWETH` withdrawal, the second drains it. #[derive(Debug, Clone)] struct MockBondClient { proposer: Address, @@ -164,13 +176,15 @@ struct MockBondClient { resolution_statuses: Arc>>, resolutions: Arc>>, unfinalized_games: Arc>>, - credit: Arc>>, - pending: Arc>>, - latest_l1_timestamp: Arc, - unlocks: Arc>>, - withdrawals: Arc>>, + settled_games: Arc>>, + closes: Arc>>, fail_game_at_once: Arc>>, - fail_claim_once: Arc>>, + fail_close_once: Arc>>, + retried_games: Arc>>, + fail_retry_lookup_once: Arc>>, + fail_resolve_once: Arc>>, + resolution_attempts: Arc>>, + parents: Arc>>, } impl MockBondClient { @@ -195,13 +209,15 @@ impl MockBondClient { resolution_statuses: Arc::default(), resolutions: Arc::default(), unfinalized_games: Arc::default(), - credit: Arc::default(), - pending: Arc::default(), - latest_l1_timestamp: Arc::default(), - unlocks: Arc::default(), - withdrawals: Arc::default(), + settled_games: Arc::default(), + closes: Arc::default(), fail_game_at_once: Arc::default(), - fail_claim_once: Arc::default(), + fail_close_once: Arc::default(), + retried_games: Arc::default(), + fail_retry_lookup_once: Arc::default(), + fail_resolve_once: Arc::default(), + resolution_attempts: Arc::default(), + parents: Arc::default(), } } } @@ -258,14 +274,29 @@ impl BondManagerClient for MockBondClient { } async fn resolution_status(&self, game: Address) -> Result { - if let Some(status) = self - .resolution_statuses - .lock() - .expect("not poisoned") - .get(&game) - .copied() { - return Ok(status); + let statuses = self.resolution_statuses.lock().expect("not poisoned"); + if let Some(mut status) = statuses.get(&game).copied() { + if !status.is_resolved() + && let Some(parent) = self.parents.lock().expect("not poisoned").get(&game) + { + match statuses.get(parent).expect("parent status exists").status { + GameStatus::ChallengerWins => { + status.resolvable = true; + status.outcome = GameStatus::ChallengerWins; + status.invalidation_reason = InvalidationReason::InvalidParent; + } + GameStatus::InProgress => { + status.resolvable = false; + if status.outcome == GameStatus::DefenderWins { + status.outcome = GameStatus::InProgress; + } + } + GameStatus::DefenderWins => {} + } + } + return Ok(status); + } } let resolved = self .resolved_games @@ -273,6 +304,11 @@ impl BondManagerClient for MockBondClient { .expect("not poisoned") .contains(&game); Ok(ResolutionStatus { + status: if resolved { + GameStatus::DefenderWins + } else { + GameStatus::InProgress + }, resolvable: false, outcome: if resolved { GameStatus::DefenderWins @@ -284,16 +320,30 @@ impl BondManagerClient for MockBondClient { } async fn resolve_game(&self, game: Address) -> Result { - let mut statuses = self.resolution_statuses.lock().expect("not poisoned"); - let status = statuses - .get_mut(&game) - .ok_or_else(|| ProposerError::message(format!("game {game} is not resolvable")))?; + self.resolution_attempts + .lock() + .expect("not poisoned") + .push(game); + if self + .fail_resolve_once + .lock() + .expect("not poisoned") + .remove(&game) + { + return Err(ProposerError::message("injected resolve failure")); + } + let mut status = self.resolution_status(game).await?; if !status.resolvable { return Err(ProposerError::message(format!( "game {game} is not resolvable" ))); } status.resolvable = false; + status.status = status.outcome; + self.resolution_statuses + .lock() + .expect("not poisoned") + .insert(game, status); self.resolutions.lock().expect("not poisoned").push(game); Ok(ResolveSubmission { tx_hash: B256::repeat_byte(0xbb), @@ -301,6 +351,9 @@ impl BondManagerClient for MockBondClient { } async fn is_game_finalized(&self, game: Address) -> Result { + if !self.resolution_status(game).await?.is_resolved() { + return Ok(false); + } Ok(!self .unfinalized_games .lock() @@ -308,75 +361,46 @@ impl BondManagerClient for MockBondClient { .contains(&game)) } - async fn credit(&self, game: Address) -> Result { + async fn has_retry(&self, game: Address) -> Result { + if self + .fail_retry_lookup_once + .lock() + .expect("not poisoned") + .remove(&game) + { + return Err(ProposerError::message("injected retry lookup failure")); + } Ok(self - .credit + .retried_games .lock() .expect("not poisoned") - .get(&game) - .copied() - .unwrap_or_default()) + .contains(&game)) } - async fn pending_withdrawal(&self, game: Address) -> Result { + async fn is_game_settled(&self, game: Address) -> Result { Ok(self - .pending + .settled_games .lock() .expect("not poisoned") - .get(&game) - .copied() - .unwrap_or_default()) - } - - async fn latest_l1_timestamp(&self) -> Result { - Ok(self.latest_l1_timestamp.load(Ordering::SeqCst)) + .contains(&game)) } - async fn claim_credit(&self, game: Address) -> Result { + async fn close_game(&self, game: Address) -> Result { if self - .fail_claim_once + .fail_close_once .lock() .expect("not poisoned") .remove(&game) { - return Err(ProposerError::message("injected claim failure")); - } - - let credit = self - .credit - .lock() - .expect("not poisoned") - .remove(&game) - .unwrap_or_default(); - if credit > U256::ZERO { - // Phase 1: unlock in DelayedWETH, immediately withdrawable in tests. - self.pending.lock().expect("not poisoned").insert( - game, - PendingWithdrawal { - amount: credit, - unlock_at: 0, - }, - ); - self.unlocks.lock().expect("not poisoned").push(game); - return Ok(ClaimSubmission { - tx_hash: B256::repeat_byte(0xdd), - amount: credit, - withdrawn: false, - }); + return Err(ProposerError::message("injected close failure")); } - - // Phase 2: drain the pending withdrawal. - let pending = self - .pending + self.settled_games .lock() .expect("not poisoned") - .remove(&game) - .unwrap_or_default(); - self.withdrawals.lock().expect("not poisoned").push(game); - Ok(ClaimSubmission { + .insert(game); + self.closes.lock().expect("not poisoned").push(game); + Ok(CloseGameSubmission { tx_hash: B256::repeat_byte(0xde), - amount: pending.amount, - withdrawn: true, }) } } @@ -403,6 +427,7 @@ impl ConsensusProvider for MockOutputRoots { fn config() -> ProposerConfig { ProposerConfig { + recovery_parent: None, poll_interval: Duration::from_secs(1), max_resolutions_per_tick: 1, } @@ -417,6 +442,7 @@ async fn advance_proposal( fn positive_ready_status() -> ResolutionStatus { ResolutionStatus { + status: GameStatus::InProgress, resolvable: true, outcome: GameStatus::DefenderWins, invalidation_reason: InvalidationReason::None, @@ -439,6 +465,7 @@ fn anchor_advanced_onto(anchor_game: Address, l2_block_number: u64) -> LineageAn fn timed_out_status() -> ResolutionStatus { ResolutionStatus { + status: GameStatus::ChallengerWins, resolvable: false, outcome: GameStatus::ChallengerWins, invalidation_reason: InvalidationReason::ProofTimeout, @@ -447,6 +474,7 @@ fn timed_out_status() -> ResolutionStatus { fn negatively_resolvable_timeout() -> ResolutionStatus { ResolutionStatus { + status: GameStatus::InProgress, resolvable: true, outcome: GameStatus::ChallengerWins, invalidation_reason: InvalidationReason::ProofTimeout, @@ -487,6 +515,7 @@ fn bond_manager_config(initial_scan_limit: u64) -> BondManagerConfig { BondManagerConfig { poll_interval: Duration::from_secs(1), initial_scan_limit, + ..BondManagerConfig::default() } } @@ -715,6 +744,7 @@ async fn resolve_games_caps_submissions_and_keeps_scanning_resolved_games() { ( game_3, ResolutionStatus { + status: GameStatus::DefenderWins, resolvable: false, outcome: GameStatus::DefenderWins, invalidation_reason: InvalidationReason::None, @@ -767,6 +797,7 @@ async fn advance_anchor_skips_newer_game_that_is_not_yet_valid() { ( GAME_1, ResolutionStatus { + status: GameStatus::DefenderWins, resolvable: false, outcome: GameStatus::DefenderWins, invalidation_reason: InvalidationReason::None, @@ -775,6 +806,7 @@ async fn advance_anchor_skips_newer_game_that_is_not_yet_valid() { ( game_2, ResolutionStatus { + status: GameStatus::DefenderWins, resolvable: false, outcome: GameStatus::DefenderWins, invalidation_reason: InvalidationReason::None, @@ -783,6 +815,7 @@ async fn advance_anchor_skips_newer_game_that_is_not_yet_valid() { ( game_3, ResolutionStatus { + status: GameStatus::DefenderWins, resolvable: false, outcome: GameStatus::DefenderWins, invalidation_reason: InvalidationReason::None, @@ -827,6 +860,7 @@ async fn resolved_games_do_not_consume_resolution_budget() { ( GAME_1, ResolutionStatus { + status: GameStatus::DefenderWins, resolvable: false, outcome: GameStatus::DefenderWins, invalidation_reason: InvalidationReason::None, @@ -972,25 +1006,25 @@ async fn bond_manager_retries_complete_range_after_partial_scan_failure() { } #[tokio::test] -async fn bond_manager_prunes_resolved_games_and_retries_failed_claims() { +async fn bond_manager_settles_finalized_games_and_retries_failed_closes() { let proposer = Address::repeat_byte(0xa1); let unresolved = game_address(1); - let zero_credit = game_address(2); - let claimable = game_address(3); - let retry_claim = game_address(4); + let already_settled = game_address(2); + let closable = game_address(3); + let retry_close = game_address(4); let awaiting_airgap = game_address(5); let games = vec![ (unresolved, proposer), - (zero_credit, proposer), - (claimable, proposer), - (retry_claim, proposer), + (already_settled, proposer), + (closable, proposer), + (retry_close, proposer), (awaiting_airgap, proposer), ]; let client = MockBondClient::new(proposer, games); client.resolved_games.lock().expect("not poisoned").extend([ - zero_credit, - claimable, - retry_claim, + already_settled, + closable, + retry_close, awaiting_airgap, ]); client @@ -998,60 +1032,41 @@ async fn bond_manager_prunes_resolved_games_and_retries_failed_claims() { .lock() .expect("not poisoned") .insert(awaiting_airgap); - client.credit.lock().expect("not poisoned").extend([ - (claimable, U256::from(10)), - (retry_claim, U256::from(20)), - (awaiting_airgap, U256::from(30)), - ]); client - .fail_claim_once + .settled_games .lock() .expect("not poisoned") - .insert(retry_claim); + .insert(already_settled); + client + .fail_close_once + .lock() + .expect("not poisoned") + .insert(retry_close); let mut manager = BondManager::new(bond_manager_config(100), client.clone()); manager.scan_games().await.unwrap(); - // Pass 1: only `claimable` advances, and only through the DelayedWETH unlock. manager.settle_games().await.unwrap(); assert!(manager.tracks_game(unresolved)); - assert!(!manager.tracks_game(zero_credit)); - assert!( - manager.tracks_game(claimable), - "unlocked bond must stay tracked" - ); - assert!(manager.tracks_game(retry_claim)); + assert!(!manager.tracks_game(already_settled)); + assert!(!manager.tracks_game(closable)); + assert!(manager.tracks_game(retry_close)); assert!( manager.tracks_game(awaiting_airgap), "a game inside the finality airgap must stay tracked" ); - assert_eq!( - *client.unlocks.lock().expect("not poisoned"), - vec![claimable] - ); - assert!(client.withdrawals.lock().expect("not poisoned").is_empty()); - - // Pass 2: `claimable` withdraws and is dropped; the failed claim is retried and unlocks. - manager.settle_games().await.unwrap(); - - assert!(!manager.tracks_game(claimable)); - assert!(manager.tracks_game(retry_claim)); - assert_eq!( - *client.withdrawals.lock().expect("not poisoned"), - vec![claimable] - ); + assert_eq!(*client.closes.lock().expect("not poisoned"), vec![closable]); - // Pass 3: the retried claim withdraws and is dropped. manager.settle_games().await.unwrap(); - assert!(!manager.tracks_game(retry_claim)); - let withdrawals = client.withdrawals.lock().expect("not poisoned"); - assert!(withdrawals.contains(&claimable)); - assert!(withdrawals.contains(&retry_claim)); + assert!(!manager.tracks_game(retry_close)); + let closes = client.closes.lock().expect("not poisoned"); + assert!(closes.contains(&closable)); + assert!(closes.contains(&retry_close)); } #[tokio::test] -async fn bond_manager_resolves_invalid_parent_before_claiming_refund() { +async fn bond_manager_resolves_invalid_parent_before_settlement() { let proposer = Address::repeat_byte(0xa1); let game = game_address(1); let client = MockBondClient::new(proposer, vec![(game, proposer)]); @@ -1062,16 +1077,12 @@ async fn bond_manager_resolves_invalid_parent_before_claiming_refund() { .insert( game, ResolutionStatus { + status: GameStatus::InProgress, resolvable: true, outcome: GameStatus::ChallengerWins, invalidation_reason: InvalidationReason::InvalidParent, }, ); - client - .credit - .lock() - .expect("not poisoned") - .insert(game, U256::from(10)); let mut manager = BondManager::new(bond_manager_config(100), client.clone()); manager.scan_games().await.unwrap(); @@ -1080,18 +1091,11 @@ async fn bond_manager_resolves_invalid_parent_before_claiming_refund() { *client.resolutions.lock().expect("not poisoned"), vec![game] ); - assert!(client.unlocks.lock().expect("not poisoned").is_empty()); + assert!(client.closes.lock().expect("not poisoned").is_empty()); assert!(manager.tracks_game(game)); manager.settle_games().await.unwrap(); - assert_eq!(*client.unlocks.lock().expect("not poisoned"), vec![game]); - assert!(manager.tracks_game(game)); - - manager.settle_games().await.unwrap(); - assert_eq!( - *client.withdrawals.lock().expect("not poisoned"), - vec![game] - ); + assert_eq!(*client.closes.lock().expect("not poisoned"), vec![game]); assert!(!manager.tracks_game(game)); } @@ -1107,6 +1111,7 @@ async fn bond_manager_leaves_direct_proof_timeout_to_lineage_proposer() { .insert( game, ResolutionStatus { + status: GameStatus::InProgress, resolvable: true, outcome: GameStatus::ChallengerWins, invalidation_reason: InvalidationReason::ProofTimeout, @@ -1121,6 +1126,160 @@ async fn bond_manager_leaves_direct_proof_timeout_to_lineage_proposer() { assert!(manager.tracks_game(game)); } +#[tokio::test] +async fn bond_manager_recovers_superseded_timeout_and_its_descendants() { + let owner = Address::repeat_byte(0xa1); + let parent = game_address(10); + let old_attempt = game_address(11); + let child = game_address(12); + let grandchild = game_address(13); + let client = MockBondClient::new( + owner, + vec![(old_attempt, owner), (child, owner), (grandchild, owner)], + ); + client.parents.lock().unwrap().extend([ + (old_attempt, parent), + (child, old_attempt), + (grandchild, child), + ]); + client.retried_games.lock().unwrap().insert(old_attempt); + client.resolution_statuses.lock().unwrap().extend([ + (parent, positive_ready_status()), + (old_attempt, negatively_resolvable_timeout()), + (child, positive_ready_status()), + (grandchild, positive_ready_status()), + ]); + client + .unfinalized_games + .lock() + .unwrap() + .extend([old_attempt, child, grandchild]); + + // Discover the superseded attempt from the factory, including after a process restart. + let mut manager = BondManager::new(bond_manager_config(100), client.clone()); + manager.scan_games().await.unwrap(); + manager.settle_games().await.unwrap(); + let waiting = client.resolution_status(old_attempt).await.unwrap(); + assert_eq!(waiting.outcome, GameStatus::ChallengerWins); + assert!(!waiting.is_resolved()); + assert!(client.resolution_attempts.lock().unwrap().is_empty()); + assert!(client.closes.lock().unwrap().is_empty()); + + // The selected branch resolves the parent; cleanup must resolve the skipped attempt. + client + .resolution_statuses + .lock() + .unwrap() + .get_mut(&parent) + .unwrap() + .status = GameStatus::DefenderWins; + manager.settle_games().await.unwrap(); + assert_eq!( + *client.resolutions.lock().unwrap(), + vec![old_attempt, child, grandchild] + ); + for game in [child, grandchild] { + let status = client.resolution_status(game).await.unwrap(); + assert!(status.is_resolved()); + assert_eq!( + status.invalidation_reason, + InvalidationReason::InvalidParent + ); + } + manager.settle_games().await.unwrap(); + assert!( + client.closes.lock().unwrap().is_empty(), + "respect the finality airgap" + ); + + client.unfinalized_games.lock().unwrap().clear(); + manager.settle_games().await.unwrap(); + assert_eq!(client.closes.lock().unwrap().len(), 3); + for game in [old_attempt, child, grandchild] { + assert!(!manager.tracks_game(game)); + } +} + +#[tokio::test] +async fn bond_manager_bounds_retry_resolutions_and_rotates_after_failure() { + let owner = Address::repeat_byte(0xa1); + let first = game_address(1); + let second = game_address(2); + let client = MockBondClient::new(owner, vec![(first, owner), (second, owner)]); + client.retried_games.lock().unwrap().extend([first, second]); + client.resolution_statuses.lock().unwrap().extend([ + (first, negatively_resolvable_timeout()), + (second, negatively_resolvable_timeout()), + ]); + client.fail_resolve_once.lock().unwrap().insert(first); + let mut manager = BondManager::new(bond_manager_config(100), client.clone()); + manager.scan_games().await.unwrap(); + + manager.settle_games().await.unwrap(); + assert_eq!(*client.resolution_attempts.lock().unwrap(), vec![first]); + assert!(client.resolutions.lock().unwrap().is_empty()); + + manager.settle_games().await.unwrap(); + assert_eq!( + *client.resolution_attempts.lock().unwrap(), + vec![first, second] + ); + assert!(manager.tracks_game(first)); + + manager.settle_games().await.unwrap(); + assert_eq!( + *client.resolution_attempts.lock().unwrap(), + vec![first, second, first] + ); + assert!(!manager.tracks_game(second)); + manager.settle_games().await.unwrap(); + assert!(!manager.tracks_game(first)); +} + +#[tokio::test] +async fn bond_manager_retries_failed_successor_lookup_without_stalling_other_games() { + let owner = Address::repeat_byte(0xa1); + let first = game_address(1); + let second = game_address(2); + let client = MockBondClient::new(owner, vec![(first, owner), (second, owner)]); + client.retried_games.lock().unwrap().extend([first, second]); + client.resolution_statuses.lock().unwrap().extend([ + (first, negatively_resolvable_timeout()), + (second, negatively_resolvable_timeout()), + ]); + client.fail_retry_lookup_once.lock().unwrap().insert(first); + let mut manager = BondManager::new(bond_manager_config(100), client.clone()); + manager.scan_games().await.unwrap(); + manager.settle_games().await.unwrap(); + assert_eq!(*client.resolutions.lock().unwrap(), vec![second]); + assert!(manager.tracks_game(first)); + manager.settle_games().await.unwrap(); + assert_eq!(*client.resolutions.lock().unwrap(), vec![second, first]); +} + +#[tokio::test] +async fn bond_manager_can_disable_retry_cleanup_without_disabling_settlement() { + let owner = Address::repeat_byte(0xa1); + let old_attempt = game_address(1); + let finalized = game_address(2); + let client = MockBondClient::new(owner, vec![(old_attempt, owner), (finalized, owner)]); + client.retried_games.lock().unwrap().insert(old_attempt); + client + .resolution_statuses + .lock() + .unwrap() + .insert(old_attempt, negatively_resolvable_timeout()); + client.resolved_games.lock().unwrap().insert(finalized); + let mut config = bond_manager_config(100); + config.max_retry_resolutions_per_tick = 0; + let mut manager = BondManager::new(config, client.clone()); + manager.scan_games().await.unwrap(); + manager.settle_games().await.unwrap(); + assert!(client.resolution_attempts.lock().unwrap().is_empty()); + assert!(manager.tracks_game(old_attempt)); + assert_eq!(*client.closes.lock().unwrap(), vec![finalized]); +} + #[tokio::test] async fn bond_manager_resolves_proof_timeout_from_obsolete_domain() { let proposer = Address::repeat_byte(0xa1); @@ -1163,11 +1322,6 @@ async fn bond_manager_resolves_positive_game_from_obsolete_domain() { .lock() .expect("not poisoned") .insert(game, positive_ready_status()); - client - .credit - .lock() - .expect("not poisoned") - .insert(game, U256::from(10)); let mut manager = BondManager::new(bond_manager_config(100), client.clone()); manager.scan_games().await.unwrap(); @@ -1180,14 +1334,7 @@ async fn bond_manager_resolves_positive_game_from_obsolete_domain() { assert!(manager.tracks_game(game)); manager.settle_games().await.unwrap(); - assert_eq!(*client.unlocks.lock().expect("not poisoned"), vec![game]); - assert!(manager.tracks_game(game)); - - manager.settle_games().await.unwrap(); - assert_eq!( - *client.withdrawals.lock().expect("not poisoned"), - vec![game] - ); + assert_eq!(*client.closes.lock().expect("not poisoned"), vec![game]); assert!(!manager.tracks_game(game)); } @@ -1208,7 +1355,7 @@ async fn bond_manager_skips_foreign_game_types() { } #[tokio::test] -async fn bond_manager_uses_l1_timestamp_for_delayed_withdrawal() { +async fn bond_manager_prunes_an_already_settled_game_without_closing_again() { let proposer = Address::repeat_byte(0xa1); let game = game_address(1); let client = MockBondClient::new(proposer, vec![(game, proposer)]); @@ -1217,28 +1364,82 @@ async fn bond_manager_uses_l1_timestamp_for_delayed_withdrawal() { .lock() .expect("not poisoned") .insert(game); - client.pending.lock().expect("not poisoned").insert( - game, - PendingWithdrawal { - amount: U256::from(10), - unlock_at: 100, - }, - ); - client.latest_l1_timestamp.store(99, Ordering::SeqCst); + client + .settled_games + .lock() + .expect("not poisoned") + .insert(game); let mut manager = BondManager::new(bond_manager_config(100), client.clone()); manager.scan_games().await.unwrap(); manager.settle_games().await.unwrap(); - assert!(manager.tracks_game(game)); - assert!(client.withdrawals.lock().expect("not poisoned").is_empty()); - - client.latest_l1_timestamp.store(100, Ordering::SeqCst); - manager.settle_games().await.unwrap(); assert!(!manager.tracks_game(game)); + assert!(client.closes.lock().expect("not poisoned").is_empty()); +} + +#[tokio::test] +async fn proposer_retries_parent_gated_timeout_and_skips_old_descendants() { + let parent = game_address(90); + let old_attempt = game_address(91); + let descendant = game_address(92); + let root_10 = B256::repeat_byte(0x10); + let root_20 = B256::repeat_byte(0x20); + let root_30 = B256::repeat_byte(0x30); + let contracts = MockContracts { + anchor: anchor_at(0), + games: Arc::new(Mutex::new(HashMap::from([ + (game_uuid(ANCHOR, root_10, 10, 0), parent), + (game_uuid(parent, root_20, 20, 0), old_attempt), + (game_uuid(old_attempt, root_30, 30, 0), descendant), + ]))), + submissions: Arc::default(), + resolution_statuses: Arc::new(Mutex::new(HashMap::from([( + old_attempt, + ResolutionStatus { + status: GameStatus::InProgress, + ..timed_out_status() + }, + )]))), + resolutions: Arc::default(), + closures: Arc::default(), + submission_failures: Arc::default(), + unfinalized_games: Arc::default(), + }; + let proposer = WorldChainProposer::new( + config(), + contracts.clone(), + MockOutputRoots { + roots: HashMap::from([(10, root_10), (20, root_20), (30, root_30)]), + finalized_l2_block: 30, + }, + ); + let scan = proposer.scan_selected_lineage().await.unwrap(); + assert_eq!(scan.lineage().games().len(), 1); assert_eq!( - *client.withdrawals.lock().expect("not poisoned"), - vec![game] + scan.next_action(), + &NextProposalAction::RetryTimedOut { + proposal: Proposal { + parent_ref: parent, + root_claim: root_20, + l2_block_number: 20, + attempt: 1 + }, + invalidated_game: old_attempt, + } + ); + proposer.submit_next_proposal(&scan).await.unwrap(); + let next_scan = proposer.scan_selected_lineage().await.unwrap(); + assert_eq!(next_scan.lineage().games().len(), 2); + assert_eq!(next_scan.lineage().games()[1].game.attempt, 1); + assert!( + next_scan + .lineage() + .games() + .iter() + .all(|selected| selected.game.address != old_attempt + && selected.game.address != descendant) ); + assert!(contracts.resolutions.lock().unwrap().is_empty()); } #[tokio::test] @@ -1326,3 +1527,38 @@ async fn timed_out_game_bumps_attempt_while_its_parent_is_still_acceptable() { } ); } + +#[tokio::test] +async fn recovery_proposes_from_override_instead_of_unusable_anchor() { + let submissions = Arc::default(); + let contracts = MockContracts { + anchor: LineageAnchor { + address: GAME_1, + l2_block_number: 10, + }, + games: Arc::default(), + submissions: Arc::clone(&submissions), + resolution_statuses: Arc::default(), + resolutions: Arc::default(), + closures: Arc::default(), + submission_failures: Arc::default(), + unfinalized_games: Arc::new(Mutex::new(HashSet::from([GAME_1]))), + }; + let proposer = WorldChainProposer::new( + ProposerConfig { + recovery_parent: Some(ANCHOR), + ..config() + }, + contracts, + MockOutputRoots { + roots: HashMap::from([(0, B256::ZERO), (10, B256::repeat_byte(0x10))]), + finalized_l2_block: 10, + }, + ); + let scan = proposer.scan_selected_lineage().await.unwrap(); + advance_proposal(&proposer, &scan).await.unwrap(); + let proposal = submissions.lock().expect("not poisoned")[0]; + assert_eq!(proposal.parent_ref, ANCHOR); + assert_eq!(proposal.l2_block_number, 10); + assert_eq!(proposal.attempt, 0); +} diff --git a/proofs/services/proposer/src/traits.rs b/proofs/services/proposer/src/traits.rs index 20f8686b6..f96f85de7 100644 --- a/proofs/services/proposer/src/traits.rs +++ b/proofs/services/proposer/src/traits.rs @@ -1,16 +1,16 @@ -use alloy_primitives::{Address, B256, U256}; +use alloy_primitives::{Address, B256}; use async_trait::async_trait; use world_chain_proof_protocol::{LineageProvider, ResolutionStatus}; use crate::{ Proposal, ProposalSubmission, ProposerError, - types::{ClaimSubmission, CloseGameSubmission, PendingWithdrawal, ResolveSubmission}, + types::{CloseGameSubmission, ResolveSubmission}, }; /// Contract surface needed by the asynchronous bond manager. #[async_trait] pub trait BondManagerClient: Send + Sync { - /// Returns the address whose proposal credits are managed. + /// Returns the proposer whose games are managed for bond settlement. fn proposer_address(&self) -> Address; /// Returns the proposal domain currently registered for WIP-1006. @@ -24,12 +24,15 @@ pub trait BondManagerClient: Send + Sync { /// holds a game of a different type. async fn game_at(&self, index: u64) -> Result, ProposerError>; - /// Returns the account that created the provided game. + /// Returns the account that created and bonded the provided game. async fn game_creator(&self, game: Address) -> Result; /// Returns the proposal domain embedded in the provided game. async fn game_domain_hash(&self, game: Address) -> Result; + /// Returns whether a newer attempt exists for the game's exact transition and domain. + async fn has_retry(&self, game: Address) -> Result; + /// Returns the resolution status of the provided game. async fn resolution_status(&self, game: Address) -> Result; @@ -37,21 +40,11 @@ pub trait BondManagerClient: Send + Sync { async fn resolve_game(&self, game: Address) -> Result; /// Returns whether the registry's finality airgap has elapsed for the provided game. - /// - /// `claimCredit` calls `closeGame`, which reverts until this holds. async fn is_game_finalized(&self, game: Address) -> Result; - - /// Returns the credit the managed proposer can unlock from the provided game. - async fn credit(&self, game: Address) -> Result; - - /// Returns the managed proposer's pending `DelayedWETH` withdrawal for the provided game. - async fn pending_withdrawal(&self, game: Address) -> Result; - - /// Returns the latest L1 block timestamp used by `DelayedWETH`. - async fn latest_l1_timestamp(&self) -> Result; - - /// Advances the managed proposer's two-phase bond claim on the provided game. - async fn claim_credit(&self, game: Address) -> Result; + /// Returns whether the game's complete bond pot has already been settled. + async fn is_game_settled(&self, game: Address) -> Result; + /// Settles the game's complete bond pot into reusable vault balances. + async fn close_game(&self, game: Address) -> Result; } /// Minimal contract surface needed by the proposer. diff --git a/proofs/services/proposer/src/types.rs b/proofs/services/proposer/src/types.rs index 92c1d3d4e..6403aa9a5 100644 --- a/proofs/services/proposer/src/types.rs +++ b/proofs/services/proposer/src/types.rs @@ -1,15 +1,7 @@ -use alloy_primitives::{Address, B256, TxHash, U256}; +use alloy_primitives::{Address, B256, TxHash}; +use serde::{Deserialize, Serialize}; use world_chain_proof_protocol::{InvalidationReason, ProposalCommitment, SelectedLineage}; -/// A pending `DelayedWETH` withdrawal opened by the first `claimCredit` call. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] -pub struct PendingWithdrawal { - /// Amount unlocked in `DelayedWETH` and awaiting the withdrawal delay. - pub amount: U256, - /// Unix timestamp at which the unlocked amount becomes withdrawable. - pub unlock_at: u64, -} - /// The selected lineage discovered by the proposer and the action available at its tip. #[derive(Debug)] pub struct ProposerScan { @@ -100,7 +92,7 @@ impl Proposal { } /// Result of a submitted proposal transaction. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] pub struct ProposalSubmission { /// Transaction hash for the proposal submission. pub tx_hash: TxHash, @@ -121,17 +113,3 @@ pub struct CloseGameSubmission { /// Transaction hash for the closeGame submission. pub tx_hash: TxHash, } - -/// Result of a `claimCredit` transaction. -/// -/// Bond payout is two-phase: the first call unlocks the credit in `DelayedWETH`, the second -/// (after the WETH delay) withdraws and transfers it. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct ClaimSubmission { - /// Transaction hash for the claim. - pub tx_hash: TxHash, - /// Amount moved by this phase. - pub amount: U256, - /// Whether this call finalized the withdrawal and transferred funds. - pub withdrawn: bool, -} diff --git a/proofs/services/prover-service/Cargo.toml b/proofs/services/prover-service/Cargo.toml index 0067b3faf..9ec6500ee 100644 --- a/proofs/services/prover-service/Cargo.toml +++ b/proofs/services/prover-service/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "world-chain-prover-service" -version = "1.0.0-rc.1" +version = "1.0.0-rc.5" edition.workspace = true rust-version.workspace = true license.workspace = true @@ -17,9 +17,11 @@ workspace = true [dependencies] # workspace world-chain-proof-metrics.workspace = true +world-chain-proof-protocol.workspace = true # alloy alloy-primitives = { workspace = true, features = ["serde"] } +alloy-provider.workspace = true # misc anyhow.workspace = true @@ -39,6 +41,8 @@ uuid.workspace = true auto_impl.workspace = true [dev-dependencies] +alloy-sol-types.workspace = true +alloy-transport.workspace = true testcontainers.workspace = true testcontainers-modules.workspace = true tokio = { workspace = true, features = ["macros", "rt-multi-thread", "time"] } diff --git a/proofs/services/prover-service/README.md b/proofs/services/prover-service/README.md new file mode 100644 index 000000000..6a6b82d28 --- /dev/null +++ b/proofs/services/prover-service/README.md @@ -0,0 +1,17 @@ +# World Chain Prover Service + +The prover-service persists proof requests and worker leases in Postgres. Workers claim jobs +over JSON-RPC and heartbeat while proving. The defender requests proofs and submits them on-chain. + +The service requires `PROVER_SERVICE_DATABASE_URL` and `L1_RPC_URL`. Set `L1_FALLBACK_RPC_URL` +to use the same shared RPC fallback client as the other proof services. `L1_RPC_TIMEOUT_SECONDS` +sets the per-request timeout (default: 10 seconds). Every +`STATUS_POLLER_INTERVAL_SECS` (default: 30 seconds), it checks active jobs against L1 and cancels +them when the game has sufficient proof support or its resolution outcome is no longer in progress. +Failed L1 reads leave jobs untouched. The same loop fails jobs that exhausted their worker attempts. + +Cancellation revokes worker leases while preserving completed proofs and backend session records. +Workers stop local work on their next heartbeat; already submitted remote proving requests are not +cancelled at the backend. A new defender request can resume a cancelled proof using existing backend +sessions without consuming a failure retry, for example after a supported game is challenged or +an L1 reorg. diff --git a/proofs/services/prover-service/migrations/20260619_proof_requests.sql b/proofs/services/prover-service/migrations/20260619_proof_requests.sql index 1e70a9843..ade4da8ea 100644 --- a/proofs/services/prover-service/migrations/20260619_proof_requests.sql +++ b/proofs/services/prover-service/migrations/20260619_proof_requests.sql @@ -24,7 +24,7 @@ CREATE TABLE proof_requests ( finished_at TIMESTAMPTZ NULL, CONSTRAINT proof_requests_status_check - CHECK (proof_status IN ('CREATED', 'RUNNING', 'SUCCEEDED', 'FAILED')), + CHECK (proof_status IN ('CREATED', 'RUNNING', 'SUCCEEDED', 'FAILED', 'CANCELLED')), CONSTRAINT proof_requests_job_status_check CHECK (job_status IN ('PENDING', 'CLAIMED', 'SUCCEEDED', 'FAILED')) diff --git a/proofs/services/prover-service/src/main.rs b/proofs/services/prover-service/src/main.rs index 5f643bb73..56318f6a6 100644 --- a/proofs/services/prover-service/src/main.rs +++ b/proofs/services/prover-service/src/main.rs @@ -8,6 +8,7 @@ use std::{net::SocketAddr, sync::Arc, time::Duration}; +use alloy_provider::ProviderBuilder; use anyhow::{Context, Result}; use clap::Parser; use tracing::info; @@ -21,6 +22,18 @@ use world_chain_prover_service::{ about = "World Chain proof-request queue: serves proof jobs to SP1 workers over JSON-RPC" )] struct Cli { + /// Ethereum L1 execution RPC URL used to check whether queued proofs are still needed. + #[arg(long, env = "L1_RPC_URL")] + l1_rpc: String, + + /// Optional fallback Ethereum L1 execution RPC URL. + #[arg(long, env = "L1_FALLBACK_RPC_URL")] + l1_fallback_rpc: Option, + + /// Per-request timeout for L1 RPC calls in seconds. + #[arg(long, env = "L1_RPC_TIMEOUT_SECONDS", default_value_t = world_chain_proof_metrics::DEFAULT_RPC_REQUEST_TIMEOUT_SECONDS)] + l1_rpc_timeout_seconds: u64, + /// Address the JSON-RPC server binds to. #[arg(long, env = "LISTEN_ADDR", default_value = "0.0.0.0:8080")] listen_addr: SocketAddr, @@ -45,8 +58,8 @@ struct Cli { #[arg(long, env = "BACKEND_POLL_INTERVAL_SECONDS", default_value_t = 30)] backend_poll_interval_seconds: u64, - /// Seconds between scans that fail proof requests after exhausted attempts. - #[arg(long, env = "STATUS_POLLER_INTERVAL_SECS", default_value_t = 30)] + /// Seconds between scans that cancel obsolete jobs and fail exhausted attempts. + #[arg(long, env = "STATUS_POLLER_INTERVAL_SECS", default_value_t = world_chain_prover_service::DEFAULT_STATUS_POLLER_INTERVAL.as_secs())] status_poller_interval_secs: u64, } @@ -58,6 +71,22 @@ async fn main() -> Result<()> { world_chain_proof_metrics::describe_metrics(); let cli = Cli::parse(); + let l1_fallback_rpc_url = cli + .l1_fallback_rpc + .as_deref() + .map(str::parse) + .transpose() + .context("invalid L1 fallback RPC URL")?; + let l1_rpc_client = world_chain_proof_metrics::metered_http_client( + cli.l1_rpc.parse().context("invalid L1 RPC URL")?, + l1_fallback_rpc_url, + world_chain_proof_metrics::RPC_TARGET_L1_EXECUTION, + Duration::from_secs(cli.l1_rpc_timeout_seconds), + ) + .context("failed to build the L1 RPC client")?; + let provider = ProviderBuilder::new() + .disable_recommended_fillers() + .connect_client(l1_rpc_client); let config = ProverServiceConfig { lock_timeout: Duration::from_secs(cli.lease_timeout_seconds), @@ -76,9 +105,14 @@ async fn main() -> Result<()> { .await .context("failed to start prover-service RPC server")?; - let status_poller = tokio::spawn(run_status_poller(service, status_poller_interval)); + let status_poller = tokio::spawn(run_status_poller(service, provider, status_poller_interval)); - info!(listen_addr = %addr, "world-chain prover-service started"); + info!( + listen_addr = %addr, + l1_fallback_rpc_configured = cli.l1_fallback_rpc.is_some(), + l1_rpc_timeout_seconds = cli.l1_rpc_timeout_seconds, + "world-chain prover-service started" + ); tokio::select! { _ = handle.clone().stopped() => info!("prover-service RPC server stopped"), diff --git a/proofs/services/prover-service/src/service.rs b/proofs/services/prover-service/src/service.rs index 4b62deeca..6721a18ff 100644 --- a/proofs/services/prover-service/src/service.rs +++ b/proofs/services/prover-service/src/service.rs @@ -10,6 +10,7 @@ use crate::{ SubmitProofRequest, SubmitProofResponse, }, }; +use alloy_primitives::Address; use async_trait::async_trait; use sqlx::{PgPool, migrate::MigrateError}; @@ -56,6 +57,14 @@ impl ProverService { pub(crate) async fn mark_exhausted_proof_requests_failed(&self) -> Result { self.store.mark_exhausted_proof_requests_failed().await } + + pub(crate) async fn active_games(&self) -> Result, ProofJobQueueError> { + self.store.active_games().await + } + + pub(crate) async fn cancel_game_proofs(&self, game: Address) -> Result { + self.store.cancel_game_proofs(game).await + } } #[async_trait] diff --git a/proofs/services/prover-service/src/status_poller.rs b/proofs/services/prover-service/src/status_poller.rs index 22982ffd6..eb456e4ba 100644 --- a/proofs/services/prover-service/src/status_poller.rs +++ b/proofs/services/prover-service/src/status_poller.rs @@ -1,18 +1,27 @@ use std::{sync::Arc, time::Duration}; +use alloy_primitives::Address; +use alloy_provider::Provider; use tokio::time::MissedTickBehavior; -use tracing::warn; +use tracing::{info, warn}; +use world_chain_proof_protocol::{GameStatus, IMultiProofGame, ProposalStatus}; use crate::ProverService; -/// Runs the periodic maintenance loop that terminalizes proof requests which -/// exhausted their worker attempts. -pub async fn run_status_poller(service: Arc, poll_interval: Duration) { +/// Cancels obsolete proof jobs and fails requests that exhausted their worker attempts. +pub async fn run_status_poller( + service: Arc, + provider: P, + poll_interval: Duration, +) { let mut interval = tokio::time::interval(poll_interval); interval.set_missed_tick_behavior(MissedTickBehavior::Delay); loop { interval.tick().await; + if let Err(error) = cancel_obsolete_proofs(&service, &provider).await { + warn!(%error, "obsolete proof scan failed"); + } match service.mark_exhausted_proof_requests_failed().await { Ok(0) => {} Ok(failed) => { @@ -27,3 +36,102 @@ pub async fn run_status_poller(service: Arc, poll_interval: Durat } } } + +async fn proof_is_obsolete( + provider: &P, + address: Address, +) -> anyhow::Result { + let game = IMultiProofGame::new(address, provider); + // One snapshot prevents a concurrent challenge from mixing old support with new state. + let (resolution, claim) = provider + .multicall() + .add(game.resolutionStatus()) + .add(game.claimData()) + .aggregate() + .await?; + let outcome = GameStatus::try_from(resolution.outcome)?; + let status = ProposalStatus::try_from(claim.status)?; + Ok(outcome != GameStatus::InProgress + || status.has_sufficient_proof_support() + || status == ProposalStatus::Resolved) +} + +pub(crate) async fn cancel_obsolete_proofs( + service: &ProverService, + provider: &P, +) -> anyhow::Result<()> { + for game in service.active_games().await? { + match proof_is_obsolete(provider, game).await { + Ok(true) => match service.cancel_game_proofs(game).await { + Ok(cancelled) if cancelled > 0 => { + info!(game_address = %game, cancelled, "cancelled obsolete proof requests"); + } + Ok(_) => {} + Err(error) => warn!(game_address = %game, %error, "proof cancellation failed"), + }, + Ok(false) => {} + Err(error) => { + warn!(game_address = %game, %error, "could not check proof support; retaining jobs") + } + } + } + Ok(()) +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + use alloy_primitives::{Bytes, U256}; + use alloy_provider::ProviderBuilder; + use alloy_sol_types::{SolCall, SolValue}; + use alloy_transport::mock::Asserter; + + pub(crate) fn push_game_state(asserter: &Asserter, outcome: u8, status: u8, bitmap: u8) { + let resolution = Bytes::from(IMultiProofGame::resolutionStatusCall::abi_encode_returns( + &IMultiProofGame::resolutionStatusReturn { + resolvable: false, + outcome, + reason: 0, + }, + )); + let claim = Bytes::from(IMultiProofGame::claimDataCall::abi_encode_returns( + &IMultiProofGame::claimDataReturn { + status, + challenger: Address::ZERO, + deadline: 0, + proofBitmap: bitmap, + invalidationReason: 0, + }, + )); + asserter.push_success(&Bytes::from( + (U256::from(100), vec![resolution, claim]).abi_encode_params(), + )); + } + + #[tokio::test] + async fn follows_contract_support_and_resolution_states() { + let asserter = Asserter::new(); + let provider = ProviderBuilder::new().connect_mocked_client(asserter.clone()); + for (outcome, status, bitmap, obsolete) in [ + (0, 0, 0, false), // Unchallenged, no support. + (0, 1, 4, false), // Challenged, council alone is below threshold. + (0, 2, 4, true), // Council satisfies an unchallenged game. + (0, 3, 6, true), // TEE plus council satisfies the threshold without SP1. + (1, 1, 0, true), // Invalidated or timed out, including with an open parent. + (2, 4, 5, true), // Resolved in the defender's favor. + ] { + push_game_state(&asserter, outcome, status, bitmap); + assert_eq!( + proof_is_obsolete(&provider, Address::ZERO).await.unwrap(), + obsolete, + "outcome={outcome}, status={status}, bitmap={bitmap}", + ); + } + for (outcome, status) in [(255, 0), (0, 255)] { + push_game_state(&asserter, outcome, status, 0); + assert!(proof_is_obsolete(&provider, Address::ZERO).await.is_err()); + } + asserter.push_failure_msg("L1 unavailable"); + assert!(proof_is_obsolete(&provider, Address::ZERO).await.is_err()); + } +} diff --git a/proofs/services/prover-service/src/store.rs b/proofs/services/prover-service/src/store.rs index cac99efd8..618e24701 100644 --- a/proofs/services/prover-service/src/store.rs +++ b/proofs/services/prover-service/src/store.rs @@ -1,3 +1,5 @@ +use std::str::FromStr; + use crate::{ ProofData, config::ProverServiceConfig, @@ -159,7 +161,7 @@ impl ProverServiceStore { }; let proof_status_str: &str = row.get("proof_status"); - let proof_status = ProofStatus::try_from(proof_status_str) + let proof_status = ProofStatus::from_str(proof_status_str) .map_err(ProofRequestError::UnknownProofStatus)?; if !request_matches(&row, &proof_request)? { @@ -177,10 +179,10 @@ impl ProverServiceStore { return Err(ProofRequestError::RequestMismatch(id)); } - if proof_status == ProofStatus::Failed { - // retry the entire proof job if retry_count is less than the max_retry + if matches!(proof_status, ProofStatus::Failed | ProofStatus::Cancelled) { + // A later challenge or reorg can require cancelled work again without a proof failure. let retry_count: i32 = row.get("retry_count"); - if retry_count > self.config.max_retries as i32 { + if proof_status == ProofStatus::Failed && retry_count > self.config.max_retries as i32 { tx.rollback().await?; return Err(ProofRequestError::TooManyRetries(TooManyRetriesErrorData { proof_id: id, @@ -193,7 +195,7 @@ impl ProverServiceStore { UPDATE proof_requests SET proof_status = $1, job_status = $2, - retry_count = retry_count + 1, + retry_count = retry_count + $5, l1_head = $3, failure_reason = NULL, proof_data = NULL, @@ -209,6 +211,7 @@ impl ProverServiceStore { .bind(ProofJobStatus::Pending.as_str()) .bind(proof_request.l1_head.as_slice()) .bind(&proof_id) + .bind(i32::from(proof_status == ProofStatus::Failed)) .execute(&mut *tx) .await?; @@ -219,9 +222,9 @@ impl ProverServiceStore { game_address = %proof_request.game, %backend, l2_block_number = proof_request.l2_block_number, - retry_count = retry_count + 1, + retry_count = retry_count + i32::from(proof_status == ProofStatus::Failed), max_retries = self.config.max_retries, - "re-queued failed proof request" + "re-queued proof request" ); let request_proof_response = RequestProofResponse { @@ -277,12 +280,14 @@ impl ProverServiceStore { proof, })) } - ProofStatus::Failed => Ok(ProofResponse::Failed(FailedProofResponse { - id: proof_id, - reason: row - .get::, _>("failure_reason") - .unwrap_or_else(|| "proof job failed".to_string()), - })), + ProofStatus::Failed | ProofStatus::Cancelled => { + Ok(ProofResponse::Failed(FailedProofResponse { + id: proof_id, + reason: row + .get::, _>("failure_reason") + .unwrap_or_else(|| "proof job failed".to_string()), + })) + } status => Ok(ProofResponse::Pending(PendingProofResponse { id: proof_id, status, @@ -290,6 +295,37 @@ impl ProverServiceStore { } } + pub(crate) async fn active_games(&self) -> Result, ProofJobQueueError> { + let games: Vec> = sqlx::query_scalar( + "SELECT DISTINCT game FROM proof_requests WHERE proof_status IN ('CREATED', 'RUNNING')", + ) + .fetch_all(&self.pool) + .await?; + games.into_iter().map(address_from_bytes).collect() + } + + pub(crate) async fn cancel_game_proofs(&self, game: Address) -> Result { + const FAILURE_REASON: &str = "game no longer requires proof support"; + let result = sqlx::query( + r#" + UPDATE proof_requests + SET proof_status = $1, job_status = $2, + failure_reason = $3, + worker_id = NULL, lock_id = NULL, lock_expires_at = NULL, + updated_at = $5, finished_at = $5 + WHERE game = $4 AND proof_status IN ('CREATED', 'RUNNING') + "#, + ) + .bind(ProofStatus::Cancelled.as_str()) + .bind(ProofJobStatus::Failed.as_str()) + .bind(FAILURE_REASON) + .bind(game.as_slice()) + .bind(Utc::now()) + .execute(&self.pool) + .await?; + Ok(result.rows_affected()) + } + pub(crate) async fn mark_exhausted_proof_requests_failed(&self) -> Result { let now = Utc::now(); let reason = format!( @@ -465,7 +501,7 @@ impl ProverServiceStore { let session = if let Some(row) = row { let backend_session_id: String = row.try_get("backend_session_id")?; let status_str: String = row.try_get("status")?; - let state = BackendSessionStatus::try_from(status_str.as_str()) + let state = BackendSessionStatus::from_str(status_str.as_str()) .map_err(ProofJobQueueError::UnknownBackendSessionStatus)?; Some(BackendSession { @@ -511,7 +547,7 @@ impl ProverServiceStore { }; let stored_job_status_str: &str = claim.get("job_status"); - let stored_job_status = ProofJobStatus::try_from(stored_job_status_str) + let stored_job_status = ProofJobStatus::from_str(stored_job_status_str) .map_err(ProofJobQueueError::UnknownProofJobStatus)?; let stored_lock_id: Option = claim.get("lock_id"); @@ -564,7 +600,7 @@ impl ProverServiceStore { // retry, any other status is a conflict. for row in &existing_backend_sessions { let status_str: &str = row.get("status"); - let stored = BackendSessionStatus::try_from(status_str) + let stored = BackendSessionStatus::from_str(status_str) .map_err(ProofJobQueueError::UnknownBackendSessionStatus)?; if stored.is_terminal() { if stored == status { @@ -686,7 +722,7 @@ impl ProverServiceStore { let stored_worker_id: Option = existing.get("worker_id"); let stored_lock_expires_at: Option> = existing.get("lock_expires_at"); let stored_job_status_str: String = existing.get("job_status"); - let stored_job_status = ProofJobStatus::try_from(stored_job_status_str.as_str()) + let stored_job_status = ProofJobStatus::from_str(stored_job_status_str.as_str()) .map_err(ProofJobQueueError::UnknownProofJobStatus)?; // validation if stored_proof_request.backend != proof.proof.backend() { @@ -779,7 +815,7 @@ impl ProverServiceStore { let stored_lock_expires_at: Option> = existing.get("lock_expires_at"); let stored_job_status_str: String = existing.get("job_status"); - let stored_job_status = ProofJobStatus::try_from(stored_job_status_str.as_str()) + let stored_job_status = ProofJobStatus::from_str(stored_job_status_str.as_str()) .map_err(ProofJobQueueError::UnknownProofJobStatus)?; // validation if stored_job_status == ProofJobStatus::Succeeded @@ -885,7 +921,7 @@ impl ProverServiceStore { let stored_worker_id: Option = existing.get("worker_id"); let stored_lock_expires_at: Option> = existing.get("lock_expires_at"); - let stored_parsed_status = ProofJobStatus::try_from(stored_job_status_str) + let stored_parsed_status = ProofJobStatus::from_str(stored_job_status_str) .map_err(ProofJobQueueError::UnknownProofJobStatus)?; if matches!( stored_parsed_status, @@ -985,7 +1021,7 @@ fn request_from_row(row: &PgRow) -> Result { } Ok(ProofRequest { - backend: ProofBackend::try_from(row.try_get::("backend")?.as_str()) + backend: ProofBackend::from_str(row.try_get::("backend")?.as_str()) .map_err(ProofJobQueueError::UnknownProofBackend)?, game: address_from_bytes(row.try_get("game")?)?, root_claim: b256_from_bytes(row.try_get("root_claim")?)?, @@ -997,7 +1033,7 @@ fn request_from_row(row: &PgRow) -> Result { } fn parse_status(status: String) -> Result { - ProofStatus::try_from(status.as_str()).map_err(ProofRequestError::UnknownProofStatus) + ProofStatus::from_str(status.as_str()).map_err(ProofRequestError::UnknownProofStatus) } fn l2_to_i64(value: u64) -> Result { diff --git a/proofs/services/prover-service/src/tests.rs b/proofs/services/prover-service/src/tests.rs index 52b8dc1a1..206276451 100644 --- a/proofs/services/prover-service/src/tests.rs +++ b/proofs/services/prover-service/src/tests.rs @@ -3,13 +3,49 @@ use crate::{ ProofJobQueueError, ProofRequest, ProofRequestError, ProofRequestId, ProofRequester, ProofResponse, ProofStatus, ProverService, ProverServiceConfig, RecordProofSessionRequest, RpcProverServiceClient, SubmitProofRequest, SucceededProofResponse, start_rpc_server, - types::{BackendSessionStatus, SessionType}, + types::{BackendSessionStatus, ProofJobStatus, SessionType}, }; use alloy_primitives::{Address, B256, Bytes}; use std::{sync::Arc, time::Duration}; use testcontainers::{ContainerAsync, runners::AsyncRunner}; use testcontainers_modules::postgres; +#[test] +fn proof_states_parse_from_str() { + assert_eq!("sp1".parse::(), Ok(ProofBackend::Sp1)); + assert_eq!("RUNNING".parse::(), Ok(ProofStatus::Running)); + assert_eq!( + "CLAIMED".parse::(), + Ok(ProofJobStatus::Claimed) + ); + assert_eq!("STARK".parse::(), Ok(SessionType::Stark)); + assert_eq!( + "COMPLETED".parse::(), + Ok(BackendSessionStatus::Completed) + ); + + assert_eq!( + "SP1".parse::(), + Err("unknown proof backend \"SP1\"".into()) + ); + assert_eq!( + "running".parse::(), + Err("Unknown proof status: running".into()) + ); + assert_eq!( + "claimed".parse::(), + Err("Unknown proof job status: claimed".into()) + ); + assert_eq!( + "stark".parse::(), + Err("Unknown session type: stark".into()) + ); + assert_eq!( + "completed".parse::(), + Err("Unknown session status: completed".into()) + ); +} + fn test_config() -> ProverServiceConfig { ProverServiceConfig { lock_timeout: Duration::from_secs(60), @@ -106,6 +142,183 @@ fn worker_id() -> String { "test-worker".to_string() } +#[tokio::test] +async fn cancellation_revokes_leases_preserves_completed_proofs_and_can_restart() { + let ctx = service(test_config()).await.expect("Postgres is required"); + let service = &ctx.service; + let running = request(ProofBackend::Sp1, 50); + let pending = request(ProofBackend::Nitro, 50); + let mut completed = request(ProofBackend::Nitro, 51); + completed.game = running.game; + let unrelated = request(ProofBackend::Sp1, 52); + for req in [&running, &pending, &completed, &unrelated] { + service.request_proof(req.clone()).await.unwrap(); + } + let completed_lock = service + .get_next_proof(get_next_proof_request_for(&completed)) + .await + .unwrap() + .locked_request + .unwrap(); + service + .submit_proof(submit_proof_request( + proof_for(&completed), + completed_lock.lock_id, + )) + .await + .unwrap(); + let lock = service + .get_next_proof(get_next_proof_request_for(&running)) + .await + .unwrap() + .locked_request + .unwrap(); + service + .record_proof_session(record_proof_session_request( + running.id(), + SessionType::Stark, + lock.lock_id, + backend_session_id(50), + BackendSessionStatus::Running, + None, + )) + .await + .unwrap(); + + assert_eq!(service.cancel_game_proofs(running.game).await.unwrap(), 2); + assert_eq!(service.cancel_game_proofs(running.game).await.unwrap(), 0); + for req in [&running, &pending] { + assert_eq!( + service.proof_status(req.id()).await.unwrap(), + ProofStatus::Cancelled + ); + assert!( + service + .get_next_proof(get_next_proof_request_for(req)) + .await + .unwrap() + .locked_request + .is_none() + ); + assert!(matches!( + service.get_proof(req.id()).await.unwrap(), + ProofResponse::Failed(_) + )); + } + assert_eq!( + service.get_proof(completed.id()).await.unwrap(), + ProofResponse::Succeeded(proof_for(&completed)) + ); + assert_eq!( + service.proof_status(unrelated.id()).await.unwrap(), + ProofStatus::Created + ); + assert!(matches!( + service + .heartbeat(crate::HeartbeatRequest { + proof_id: running.id(), + worker_id: worker_id(), + lock_id: lock.lock_id, + }) + .await, + Err(ProofJobQueueError::AlreadyTerminal(_)) + )); + assert!( + service + .submit_proof(submit_proof_request(proof_for(&running), lock.lock_id)) + .await + .is_err() + ); + assert!( + service + .record_proof_session(record_proof_session_request( + running.id(), + SessionType::Stark, + lock.lock_id, + backend_session_id(50), + BackendSessionStatus::Completed, + None, + )) + .await + .is_err() + ); + let session_status: String = + sqlx::query_scalar("SELECT status FROM proof_sessions WHERE proof_id = $1") + .bind(running.id().0.as_slice()) + .fetch_one(service.pool()) + .await + .unwrap(); + assert_eq!(session_status, "RUNNING"); + + service.request_proof(running.clone()).await.unwrap(); + let retries: i32 = + sqlx::query_scalar("SELECT retry_count FROM proof_requests WHERE proof_id = $1") + .bind(running.id().0.as_slice()) + .fetch_one(service.pool()) + .await + .unwrap(); + assert_eq!(retries, 0); + let restarted = service + .get_next_proof(get_next_proof_request_for(&running)) + .await + .unwrap() + .locked_request + .unwrap(); + assert_ne!(lock.lock_id, restarted.lock_id); + let resumed_session = service + .get_proof_session(get_proof_session_request(running.id(), SessionType::Stark)) + .await + .unwrap() + .session + .unwrap(); + assert_eq!(resumed_session.backend_session_id, backend_session_id(50)); + assert_eq!(resumed_session.status, BackendSessionStatus::Running); + assert!( + service + .submit_proof(submit_proof_request(proof_for(&running), lock.lock_id)) + .await + .is_err() + ); + service + .submit_proof(submit_proof_request(proof_for(&running), restarted.lock_id)) + .await + .unwrap(); +} + +#[tokio::test] +async fn cleanup_retains_needed_jobs_and_cancels_after_council_support() { + use crate::status_poller::{cancel_obsolete_proofs, tests::push_game_state}; + use alloy_provider::ProviderBuilder; + use alloy_transport::mock::Asserter; + + let ctx = service(test_config()).await.expect("Postgres is required"); + let service = &ctx.service; + let req = request(ProofBackend::Sp1, 60); + service.request_proof(req.clone()).await.unwrap(); + let asserter = Asserter::new(); + let provider = ProviderBuilder::new().connect_mocked_client(asserter.clone()); + + asserter.push_failure_msg("L1 unavailable"); + cancel_obsolete_proofs(service, &provider).await.unwrap(); + assert_eq!( + service.proof_status(req.id()).await.unwrap(), + ProofStatus::Created + ); + push_game_state(&asserter, 0, 1, 4); + cancel_obsolete_proofs(service, &provider).await.unwrap(); + assert_eq!( + service.proof_status(req.id()).await.unwrap(), + ProofStatus::Created + ); + push_game_state(&asserter, 0, 3, 6); + cancel_obsolete_proofs(service, &provider).await.unwrap(); + assert_eq!( + service.proof_status(req.id()).await.unwrap(), + ProofStatus::Cancelled + ); + assert!(service.active_games().await.unwrap().is_empty()); +} + fn get_next_proof_request_for(request: &ProofRequest) -> GetNextProofRequest { GetNextProofRequest { backend: request.backend, diff --git a/proofs/services/prover-service/src/traits.rs b/proofs/services/prover-service/src/traits.rs index d8358496d..60ae9d74f 100644 --- a/proofs/services/prover-service/src/traits.rs +++ b/proofs/services/prover-service/src/traits.rs @@ -20,6 +20,7 @@ pub trait ProofRequester { /// Requests are deduplicated by their deterministic id: re-requesting /// a proof that is already queued, in progress, or completed is a no-op /// returning the same id, while re-requesting a failed proof re-queues it. + /// Cancelled proofs can be re-queued without consuming a retry if support is needed again. async fn request_proof( &self, proof_request: ProofRequest, diff --git a/proofs/services/prover-service/src/types.rs b/proofs/services/prover-service/src/types.rs index 7d511df57..572a6dd81 100644 --- a/proofs/services/prover-service/src/types.rs +++ b/proofs/services/prover-service/src/types.rs @@ -1,3 +1,5 @@ +use std::str::FromStr; + use alloy_primitives::{Address, B256, BlockNumber, Bytes, keccak256}; use serde::{Deserialize, Serialize}; use uuid::Uuid; @@ -34,10 +36,10 @@ impl ProofBackend { } } -impl TryFrom<&str> for ProofBackend { - type Error = String; +impl FromStr for ProofBackend { + type Err = String; - fn try_from(value: &str) -> Result { + fn from_str(value: &str) -> Result { match value { "sp1" => Ok(Self::Sp1), "nitro" => Ok(Self::Nitro), @@ -104,6 +106,8 @@ pub enum ProofStatus { Succeeded, /// Proof generation failed. Failed, + /// The game no longer needs this proof. A later challenge may require it again. + Cancelled, } impl ProofStatus { @@ -114,6 +118,7 @@ impl ProofStatus { Self::Running => "RUNNING", Self::Succeeded => "SUCCEEDED", Self::Failed => "FAILED", + Self::Cancelled => "CANCELLED", } } } @@ -124,15 +129,16 @@ impl std::fmt::Display for ProofStatus { } } -impl TryFrom<&str> for ProofStatus { - type Error = String; +impl FromStr for ProofStatus { + type Err = String; - fn try_from(s: &str) -> Result { + fn from_str(s: &str) -> Result { match s { "CREATED" => Ok(Self::Created), "RUNNING" => Ok(Self::Running), "SUCCEEDED" => Ok(Self::Succeeded), "FAILED" => Ok(Self::Failed), + "CANCELLED" => Ok(Self::Cancelled), other => Err(format!("Unknown proof status: {other}")), } } @@ -169,10 +175,10 @@ impl std::fmt::Display for ProofJobStatus { } } -impl TryFrom<&str> for ProofJobStatus { - type Error = String; +impl FromStr for ProofJobStatus { + type Err = String; - fn try_from(s: &str) -> Result { + fn from_str(s: &str) -> Result { match s { "PENDING" => Ok(Self::Pending), "CLAIMED" => Ok(Self::Claimed), @@ -317,10 +323,10 @@ impl SessionType { } } -impl TryFrom<&str> for SessionType { - type Error = String; +impl FromStr for SessionType { + type Err = String; - fn try_from(s: &str) -> Result { + fn from_str(s: &str) -> Result { match s { "STARK" => Ok(Self::Stark), "SNARK" => Ok(Self::Snark), @@ -372,10 +378,10 @@ impl BackendSessionStatus { } } -impl TryFrom<&str> for BackendSessionStatus { - type Error = String; +impl FromStr for BackendSessionStatus { + type Err = String; - fn try_from(s: &str) -> Result { + fn from_str(s: &str) -> Result { match s { "SUBMITTING" => Ok(Self::Submitting), "RUNNING" => Ok(Self::Running), diff --git a/proofs/services/tx-signer/Cargo.toml b/proofs/services/tx-signer/Cargo.toml index 978cfbe0d..2ba16eb05 100644 --- a/proofs/services/tx-signer/Cargo.toml +++ b/proofs/services/tx-signer/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "world-chain-proof-tx-signer" -version = "1.0.0-rc.1" +version = "1.0.0-rc.5" edition.workspace = true rust-version.workspace = true license.workspace = true diff --git a/proofs/workers/core/Cargo.toml b/proofs/workers/core/Cargo.toml index cd5a24c91..95bb2eb32 100644 --- a/proofs/workers/core/Cargo.toml +++ b/proofs/workers/core/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "world-chain-proof-worker" -version = "1.0.0-rc.1" +version = "1.0.0-rc.5" edition.workspace = true rust-version.workspace = true license.workspace = true diff --git a/proofs/workers/nitro/Cargo.toml b/proofs/workers/nitro/Cargo.toml index 7d34b474b..c30d012c9 100644 --- a/proofs/workers/nitro/Cargo.toml +++ b/proofs/workers/nitro/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "world-chain-proof-nitro-worker" -version = "1.0.0-rc.1" +version = "1.0.0-rc.5" edition.workspace = true rust-version.workspace = true license.workspace = true diff --git a/proofs/workers/nitro/src/cmd/run.rs b/proofs/workers/nitro/src/cmd/run.rs index b753cd955..badfc423f 100644 --- a/proofs/workers/nitro/src/cmd/run.rs +++ b/proofs/workers/nitro/src/cmd/run.rs @@ -185,7 +185,7 @@ pub struct WorkerArgs { poll_interval_seconds: u64, /// Maximum seconds to spend generating one Kona witness. - #[arg(long, default_value_t = 900)] + #[arg(long, env = "WITNESS_TIMEOUT_SECONDS", default_value_t = 900)] witness_timeout_seconds: u64, /// Maximum number of jobs proved concurrently. TEE attestation is cheaper than ZK diff --git a/proofs/workers/nitro/src/lib.rs b/proofs/workers/nitro/src/lib.rs index 817fcfdb6..fbb49b82f 100644 --- a/proofs/workers/nitro/src/lib.rs +++ b/proofs/workers/nitro/src/lib.rs @@ -22,12 +22,14 @@ #![cfg(target_os = "linux")] +use std::time::Instant; + use alloy_primitives::{B256, Bytes, keccak256}; use alloy_sol_types::SolValue; use anyhow::{Context, bail}; use tracing::{debug, info}; use world_chain_proof_kona_host::online::{ - OnlineHostConfig, RangeWitnessRequest, build_range_input, + OnlineHostConfig, RangeWitnessRequest, build_range_input, is_witness_generation_timeout, }; use world_chain_proof_nitro_enclave::{ ExpectedPcrs, NitroRangeProofRequest, @@ -109,14 +111,13 @@ where let prover = NitroProver::new(endpoint, self.config.expected_pcrs); info!( + proof_id = %request.id(), start_block, end_block = request.l2_block_number, - l1_rpc = %self.config.online.l1_rpc, - l2_rpc = %self.config.online.l2_rpc, "collecting witness data for range" ); - let witness_collection_started_at = std::time::Instant::now(); - let input = build_range_input( + let witness_collection_started_at = Instant::now(); + let input = match build_range_input( &self.config.online, RangeWitnessRequest { start_block, @@ -126,12 +127,35 @@ where }, ) .await - .context("witness generation failed")?; + { + Ok(input) => { + world_chain_proof_metrics::record_witness_collection( + "nitro", + "success", + witness_collection_started_at.elapsed(), + ); + input + } + Err(error) => { + let outcome = if is_witness_generation_timeout(&error) { + "timeout" + } else { + "error" + }; + world_chain_proof_metrics::record_witness_collection( + "nitro", + outcome, + witness_collection_started_at.elapsed(), + ); + return Err(error).context("witness generation failed"); + } + }; let nitro_request = NitroRangeProofRequest::from_witness_data(&input.witness, None) .context("witness serialize")?; info!( + proof_id = %request.id(), start_block, end_block = request.l2_block_number, duration_secs = witness_collection_started_at.elapsed().as_secs_f64(), @@ -139,10 +163,50 @@ where "witness data collection complete" ); - let artifact = prover - .prove_range(nitro_request) - .await - .context("nitro enclave proving failed")?; + info!( + proof_id = %request.id(), + start_block, + end_block = request.l2_block_number, + "requesting Nitro enclave range proof" + ); + let enclave_proving_started_at = Instant::now(); + let artifact = match prover.prove_range(nitro_request).await { + Ok(artifact) => { + let duration = enclave_proving_started_at.elapsed(); + world_chain_proof_metrics::record_proof_phase_duration( + "nitro", + "enclave_proving", + "success", + duration, + ); + tracing::info!( + proof_id = %request.id(), + start_block, + end_block = request.l2_block_number, + duration_secs = duration.as_secs_f64(), + "Nitro enclave range proof complete" + ); + artifact + } + Err(error) => { + let duration = enclave_proving_started_at.elapsed(); + world_chain_proof_metrics::record_proof_phase_duration( + "nitro", + "enclave_proving", + "error", + duration, + ); + tracing::error!( + proof_id = %request.id(), + start_block, + end_block = request.l2_block_number, + duration_secs = duration.as_secs_f64(), + error = %error, + "Nitro enclave range proof failed" + ); + return Err(error).context("nitro enclave proving failed"); + } + }; if artifact.transition_public_values.l2PostRoot != request.root_claim { bail!( diff --git a/proofs/workers/sp1/Cargo.toml b/proofs/workers/sp1/Cargo.toml index a14fd1dca..c48533e34 100644 --- a/proofs/workers/sp1/Cargo.toml +++ b/proofs/workers/sp1/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "world-chain-proof-sp1-worker" -version = "1.0.0-rc.1" +version = "1.0.0-rc.5" edition.workspace = true rust-version.workspace = true license.workspace = true diff --git a/proofs/workers/sp1/src/backend.rs b/proofs/workers/sp1/src/backend.rs index aef9b4677..77ec3505d 100644 --- a/proofs/workers/sp1/src/backend.rs +++ b/proofs/workers/sp1/src/backend.rs @@ -1,6 +1,9 @@ //! SP1 validity-proof backend for the defender's [`ProofWorker`]. -use std::{collections::HashMap, time::Duration}; +use std::{ + collections::HashMap, + time::{Duration, Instant}, +}; use alloy_primitives::B256; use alloy_sol_types::SolValue; @@ -8,6 +11,7 @@ use anyhow::Context; use world_chain_proof_core::artifacts::{AggregationProofArtifact, RangeProofArtifact}; use world_chain_proof_kona_host::online::{ OnlineHostConfig, RangeWitnessRequest, build_range_input, fetch_l1_header_by_hash, + is_witness_generation_timeout, }; use world_chain_proof_protocol::ProofGameProvider; use world_chain_proof_sp1_host::{ @@ -224,9 +228,16 @@ impl Sp1Backend Sp1Backend { + let duration = witness_started_at.elapsed(); + tracing::info!( + proof_id = %request.id(), + start_block = range_start, + end_block = range_end, + splits, + witness_bytes = range_request.witness_rkyv.len(), + duration_secs = duration.as_secs_f64(), + "SP1 range witness complete" + ); + range_request + } + Err(error) => { + let duration = witness_started_at.elapsed(); + tracing::error!( + proof_id = %request.id(), + start_block = range_start, + end_block = range_end, + splits, + duration_secs = duration.as_secs_f64(), + error = %error, + "SP1 range witness failed" + ); + return Err(error).context("failed to build range proof request"); + } + }; + tracing::info!( + proof_id = %request.id(), + start_block = range_start, + end_block = range_end, + splits, + "submitting SP1 range proof request" + ); + let submission_started_at = Instant::now(); + let session_id = match self .prover .submit(Sp1ProofRequest::Range(range_request)) .await - .context("failed to submit range proof")?; + { + Ok(session_id) => { + let duration = submission_started_at.elapsed(); + world_chain_proof_metrics::record_proof_phase_duration( + "sp1", + "range_submission", + "success", + duration, + ); + tracing::info!( + proof_id = %request.id(), + start_block = range_start, + end_block = range_end, + splits, + backend_session_id = %session_id, + duration_secs = duration.as_secs_f64(), + "SP1 range proof request submitted" + ); + session_id + } + Err(error) => { + let duration = submission_started_at.elapsed(); + world_chain_proof_metrics::record_proof_phase_duration( + "sp1", + "range_submission", + "error", + duration, + ); + tracing::error!( + proof_id = %request.id(), + start_block = range_start, + end_block = range_end, + splits, + duration_secs = duration.as_secs_f64(), + error = %error, + "SP1 range proof request failed" + ); + return Err(error).context("failed to submit range proof"); + } + }; plan.ranges[index].session_id = Some(session_id); self.persist_plan(job, plan, BackendSessionStatus::Running, None) .await?; @@ -313,12 +407,56 @@ impl Sp1Backend { + let duration = wait_started_at.elapsed(); + world_chain_proof_metrics::record_proof_phase_duration( + "sp1", + "range_wait", + "success", + duration, + ); + tracing::info!( + proof_id = %request.id(), + start_block = range.start_block, + end_block = range.end_block, + splits = range.splits, + backend_session_id = %session_id, + duration_secs = duration.as_secs_f64(), + "SP1 range proof fulfilled" + ); artifacts.insert(key, range_artifact_from_sp1_proof(&proof)?); continue; } - Err(error) => error, + Err(error) => { + let duration = wait_started_at.elapsed(); + world_chain_proof_metrics::record_proof_phase_duration( + "sp1", + "range_wait", + "error", + duration, + ); + tracing::warn!( + proof_id = %request.id(), + start_block = range.start_block, + end_block = range.end_block, + splits = range.splits, + backend_session_id = %session_id, + duration_secs = duration.as_secs_f64(), + error = %error, + "SP1 range proof wait failed" + ); + error + } }; match error.downcast_ref::() { Some(session_error) if session_error.should_resubmit() => { @@ -431,8 +569,27 @@ impl Sp1Backend anyhow::Result> { let session_type = SessionType::Snark; + tracing::info!( + proof_id = %job.request.id(), + backend_session_id = %session_id, + "waiting for SP1 aggregation proof" + ); + let wait_started_at = Instant::now(); match self.prover.wait(&session_id).await { Ok(proof) => { + let duration = wait_started_at.elapsed(); + world_chain_proof_metrics::record_proof_phase_duration( + "sp1", + "aggregation_wait", + "success", + duration, + ); + tracing::info!( + proof_id = %job.request.id(), + backend_session_id = %session_id, + duration_secs = duration.as_secs_f64(), + "SP1 aggregation proof fulfilled" + ); let artifact = aggregation_artifact_from_sp1_proof(&proof)?; self.record_session( job, @@ -445,6 +602,20 @@ impl Sp1Backend { + let duration = wait_started_at.elapsed(); + world_chain_proof_metrics::record_proof_phase_duration( + "sp1", + "aggregation_wait", + "error", + duration, + ); + tracing::warn!( + proof_id = %job.request.id(), + backend_session_id = %session_id, + duration_secs = duration.as_secs_f64(), + error = %error, + "SP1 aggregation proof wait failed" + ); self.handle_wait_error(job, session_type, &session_id, error) .await?; Ok(None) @@ -501,13 +672,58 @@ impl Sp1Backend { + let duration = submission_started_at.elapsed(); + world_chain_proof_metrics::record_proof_phase_duration( + "sp1", + "aggregation_submission", + "success", + duration, + ); + tracing::info!( + proof_id = %job.request.id(), + ranges = request.range_proofs.len(), + resubmission, + backend_session_id = %session_id, + duration_secs = duration.as_secs_f64(), + "SP1 aggregation proof request submitted" + ); + session_id + } + Err(error) => { + let duration = submission_started_at.elapsed(); + world_chain_proof_metrics::record_proof_phase_duration( + "sp1", + "aggregation_submission", + "error", + duration, + ); + tracing::error!( + proof_id = %job.request.id(), + ranges = request.range_proofs.len(), + resubmission, + duration_secs = duration.as_secs_f64(), + error = %error, + "SP1 aggregation proof request failed" + ); + return Err(error); + } + }; if let Some(artifact) = self.wait_for_aggregation(job, session_id).await? { return Ok(artifact); } @@ -563,7 +779,8 @@ impl Sp1Backend anyhow::Result { - let input = build_range_input( + let witness_collection_started_at = std::time::Instant::now(); + let input = match build_range_input( &self.host, RangeWitnessRequest { start_block, @@ -573,7 +790,29 @@ impl Sp1Backend { + world_chain_proof_metrics::record_witness_collection( + "sp1", + "success", + witness_collection_started_at.elapsed(), + ); + input + } + Err(error) => { + let outcome = if is_witness_generation_timeout(&error) { + "timeout" + } else { + "error" + }; + world_chain_proof_metrics::record_witness_collection( + "sp1", + outcome, + witness_collection_started_at.elapsed(), + ); + return Err(error).context("failed to build SP1 range witness"); + } + }; let range_request = RangeProofRequest::from_witness_data(&input.witness) .context("failed to serialize SP1 range witness")?; diff --git a/proofs/workers/sp1/src/cmd/run.rs b/proofs/workers/sp1/src/cmd/run.rs index 190863a57..686feea7f 100644 --- a/proofs/workers/sp1/src/cmd/run.rs +++ b/proofs/workers/sp1/src/cmd/run.rs @@ -121,7 +121,7 @@ pub struct WorkerArgs { allow_unfinalized: bool, /// Maximum seconds to spend generating one Kona witness. - #[arg(long, default_value_t = 900)] + #[arg(long, env = "WITNESS_TIMEOUT_SECONDS", default_value_t = 900)] witness_timeout_seconds: u64, /// Prover backend. diff --git a/rust-toolchain.toml b/rust-toolchain.toml index c7485b814..5ab024b45 100644 --- a/rust-toolchain.toml +++ b/rust-toolchain.toml @@ -1,3 +1,3 @@ [toolchain] -channel = "nightly-2026-07-01" +channel = "nightly-2026-10-10" components = ["clippy", "rustfmt"] diff --git a/scripts/review-policy/admin.cjs b/scripts/review-policy/admin.cjs new file mode 100644 index 000000000..508c6eca6 --- /dev/null +++ b/scripts/review-policy/admin.cjs @@ -0,0 +1,225 @@ +'use strict'; + +const fs = require('node:fs'); +const path = require('node:path'); +const { execFileSync } = require('node:child_process'); +const { isDeepStrictEqual } = require('node:util'); +const { GATES, human } = require('./policy.cjs'); +const { Api, readCodeowners } = require('./github.cjs'); + +const REPO = 'worldcoin/world-chain'; +const RULESET = 'world-chain-review-policy'; +const CI_RULESET = 'world-chain-ci-policy'; +const CI_GATES = GATES.filter((gate) => gate !== 'human-review-gate'); + +function request(method, path, body) { + try { + const endpoint = path.startsWith('/') ? path.slice(1) : `repos/${REPO}/${path}`; + return JSON.parse(execFileSync('gh', ['api', endpoint, '--method', method, + '--header', 'Accept: application/vnd.github.v3.repository+json', ...(body === undefined ? [] : ['--input', '-'])], { + input: body === undefined ? undefined : JSON.stringify(body), encoding: 'utf8', stdio: 'pipe', timeout: 30000, maxBuffer: 16000000, + }) || 'null'); + } catch (error) { + error.status = Number(String(error.stderr || '').match(/\(HTTP (\d{3})\)/)?.[1]) || undefined; + throw error; + } +} + +function list(path, key) { + const result = []; + for (let page = 1; page <= 100; page++) { + const data = request('GET', `${path}${path.includes('?') ? '&' : '?'}per_page=100&page=${page}`); + const items = key ? data[key] : data; + result.push(...items); + if (items.length < 100) return result; + } + throw new Error(`Pagination limit: ${path}`); +} + +function reviewSettings(protection) { + const reviews = protection.required_pull_request_reviews; + if (!reviews) throw new Error('Existing PR review protection is missing; inspect manually before changing rules.'); + return Object.fromEntries(['required_approving_review_count', 'require_code_owner_reviews', 'dismiss_stale_reviews', 'require_last_push_approval'].map((key) => [key, reviews[key]])); +} + +function requiredChecks(gates) { + return { type: 'required_status_checks', parameters: { + strict_required_status_checks_policy: false, do_not_enforce_on_create: false, + required_status_checks: gates.map((context) => ({ context, integration_id: 15368 })), + } }; +} + +function rulesetBody() { + return { + name: RULESET, target: 'branch', enforcement: 'active', bypass_actors: [], + conditions: { ref_name: { include: ['refs/heads/main'], exclude: [] } }, + rules: [ + requiredChecks(['human-review-gate']), + { type: 'pull_request', parameters: { + required_approving_review_count: 0, require_code_owner_review: false, + dismiss_stale_reviews_on_push: false, require_last_push_approval: false, + required_review_thread_resolution: true, allowed_merge_methods: ['squash'], + } }, + ], + }; +} + +function ciRulesetBody(bypassActors) { + return { + name: CI_RULESET, target: 'branch', enforcement: 'active', bypass_actors: bypassActors, + conditions: { ref_name: { include: ['refs/heads/main'], exclude: [] } }, + rules: [requiredChecks(CI_GATES)], + }; +} + +async function ciBypassActors(request, ref) { + const rules = await readCodeowners({ + async content(path, sha) { + const file = request('GET', `contents/${path}?ref=${sha}`); + if (file.type !== 'file' || file.encoding !== 'base64' || file.size > 1000000) throw new Error(`Cannot read trusted ${path}`); + return Buffer.from(file.content, 'base64').toString('utf8'); + }, + }, ref); + const owners = [...new Set([...rules].reverse().find((rule) => rule.pattern === '*')?.owners || [])]; + if (!owners.length) throw new Error('CI bypass requires a nonempty global * CODEOWNERS rule on main.'); + const actors = []; + for (const owner of owners) { + if (owner.includes('/')) { + const [org, slug] = owner.slice(1).split('/'); + if (org !== REPO.split('/')[0]) throw new Error(`CI bypass team ${owner} must belong to the repository organization.`); + const team = request('GET', `/orgs/${org}/teams/${slug}`); + const repo = request('GET', `/orgs/${org}/teams/${slug}/repos/${REPO}`); + if (!Number.isSafeInteger(team.id) || team.id < 1 || team.slug !== slug || team.privacy !== 'closed' + || repo.full_name !== REPO || !repo.permissions?.push) { + throw new Error(`CI bypass team ${owner} must be visible and have repository write access.`); + } + actors.push({ actor_id: team.id, actor_type: 'Team', bypass_mode: 'pull_request' }); + continue; + } + const login = owner.slice(1); + const result = request('GET', `collaborators/${login}/permission`); + if (!human(result.user) || !Number.isSafeInteger(result.user.id) || result.user.id < 1 + || result.user.login.toLowerCase() !== login + || !(['admin', 'maintain', 'write'].includes(result.permission) || result.user.permissions?.push)) { + throw new Error(`CI bypass owner ${owner} must be a human collaborator with write access.`); + } + actors.push({ actor_id: result.user.id, actor_type: 'User', bypass_mode: 'pull_request' }); + } + return actors; +} + +function verifyRuleset(actual, expected) { + const actors = (items) => items?.map(({ actor_id, actor_type, bypass_mode }) => ({ actor_id, actor_type, bypass_mode })) + .sort((a, b) => a.actor_id - b.actor_id); + const checks = (rules) => rules?.find((rule) => rule.type === 'required_status_checks')?.parameters?.required_status_checks + ?.map(({ context, integration_id }) => ({ context, integration_id })).sort((a, b) => a.context.localeCompare(b.context)); + const pull = actual.rules?.find((rule) => rule.type === 'pull_request')?.parameters; + const expectedPull = expected.rules.find((rule) => rule.type === 'pull_request')?.parameters; + if (actual.name !== expected.name || actual.target !== 'branch' || actual.enforcement !== 'active' + || !isDeepStrictEqual(actual.conditions, expected.conditions) + || !isDeepStrictEqual(actors(actual.bypass_actors), actors(expected.bypass_actors)) + || !isDeepStrictEqual(checks(actual.rules), checks(expected.rules)) + || actual.rules?.length !== expected.rules.length + || (expectedPull && Object.entries(expectedPull).some(([key, value]) => !isDeepStrictEqual(pull?.[key], value)))) { + throw new Error(`Ruleset ${expected.name} was not installed as expected; keeping the native review requirement.`); + } +} + +async function main(args = process.argv.slice(2), api = { request, list }, log = console.log) { + const { request, list } = api; + const [command, ...options] = args; + const option = (name) => { const i = options.indexOf(name); return i < 0 ? undefined : options[i + 1]; }; + const apply = options.includes('--apply'); + const backupPath = option('--backup'); + if (!['snapshot', 'activate', 'restore'].includes(command) || !backupPath) { + throw new Error('Usage: node scripts/review-policy/admin.cjs snapshot|activate|restore --backup /absolute/file.json [--evidence-pr N] [--apply]'); + } + if (!path.isAbsolute(backupPath)) throw new Error('--backup must be an absolute path outside the checkout.'); + const relative = path.relative(process.cwd(), backupPath); + if (!relative.startsWith(`..${path.sep}`) && relative !== '..') throw new Error('Save the backup outside the checkout.'); + if (command === 'snapshot') { + const protection = request('GET', 'branches/main/protection'); + const rulesets = list('rulesets'); + const ownRulesets = rulesets.filter((rule) => rule.source_type === 'Repository').map((rule) => request('GET', `rulesets/${rule.id}`)); + fs.writeFileSync(backupPath, JSON.stringify({ repo: REPO, takenAt: new Date().toISOString(), protection, rulesets, ownRulesets }, null, 2) + '\n', { flag: 'wx', mode: 0o600 }); + log(`Saved protection snapshot to ${backupPath}; GitHub settings unchanged.`); + return; + } + const backup = JSON.parse(fs.readFileSync(backupPath, 'utf8')); + if (backup.repo !== REPO) throw new Error('Snapshot repository mismatch.'); + const current = list('rulesets').filter((rule) => rule.source_type === 'Repository'); + if (command === 'restore') { + log('Restore the previous native review requirements first, then restore/remove only the review-policy and CI-policy rulesets. Socket and unrelated rules remain untouched.'); + if (!apply) { log('Dry run. Add --apply to restore.'); return; } + request('PATCH', 'branches/main/protection/required_pull_request_reviews', reviewSettings(backup.protection)); + for (const name of [RULESET, CI_RULESET]) { + const previous = backup.ownRulesets.find((rule) => rule.name === name); + const installed = current.find((rule) => rule.name === name); + if (previous) { + const { target, enforcement, conditions, rules, bypass_actors } = previous; + request(installed ? 'PUT' : 'POST', installed ? `rulesets/${installed.id}` : 'rulesets', { name, target, enforcement, conditions, rules, bypass_actors }); + } else if (installed) request('DELETE', `rulesets/${installed.id}`); + } + log('Previous review protection restored.'); + return; + } + const evidence = Number(option('--evidence-pr')); + if (!Number.isSafeInteger(evidence) || evidence < 1) throw new Error('--evidence-pr must identify a real PR with all four gates successful.'); + const main = request('GET', 'branches/main').commit.sha; + for (const path of [ + '.github/review-policy.json', '.github/workflows/review-policy.yml', '.github/workflows/review-policy-events.yml', + '.github/workflows/review-policy-tests.yml', 'scripts/review-policy/policy.cjs', 'scripts/review-policy/github.cjs', + 'scripts/review-policy/admin.cjs', 'scripts/review-policy/policy.test.cjs', 'scripts/review-policy/github.test.cjs', 'scripts/review-policy/admin.test.cjs', + '.github/actionlint.yaml', '.github/workflows/rust-ci.yml', '.github/workflows/foundry.yml', '.github/workflows/verify-measurements.yml', + ]) { + const remote = request('GET', `contents/${path}?ref=${main}`); + if (Buffer.from(remote.content || '', 'base64').toString('utf8') !== fs.readFileSync(path, 'utf8')) { + throw new Error(`${path} is not deployed identically on main; activation refused.`); + } + } + const pr = request('GET', `pulls/${evidence}`); + if (pr.base.ref !== 'main') throw new Error('Evidence PR must target main.'); + const checks = list(`commits/${pr.head.sha}/check-runs`, 'check_runs'); + const statuses = list(`commits/${pr.head.sha}/statuses`); + const policyApi = new Api({ request: async (route, { tree_sha }) => { + if (route !== 'GET /repos/{owner}/{repo}/git/trees/{tree_sha}') throw new Error(`Unexpected policy API: ${route}`); + return { data: request('GET', `git/trees/${tree_sha}`) }; + } }, {}); + for (const name of GATES) { + const result = checks.find((check) => check.name === name && check.app?.slug === 'github-actions' + && check.external_id === `review-policy:${REPO}:${evidence}:${pr.head.sha}`); + if (result?.status !== 'completed' || result.conclusion !== 'success') throw new Error(`Evidence gate ${name} is not successful on the PR head.`); + const status = statuses.find((status) => status.context === name); + if (status?.state !== 'success' || status.creator?.login !== 'github-actions[bot]' + || status.target_url !== `https://github.com/${REPO}/runs/${result.id}`) { + throw new Error(`Evidence gate ${name} lacks a matching successful GitHub Actions commit status; re-evaluate the PR.`); + } + const header = result.output?.summary?.match(/^PR #(\d+); head ([^;\r\n]+); base ([a-f0-9]{40}); risk: /); + if (!header || Number(header[1]) !== evidence || header[2] !== pr.head.sha) { + throw new Error(`Evidence gate ${name} has a missing or invalid target commit; re-evaluate the PR.`); + } + if (!await policyApi.samePolicy(header[3], main)) throw new Error(`Evidence gate ${name} used a different target policy; re-evaluate the PR.`); + } + const bypassActors = await ciBypassActors(request, main); + log(`Ready to require ${GATES.join(', ')} and resolved threads, then replace the blanket review count with dynamic ownership. ${CI_GATES.join(', ')} permit explicit PR-only bypass by ${bypassActors.length} global CODEOWNERS users/teams. Human confirmations and resolved threads cannot be bypassed. Backup: ${backupPath}`); + if (!apply) { log('Dry run. Add --apply to activate.'); return; } + const liveProtection = request('GET', 'branches/main/protection'); + if (JSON.stringify(reviewSettings(liveProtection)) !== JSON.stringify(reviewSettings(backup.protection))) { + throw new Error('Review settings changed since the snapshot; take a fresh snapshot before activation.'); + } + if (request('GET', 'branches/main').commit.sha !== main) throw new Error('Main changed during readiness checks; rerun activation.'); + for (const desired of [ciRulesetBody(bypassActors), rulesetBody()]) { + const existing = current.find((rule) => rule.name === desired.name); + const installed = request(existing ? 'PUT' : 'POST', existing ? `rulesets/${existing.id}` : 'rulesets', desired); + verifyRuleset(request('GET', `rulesets/${installed.id}`), desired); + } + request('PATCH', 'branches/main/protection/required_pull_request_reviews', { + required_approving_review_count: 0, require_code_owner_reviews: false, dismiss_stale_reviews: false, require_last_push_approval: false, + }); + const active = request('GET', 'branches/main/protection'); + if (active.required_pull_request_reviews.required_approving_review_count !== 0 || active.required_pull_request_reviews.require_code_owner_reviews) throw new Error('Native review requirements were not updated.'); + log('Review policy activated. Socket Security and unrelated protections preserved.'); +} + +if (require.main === module) main().catch((error) => { console.error(error.message); process.exitCode = 1; }); +module.exports = { rulesetBody, ciRulesetBody, ciBypassActors, reviewSettings, main }; diff --git a/scripts/review-policy/admin.test.cjs b/scripts/review-policy/admin.test.cjs new file mode 100644 index 000000000..4281d54d0 --- /dev/null +++ b/scripts/review-policy/admin.test.cjs @@ -0,0 +1,298 @@ +'use strict'; + +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const { main, rulesetBody, ciRulesetBody } = require('./admin.cjs'); +const { GATES } = require('./policy.cjs'); +const base = 'b'.repeat(40); +const previousBase = 'a'.repeat(40); + +async function fixture(t, options = {}) { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'world-chain-policy-test-')); + t.after(() => fs.rmSync(dir, { recursive: true, force: true })); + const backup = path.join(dir, 'backup.json'); + const original = { required_pull_request_reviews: { required_approving_review_count: 1, require_code_owner_reviews: true, dismiss_stale_reviews: false, require_last_push_approval: false } }; + const live = structuredClone(original); + const mutations = []; + const reads = []; + const socket = { id: 99, name: 'require-socket-pr-alerts', source_type: 'Organization' }; + const rulesets = new Map((options.existingRulesets || []).map((rule) => [rule.id, structuredClone(rule)])); + const originalRulesets = structuredClone([...rulesets.values()]); + let nextId = 10; + let branchReads = 0; + const content = (text) => ({ type: 'file', encoding: 'base64', size: Buffer.byteLength(text), content: Buffer.from(text).toString('base64') }); + const api = { + request(method, resource, body) { + if (method !== 'GET') mutations.push({ method, resource, body }); + else reads.push(resource); + if (resource === 'branches/main/protection') return structuredClone(live); + if (resource === 'branches/main') return { commit: { sha: options.mainChanged && branchReads++ > 0 ? 'new-base' : base } }; + if (resource.startsWith('git/trees/')) { + if (options.treeError) throw Object.assign(new Error('Cannot read policy tree'), { status: 403 }); + const ref = resource.slice('git/trees/'.length); + assert([base, previousBase].includes(ref), `Unexpected policy reference: ${ref}`); + return { truncated: Boolean(options.truncatedTree), tree: [{ path: 'CODEOWNERS', type: 'blob', mode: '100644', + sha: options.changedPolicy && ref === previousBase ? 'previous-owners' : 'current-owners' }] }; + } + if (resource.startsWith('contents/')) { + if (options.notDeployed) throw new Error('Not deployed on main'); + const filename = resource.slice('contents/'.length).split('?')[0]; + if (filename.endsWith('CODEOWNERS')) { + if (options.codeownersError) throw Object.assign(new Error('CODEOWNERS access denied'), { status: 403 }); + const source = filename === '.github/CODEOWNERS' ? options.githubCodeowners + : filename === 'CODEOWNERS' ? options.codeowners ?? '* @Alice @Bob\n' : undefined; + if (source === undefined) throw Object.assign(new Error('Not found'), { status: 404 }); + return content(source); + } + return content(fs.readFileSync(filename, 'utf8')); + } + if (resource.startsWith('collaborators/')) { + const login = resource.split('/')[1]; + const id = { alice: 101, bob: 102, carol: 103 }[login]; + if (!id) throw new Error(`Unexpected owner: ${login}`); + return { permission: options.readOnlyOwner ? 'read' : 'write', user: { login, id, type: options.botOwner ? 'Bot' : 'User' } }; + } + if (resource === '/orgs/worldcoin/teams/protocol') { + if (options.missingTeam) throw Object.assign(new Error('CI bypass team not found'), { status: 404 }); + return { id: 14554659, slug: 'protocol', privacy: options.secretTeam ? 'secret' : 'closed' }; + } + if (resource === '/orgs/worldcoin/teams/protocol/repos/worldcoin/world-chain') { + return { full_name: 'worldcoin/world-chain', permissions: { push: !options.readOnlyTeam } }; + } + if (resource === 'pulls/1') return { base: { ref: 'main', sha: options.stalePrBase ? previousBase : base }, head: { sha: 'head' } }; + if (resource === 'rulesets' && method === 'POST') { + const rule = { id: nextId++, ...body }; rulesets.set(rule.id, structuredClone(rule)); return rule; + } + if (resource.startsWith('rulesets/')) { + const id = Number(resource.split('/')[1]); + if (method === 'PUT') { const rule = { id, ...body }; rulesets.set(id, structuredClone(rule)); return rule; } + if (method === 'DELETE') { rulesets.delete(id); return null; } + if (method === 'GET') { + const rule = structuredClone(rulesets.get(id)); + if (options.reorderedConditions) rule.conditions = { ref_name: { exclude: [], include: ['refs/heads/main'] } }; + if (options.badRuleset === true || options.badRuleset === rule.name) rule.enforcement = 'disabled'; + if (options.reviewBypass && rule.name === 'world-chain-review-policy') rule.bypass_actors = [{ actor_id: 5, actor_type: 'RepositoryRole', bypass_mode: 'pull_request' }]; + if (options.wrongCiOwner && rule.name === 'world-chain-ci-policy') rule.bypass_actors[0].actor_id = 999; + return rule; + } + } + if (resource === 'branches/main/protection/required_pull_request_reviews' && method === 'PATCH') { + Object.assign(live.required_pull_request_reviews, body); return live.required_pull_request_reviews; + } + throw new Error(`Unexpected admin API: ${method} ${resource}`); + }, + list(resource) { + if (resource === 'rulesets') return [socket, ...[...rulesets.values()].map((rule) => ({ ...rule, source_type: 'Repository' }))]; + if (resource === 'commits/head/check-runs') return GATES.map((name, id) => ({ id, name, status: 'completed', conclusion: options.badGate ? 'failure' : 'success', + app: { slug: 'github-actions' }, external_id: 'review-policy:worldcoin/world-chain:1:head', + output: { summary: options.gateSummary ?? `PR #1; head head; base ${options.gateBases?.[name] || options.evidenceBase || base}; risk: critical.` } })); + if (resource === 'commits/head/statuses') return options.noStatuses ? [] : GATES.map((context, id) => ({ + context, state: options.statusState || 'success', creator: { login: options.statusCreator || 'github-actions[bot]' }, + target_url: `https://github.com/worldcoin/world-chain/runs/${options.wrongStatusTarget ? 999 : id}`, + })); + throw new Error(`Unexpected admin list: ${resource}`); + }, + }; + const run = (command, extra = []) => main([command, '--backup', backup, ...extra], api, () => {}); + await run('snapshot'); + return { backup, original, live, mutations, reads, rulesets, originalRulesets, run }; +} + +test('activation dry-run checks readiness without GitHub mutations; snapshot cannot be overwritten', async (t) => { + const f = await fixture(t); + await f.run('activate', ['--evidence-pr', '1']); + assert.deepEqual(f.mutations, []); + await assert.rejects(() => f.run('snapshot'), /EEXIST/); +}); + +test('activation verifies current target policy from gate evidence despite a cached PR base SHA', async (t) => { + const f = await fixture(t, { stalePrBase: true }); + await f.run('activate', ['--evidence-pr', '1']); + assert.deepEqual(f.mutations, []); +}); + +test('activation accepts successful evidence from an older commit with identical policy', async (t) => { + for (const apply of [false, true]) await t.test(apply ? 'apply' : 'dry run', async (t) => { + const f = await fixture(t, { evidenceBase: previousBase }); + await f.run('activate', ['--evidence-pr', '1', ...(apply ? ['--apply'] : [])]); + assert.equal(f.mutations.length, apply ? 3 : 0); + assert.deepEqual(f.reads.filter((resource) => resource.startsWith('git/trees/')), + [`git/trees/${previousBase}`, `git/trees/${base}`], 'all four gates share immutable policy reads'); + }); +}); + +test('incompatible or unverifiable evidence policy cannot change protections', async (t) => { + for (const options of [{ changedPolicy: true }, { treeError: true }, { truncatedTree: true }]) { + const f = await fixture(t, { gateBases: { 'required-ci-gate': previousBase }, ...options }); + await assert.rejects(() => f.run('activate', ['--evidence-pr', '1', '--apply']), + /different target policy|Cannot read policy tree|Incomplete Git tree/); + assert.deepEqual(f.mutations, []); + assert.deepEqual(f.live, f.original); + } +}); + +test('missing or malformed evidence headers cannot select a policy reference', async (t) => { + for (const gateSummary of ['', `Unrelated text; base ${base};`, 'PR #1; head head; base main; risk: low.', + `PR #2; head head; base ${base}; risk: low.`, `PR #1; head other; base ${base}; risk: low.`]) { + const f = await fixture(t, { gateSummary }); + await assert.rejects(() => f.run('activate', ['--evidence-pr', '1', '--apply']), /missing or invalid target commit/); + assert.deepEqual(f.mutations, []); + assert(!f.reads.some((resource) => resource.startsWith('git/trees/'))); + } +}); + +test('activation installs CI before review gates; rollback restores reviews before deleting both rulesets', async (t) => { + const f = await fixture(t); + await f.run('activate', ['--evidence-pr', '1', '--apply']); + assert.deepEqual(f.mutations.map((item) => item.resource), ['rulesets', 'rulesets', 'branches/main/protection/required_pull_request_reviews']); + assert.equal(f.live.required_pull_request_reviews.required_approving_review_count, 0); + await f.run('restore', ['--apply']); + assert.deepEqual(f.mutations.slice(3).map((item) => item.resource), ['branches/main/protection/required_pull_request_reviews', 'rulesets/11', 'rulesets/10']); + assert.deepEqual(f.live, f.original); + assert(!f.mutations.some((item) => item.resource === 'rulesets/99')); +}); + +test('undeployed code and unsuccessful pilot gates cannot change protection', async (t) => { + for (const options of [{ notDeployed: true }, { badGate: true }]) { + const f = await fixture(t, options); + await assert.rejects(() => f.run('activate', ['--evidence-pr', '1', '--apply'])); + assert.deepEqual(f.mutations, []); + assert.deepEqual(f.live, f.original); + } +}); + +test('diagnostic checks alone cannot activate protection without matching successful merge statuses', async (t) => { + for (const options of [{ noStatuses: true }, { statusState: 'pending' }, { statusState: 'failure' }, + { statusCreator: 'someone-else' }, { wrongStatusTarget: true }]) { + const f = await fixture(t, options); + await assert.rejects(() => f.run('activate', ['--evidence-pr', '1', '--apply']), /matching successful GitHub Actions commit status/); + assert.deepEqual(f.mutations, []); + assert.deepEqual(f.live, f.original); + } +}); + +test('a ruleset not enforced by GitHub cannot relax the original approval requirement', async (t) => { + const f = await fixture(t, { badRuleset: true }); + await assert.rejects(() => f.run('activate', ['--evidence-pr', '1', '--apply']), /keeping the native review requirement/); + assert.deepEqual(f.live, f.original); + assert.equal(f.mutations.length, 1); +}); + +test('build/test CI and both AI gates permit PR-only bypass while human approvals and threads remain mandatory', async (t) => { + const f = await fixture(t, { codeowners: '* @Alice @Bob @Alice\n/docs/ @Carol\n' }); + await f.run('activate', ['--evidence-pr', '1', '--apply']); + const [ci, review] = f.mutations.map((item) => item.body); + assert.deepEqual(ci.bypass_actors, [ + { actor_id: 101, actor_type: 'User', bypass_mode: 'pull_request' }, + { actor_id: 102, actor_type: 'User', bypass_mode: 'pull_request' }, + ]); + assert.deepEqual(ci.rules.map((rule) => rule.type), ['required_status_checks']); + assert.deepEqual(ci.rules[0].parameters.required_status_checks, [ + { context: 'codex-review-gate', integration_id: 15368 }, + { context: 'bugbot-review-gate', integration_id: 15368 }, + { context: 'required-ci-gate', integration_id: 15368 }, + ]); + assert.deepEqual(review.bypass_actors, []); + assert.deepEqual(review.rules[0].parameters.required_status_checks, [{ context: 'human-review-gate', integration_id: 15368 }]); + assert.equal(review.rules[1].parameters.required_review_thread_resolution, true); + assert(f.reads.includes(`contents/CODEOWNERS?ref=${base}`)); + assert(!f.reads.some((resource) => resource.includes('CODEOWNERS?ref=head'))); +}); + +test('CI bypass honors CODEOWNERS precedence and the last global rule', async (t) => { + const f = await fixture(t, { githubCodeowners: '* @Alice\n* @Carol\n', codeowners: '* @Bob\n' }); + await f.run('activate', ['--evidence-pr', '1', '--apply']); + assert.deepEqual(f.mutations[0].body.bypass_actors, [{ actor_id: 103, actor_type: 'User', bypass_mode: 'pull_request' }]); + assert(!f.reads.includes(`contents/CODEOWNERS?ref=${base}`)); +}); + +test('a global owner team becomes a native team bypass actor without copying its members', async (t) => { + const f = await fixture(t, { codeowners: '* @worldcoin/protocol\n' }); + await f.run('activate', ['--evidence-pr', '1', '--apply']); + assert.deepEqual(f.mutations[0].body.bypass_actors, [{ actor_id: 14554659, actor_type: 'Team', bypass_mode: 'pull_request' }]); + assert.deepEqual(f.mutations[1].body.bypass_actors, []); + assert(!f.reads.some((resource) => resource.includes('/members'))); + assert(!f.reads.some((resource) => resource.startsWith('collaborators/'))); + await f.run('restore', ['--apply']); + assert.deepEqual(f.live, f.original); + assert.equal(f.rulesets.size, 0); +}); + +test('GitHub response key order does not change verification of ruleset conditions', async (t) => { + const f = await fixture(t, { reorderedConditions: true }); + await f.run('activate', ['--evidence-pr', '1', '--apply']); + assert.equal(f.live.required_pull_request_reviews.required_approving_review_count, 0); +}); + +test('missing global owners, non-writable owners, bots and unreadable CODEOWNERS cannot grant bypass', async (t) => { + for (const options of [{ codeowners: '/docs/ @Alice' }, + { codeowners: '*' }, { readOnlyOwner: true }, { botOwner: true }, { codeownersError: true }]) { + const f = await fixture(t, options); + await assert.rejects(() => f.run('activate', ['--evidence-pr', '1', '--apply']), /CI bypass|CODEOWNERS access denied/); + assert.deepEqual(f.mutations, []); + } +}); + +test('foreign, secret, missing or non-writable teams cannot receive CI bypass', async (t) => { + for (const options of [{ codeowners: '* @another-org/protocol' }, { secretTeam: true }, { readOnlyTeam: true }, { missingTeam: true }]) { + const f = await fixture(t, { codeowners: '* @worldcoin/protocol', ...options }); + await assert.rejects(() => f.run('activate', ['--evidence-pr', '1', '--apply']), /CI bypass team/); + assert.deepEqual(f.mutations, []); + } +}); + +test('an unexpected review bypass or CI owner cannot relax the original approval requirement', async (t) => { + for (const options of [{ reviewBypass: true }, { wrongCiOwner: true }, { badRuleset: 'world-chain-review-policy' }]) { + const f = await fixture(t, options); + await assert.rejects(() => f.run('activate', ['--evidence-pr', '1', '--apply']), /keeping the native review requirement/); + assert.deepEqual(f.live, f.original); + assert(!f.mutations.some((item) => item.resource === 'branches/main/protection/required_pull_request_reviews')); + } +}); + +test('rollback restores both previous rulesets, including their previous bypass actors', async (t) => { + const f = await fixture(t, { existingRulesets: [ + { id: 50, ...rulesetBody() }, + { id: 60, ...ciRulesetBody([{ actor_id: 103, actor_type: 'User', bypass_mode: 'pull_request' }]) }, + ] }); + await f.run('activate', ['--evidence-pr', '1', '--apply']); + await f.run('restore', ['--apply']); + assert.deepEqual(f.live, f.original); + assert.deepEqual([...f.rulesets.values()], f.originalRulesets); + assert.deepEqual(f.mutations.slice(3).map((item) => item.resource), ['branches/main/protection/required_pull_request_reviews', 'rulesets/50', 'rulesets/60']); +}); + +test('migration from the combined ruleset installs CI protection before removing its old CI requirement', async (t) => { + const old = { id: 50, ...rulesetBody() }; + old.rules[0].parameters.required_status_checks = GATES.map((context) => ({ context, integration_id: 15368 })); + const f = await fixture(t, { existingRulesets: [old] }); + await f.run('activate', ['--evidence-pr', '1', '--apply']); + assert.deepEqual(f.mutations.map((item) => item.resource), ['rulesets', 'rulesets/50', 'branches/main/protection/required_pull_request_reviews']); + await f.run('restore', ['--apply']); + assert.deepEqual([...f.rulesets.values()], f.originalRulesets); +}); + +test('extending an existing CI-only bypass installs AI checks before removing their old requirements and restores the old split', async (t) => { + const review = { id: 50, ...rulesetBody() }; + review.rules[0].parameters.required_status_checks = GATES.filter((gate) => gate !== 'required-ci-gate') + .map((context) => ({ context, integration_id: 15368 })); + const ci = { id: 60, ...ciRulesetBody([{ actor_id: 14554659, actor_type: 'Team', bypass_mode: 'pull_request' }]) }; + ci.rules[0].parameters.required_status_checks = [{ context: 'required-ci-gate', integration_id: 15368 }]; + const f = await fixture(t, { codeowners: '* @worldcoin/protocol', existingRulesets: [review, ci] }); + await f.run('activate', ['--evidence-pr', '1', '--apply']); + assert.deepEqual(f.mutations.map((item) => item.resource), ['rulesets/60', 'rulesets/50', 'branches/main/protection/required_pull_request_reviews']); + assert.deepEqual(f.rulesets.get(60), { id: 60, ...ciRulesetBody(ci.bypass_actors) }); + assert.deepEqual(f.rulesets.get(50), { id: 50, ...rulesetBody() }); + await f.run('restore', ['--apply']); + assert.deepEqual([...f.rulesets.values()], f.originalRulesets); + assert.deepEqual(f.live, f.original); +}); + +test('a target-branch change during owner lookup requires a fresh readiness check', async (t) => { + const f = await fixture(t, { mainChanged: true }); + await assert.rejects(() => f.run('activate', ['--evidence-pr', '1', '--apply']), /Main changed/); + assert.deepEqual(f.mutations, []); +}); diff --git a/scripts/review-policy/github.cjs b/scripts/review-policy/github.cjs new file mode 100644 index 000000000..b56c3aa7d --- /dev/null +++ b/scripts/review-policy/github.cjs @@ -0,0 +1,445 @@ +'use strict'; + +const fs = require('node:fs'); +const { createHash } = require('node:crypto'); +const policy = require('./policy.cjs'); +const AI_POLL_INTERVAL_MS = 60000; +const POLICY_INPUTS = [ + ['', ['CODEOWNERS']], + ['.github', ['CODEOWNERS', 'review-policy.json', 'workflows', 'actions']], + ['scripts', ['review-policy']], + ['docs', ['CODEOWNERS']], +]; + +function fingerprint(value) { + const canonical = (item) => Array.isArray(item) ? item.map(canonical) + : item && typeof item === 'object' ? Object.fromEntries(Object.keys(item).sort().map((key) => [key, canonical(item[key])])) : item; + return createHash('sha256').update(JSON.stringify(canonical(value))).digest('hex'); +} + +class RateLimitError extends Error { + constructor(error, scope) { + super(`GitHub ${scope} API rate limit`, { cause: error }); + this.headers = error.response?.headers || {}; + } +} + +async function withRateLimitRecovery(operation, { core, sleep, now }) { + let pausedMs = 0; + for (let attempt = 0; ; attempt++) { + try { return await operation(pausedMs); } + catch (error) { + if (!(error instanceof RateLimitError)) throw error; + const headers = error.headers; + const reset = Number(headers['x-ratelimit-reset']) * 1000; + const retryAfter = Number(headers['retry-after']) * 1000; + const primaryWait = headers['x-ratelimit-remaining'] === '0' && Number.isFinite(reset) ? reset - now() + 1000 : 0; + const delay = Math.max(primaryWait, Number.isFinite(retryAfter) ? retryAfter : 0, 60000 * 2 ** attempt); + if (attempt >= 3 || pausedMs + delay > 65 * 60000) { + throw new Error(`${error.message}; recovery budget exhausted. Rerun Review policy after the quota resets.`); + } + core.info(`${error.message}; waiting until ${new Date(now() + delay).toISOString()}, then re-reading current evidence.`); + await sleep(delay); + pausedMs += delay; + } + } +} + +class Api { + constructor(github, repo, teamGithub) { + this.github = github; this.repo = repo; this.teamGithub = teamGithub; + this.cache = new Map(); + this.trees = new Map(); + this.policyRevisions = new Map(); + this.queue = Promise.resolve(); + this.rateLimit = undefined; + } + call(route, args = {}) { + const request = this.queue.then(() => this.request(route, args)); + this.queue = request.catch(() => {}); + return request; + } + async request(route, args) { + if (this.rateLimit) throw this.rateLimit; + const teamRequest = route.startsWith('GET /orgs/{org}/teams/{team_slug}'); + const client = teamRequest ? this.teamGithub : this.github; + if (!client) throw new Error('Configure REVIEW_POLICY_TEAM_TOKEN with organization Members: read for team ownership checks.'); + const key = route.startsWith('GET ') ? fingerprint([route, args]) : undefined; + const cached = this.cache.get(key); + let response; + try { + response = await client.request(route, { ...(!teamRequest ? this.repo : {}), ...args, + ...(cached ? { headers: { ...args.headers, 'if-none-match': cached.etag } } : {}), request: { timeout: 20000 } }); + } catch (error) { + if (error.status === 304 && cached) return structuredClone(cached.data); + const headers = error.response?.headers || {}; + if ([403, 429].includes(error.status) && (error.status === 429 || headers['x-ratelimit-remaining'] === '0' + || headers['retry-after'] !== undefined || /rate limit/i.test(error.message))) { + this.rateLimit = new RateLimitError(error, teamRequest ? 'team membership' : 'repository'); + throw this.rateLimit; + } + throw error; + } + if (response.status === 304 && cached) return structuredClone(cached.data); + if (key) { + if (response.headers?.etag) this.cache.set(key, { etag: response.headers.etag, data: structuredClone(response.data) }); + else this.cache.delete(key); + } + return response.data; + } + async all(route, args = {}, key) { + const result = []; + for (let page = 1; page <= 100; page++) { + const data = await this.call(route, { ...args, per_page: 100, page }); + const items = key ? data[key] : data; + if (!Array.isArray(items)) throw new Error(`Invalid paginated response: ${route}`); + result.push(...items); + if (items.length < 100) return result; + } + throw new Error(`Pagination limit exceeded: ${route}`); + } + async content(path, ref) { + const result = await this.call('GET /repos/{owner}/{repo}/contents/{path}', { path, ref }); + if (result.type !== 'file' || result.encoding !== 'base64' || result.size > 1000000) throw new Error(`Cannot read trusted ${path}`); + return Buffer.from(result.content, 'base64').toString('utf8'); + } + async tree(sha) { + if (!this.trees.has(sha)) { + const data = await this.call('GET /repos/{owner}/{repo}/git/trees/{tree_sha}', { tree_sha: sha }); + if (data.truncated || !Array.isArray(data.tree)) throw new Error('Incomplete Git tree; cannot verify review policy.'); + this.trees.set(sha, data.tree); + } + return this.trees.get(sha); + } + async policyRevision(sha) { + if (!this.policyRevisions.has(sha)) { + const root = await this.tree(sha); + const inputs = []; + for (const [directory, names] of POLICY_INPUTS) { + const entry = directory && root.find((item) => item.path === directory); + if (entry && entry.type !== 'tree') throw new Error(`Invalid review-policy directory: ${directory}`); + const entries = !directory ? root : entry ? await this.tree(entry.sha) : []; + for (const name of names) { + const item = entries.find((candidate) => candidate.path === name); + inputs.push([directory ? `${directory}/${name}` : name, item ? [item.mode, item.type, item.sha] : null]); + } + } + this.policyRevisions.set(sha, fingerprint(inputs)); + } + return this.policyRevisions.get(sha); + } + async samePolicy(before, after) { + return before === after || await this.policyRevision(before) === await this.policyRevision(after); + } +} + +async function targets({ github, context, core = { info: () => {} }, + sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)), now = Date.now }) { + return withRateLimitRecovery(() => findTargets(github, context), { core, sleep, now }); +} + +async function findTargets(github, context) { + const api = new Api(github, context.repo); + const event = context.payload; + if (context.eventName === 'workflow_run' && event.action !== 'completed' + && !(event.action === 'in_progress' && event.workflow_run?.run_attempt > 1)) return []; + if (context.eventName === 'push') { + if (event.deleted) return []; + if (!event.before || !event.after) throw new Error('Push is missing commit identities; cannot verify review-policy changes.'); + if (!/^0+$/.test(event.before) && await api.samePolicy(event.before, event.after)) return []; + return (await api.all('GET /repos/{owner}/{repo}/pulls', { state: 'open', base: 'main' })).map((pr) => pr.number); + } + if (event.pull_request) return [event.pull_request.number]; + if (event.issue?.pull_request) { + const command = /^\/(?:un)?approve$/; + return [event.comment?.body, event.changes?.body?.from].some((body) => command.test((body || '').trim())) ? [event.issue.number] : []; + } + if (context.eventName === 'workflow_dispatch') { + const number = Number(event.inputs?.pr); + if (!Number.isSafeInteger(number) || number < 1) throw new Error('A valid PR number is required.'); + return [number]; + } + const check = event.check_run; + if (check && check.app?.slug !== 'cursor') return []; + const sha = check?.head_sha || event.workflow_run?.head_sha; + if (!sha) return []; + const pulls = await api.all('GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls', { commit_sha: sha }); + return pulls.filter((pr) => pr.state === 'open' && pr.base.ref === 'main' && pr.head.sha === sha).map((pr) => pr.number); +} + +async function readCodeowners(api, ref) { + for (const path of ['.github/CODEOWNERS', 'CODEOWNERS', 'docs/CODEOWNERS']) { + try { return policy.parseCodeowners(await api.content(path, ref)); } + catch (error) { if (error.status !== 404) throw error; } + } + throw new Error('No CODEOWNERS found on the target branch.'); +} + +async function people(api, pr, reviews, paths) { + const writable = new Set(); + const candidates = [...new Set([pr.user, ...reviews.map((review) => review.user)].filter(policy.human).map((user) => user.login.toLowerCase()))]; + for (const username of candidates) { + try { + const result = await api.call('GET /repos/{owner}/{repo}/collaborators/{username}/permission', { username }); + if (['admin', 'maintain', 'write'].includes(result.permission) || result.user?.permissions?.push) writable.add(username); + } catch (error) { if (error.status !== 404) throw error; } + } + const ownerMembers = new Map(); + for (const owner of new Set(paths.flatMap((path) => path.requiredOwners))) { + if (!owner.includes('/')) { ownerMembers.set(owner, new Set([owner.slice(1)])); continue; } + const [org, team_slug] = owner.slice(1).split('/'); + try { + const members = await api.all('GET /orgs/{org}/teams/{team_slug}/members', { org, team_slug }); + ownerMembers.set(owner, new Set(members.filter(policy.human).map((user) => user.login.toLowerCase()))); + } catch (error) { + if (error instanceof RateLimitError) throw error; + throw new Error(`Cannot verify team ${owner} membership: ${error.status ? `HTTP ${error.status}` : error.message}; check REVIEW_POLICY_TEAM_TOKEN (organization Members: read).`); + } + } + return { writable, ownerMembers }; +} + +function summary(pr, classification, results, humanEvidenceFingerprint) { + const lines = [`PR #${pr.number}; head ${pr.head.sha}; base ${pr.base.sha}; risk: ${classification?.risk || 'unknown'}.`]; + if (humanEvidenceFingerprint) lines.push(`Verified human evidence fingerprint: ${humanEvidenceFingerprint}`); + if (classification) { + lines.push('', 'Paths setting the risk:'); + for (const item of classification.details.filter((item) => item.risk === classification.risk).slice(0, 40)) lines.push(`- ${item.path}`); + } + for (const [name, result] of Object.entries(results)) { + lines.push('', `${name}: ${result.state}`, result.reason || ''); + if (result.fastPath !== undefined) lines.push(`Owner fast path: ${result.fastPath}; human confirmations: ${result.confirmations.join(', ') || 'none'}; required: ${result.required}`); + lines.push(...(result.reasons || []).slice(0, 40)); + } + return lines.join('\n').slice(0, 60000); +} + +async function evaluate({ github, context, core, number, teamGithub, + sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)), now = Date.now }) { + const timing = {}; + try { + await withRateLimitRecovery((pausedMs) => evaluateOnce({ github, context, core, number, teamGithub, sleep, now, timing, pausedMs }), { core, sleep, now }); + } catch (error) { + core.setFailed(`Review policy could not verify requirements: ${error.message}`); + } +} + +async function evaluateOnce({ github, context, core, number, teamGithub, sleep, now, timing, pausedMs }) { + const api = new Api(github, context.repo, teamGithub); + const fullName = `${context.repo.owner}/${context.repo.repo}`; + const getPr = async () => { + const [pull, branch] = await Promise.all([ + api.call('GET /repos/{owner}/{repo}/pulls/{pull_number}', { pull_number: number }), + api.call('GET /repos/{owner}/{repo}/branches/{branch}', { branch: 'main' }), + ]); + // The PR API can retain an older base SHA after main advances. + return pull.base.ref === 'main' && pull.base.repo.full_name === fullName + ? { ...pull, base: { ...pull.base, sha: branch.commit.sha } } : pull; + }; + const pr = await getPr(); + if (pr.state !== 'open' || pr.base.ref !== 'main' || pr.base.repo.full_name !== fullName) return; + const sha = pr.head.sha; + const external = `review-policy:${fullName}:${number}:${sha}`; + const checks = await api.all('GET /repos/{owner}/{repo}/commits/{ref}/check-runs', { ref: sha, filter: 'all' }, 'check_runs'); + const own = (name) => checks.filter((check) => check.name === name && check.app?.slug === 'github-actions' && check.external_id === external).sort((a, b) => a.id - b.id)[0]; + const link = `${context.serverUrl || 'https://github.com'}/${fullName}/actions/runs/${context.runId}`; + const gateChecks = new Map(); + const gateStatuses = new Map(); + async function create(name, extra) { + return api.call('POST /repos/{owner}/{repo}/check-runs', { name, head_sha: sha, external_id: external, details_url: link, ...extra }); + } + async function publishStatus(name, result, check) { + const target_url = `${context.serverUrl || 'https://github.com'}/${fullName}/runs/${check.id}`; + const previous = gateStatuses.get(name); + if (previous?.state === result.state && previous.target_url === target_url) return; + const status = await api.call('POST /repos/{owner}/{repo}/statuses/{sha}', { + sha, context: name, state: result.state, target_url, description: `${name}: ${result.state}`, + }); + if (status.state !== result.state || status.context !== name || status.target_url !== target_url) { + throw new Error(`GitHub did not publish the expected ${name} commit status.`); + } + gateStatuses.set(name, status); + } + async function publish(name, result, text) { + const current = await getPr(); + if (current.state !== 'open' || current.head.sha !== sha || current.base.ref !== pr.base.ref) return false; + if (result.state === 'success' && !await api.samePolicy(pr.base.sha, current.base.sha)) return false; + let active = gateChecks.get(name); + if (result.state === 'pending' && active.status === 'completed') { + active = await create(name, { status: 'in_progress' }); + gateChecks.set(name, active); + } + const all = await api.all('GET /repos/{owner}/{repo}/commits/{ref}/check-runs', { ref: sha, filter: 'all' }, 'check_runs'); + const matching = all.filter((check) => check.name === name && check.app?.slug === 'github-actions' && check.external_id === external); + if (matching.some((check) => check.id > active.id)) return false; + // Invalidate merge clearance before updating diagnostic checks. + if (result.state !== 'success') await publishStatus(name, result, active); + for (const check of [active, ...matching.filter((check) => check.id !== active.id)]) { + const superseded = check.id !== active.id && result.state === 'pending'; + const conclusion = superseded ? 'failure' : result.state === 'pending' ? undefined : result.state; + const status = conclusion ? 'completed' : 'in_progress'; + const output = { title: `${name}: ${result.state}`, summary: superseded ? `Superseded; awaiting the current evaluation.\n\n${text}` : text }; + if (check.status === status && (check.conclusion || undefined) === conclusion + && (check.id !== active.id || (check.output?.title === output.title && check.output?.summary === output.summary))) continue; + const updated = await api.call('PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}', { + check_run_id: check.id, details_url: link, status, + ...(conclusion ? { conclusion, completed_at: new Date(now()).toISOString() } : {}), + output, + }); + if (updated.status !== status || (updated.conclusion || undefined) !== conclusion) throw new Error(`GitHub did not publish the expected ${name} result.`); + if (check.id === active.id) gateChecks.set(name, updated); + } + if (result.state === 'success' && gateStatuses.get(name)?.state !== 'success') { + const latest = await getPr(); + if (latest.state !== 'open' || latest.head.sha !== sha || latest.base.ref !== pr.base.ref + || !await api.samePolicy(pr.base.sha, latest.base.sha)) return false; + const latestChecks = await api.all('GET /repos/{owner}/{repo}/commits/{ref}/check-runs', { ref: sha, filter: 'all' }, 'check_runs'); + if (latestChecks.some((check) => check.name === name && check.app?.slug === 'github-actions' + && check.external_id === external && check.id > active.id)) return false; + await publishStatus(name, result, active); + } + return true; + } + let classification; + let results = {}; + try { + let observation = own('review-policy-observed'); + if (!observation) observation = await create('review-policy-observed', { + status: 'completed', conclusion: 'neutral', started_at: new Date(now()).toISOString(), + output: { title: 'First observation of this PR head', summary: `Head ${sha}; PR #${number}.` }, + }); + for (const name of policy.GATES) { + gateChecks.set(name, await create(name, { status: 'in_progress' })); + await publish(name, { state: 'pending' }, `Re-evaluating PR #${number}, head ${sha}.`); + } + const checkoutSha = process.env.REVIEW_POLICY_BASE_SHA; + if (!checkoutSha || !await api.samePolicy(checkoutSha, pr.base.sha)) throw new Error('Target review policy changed since checkout; rerun Review policy.'); + const config = JSON.parse(fs.readFileSync('.github/review-policy.json', 'utf8')); + const files = await api.all('GET /repos/{owner}/{repo}/pulls/{pull_number}/files', { pull_number: number }); + if (files.length !== pr.changed_files) throw new Error('Incomplete PR file list (GitHub limits this API to 3000 files); split the PR.'); + const paths = policy.changedPaths(files); + if (paths.includes('.github/workflows/review-policy-events.yml')) { + throw new Error('PRs cannot change the review-event notifier; restore it or use a controlled migration with native review protection enabled.'); + } + classification = policy.classify(paths, config); + const rules = await readCodeowners(api, pr.base.sha); + const owners = policy.ownership(paths, rules); + const sameHead = (await api.all('GET /repos/{owner}/{repo}/pulls', { state: 'open', base: 'main' })).filter((pull) => pull.head.sha === sha); + if (sameHead.length !== 1) throw new Error('Multiple open PRs share this head SHA; close duplicates to avoid sharing human gate results.'); + const groups = policy.requiredCi(paths, config); + const workflowIds = {}; + for (const workflow of new Set(groups.map((group) => group.workflow))) { + workflowIds[workflow] = (await api.call('GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}', { workflow_id: workflow })).id; + } + async function checkIdentity(current) { + if (current.state !== 'open' || current.head.sha !== sha || current.base.ref !== pr.base.ref + || !await api.samePolicy(pr.base.sha, current.base.sha)) { + throw new Error('PR head or target review policy changed while collecting evidence; rerun Review policy.'); + } + } + async function readHumanEvidence(reviews, comments) { + if (!reviews) [reviews, comments] = await Promise.all([ + api.all('GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews', { pull_number: number }), + api.all('GET /repos/{owner}/{repo}/issues/{issue_number}/comments', { issue_number: number }), + ]); + const humans = await people(api, pr, reviews, owners); + const humanReviews = [...policy.latestReviews(reviews)].map(([login, review]) => ({ login, state: review.state })) + .sort((a, b) => a.login.localeCompare(b.login)); + const humanParticipants = new Set([pr.user.login.toLowerCase(), ...humanReviews.map((review) => review.login)]); + return { + result: policy.humanGate({ pr, risk: classification.risk, paths: owners, reviews, comments, ...humans }), + fingerprint: fingerprint({ + head: sha, base: pr.base.sha, risk: classification.risk, paths: owners, + author: { login: pr.user.login.toLowerCase(), human: policy.human(pr.user) }, + authorApproved: policy.authorApproved(comments, pr.user.login), reviews: humanReviews, + writable: [...humans.writable].filter((login) => humanParticipants.has(login)).sort(), + ownerMembers: [...humans.ownerMembers].map(([owner, members]) => [owner, [...members].sort()]).sort(), + }), + }; + } + const completedJobs = new Map(); + async function readEvidence() { + await checkIdentity(await getPr()); + const [reviews, comments, reactions, checks, allRuns] = await Promise.all([ + api.all('GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews', { pull_number: number }), + api.all('GET /repos/{owner}/{repo}/issues/{issue_number}/comments', { issue_number: number }), + api.all('GET /repos/{owner}/{repo}/issues/{issue_number}/reactions', { issue_number: number }), + api.all('GET /repos/{owner}/{repo}/commits/{ref}/check-runs', { ref: sha, filter: 'all' }, 'check_runs'), + api.all('GET /repos/{owner}/{repo}/actions/runs', { head_sha: sha, event: 'pull_request' }, 'workflow_runs'), + ]); + const runs = allRuns.filter((run) => Object.values(workflowIds).includes(run.workflow_id)); + const jobs = new Map(); + for (const id of new Set(Object.values(workflowIds))) { + const run = runs.filter((run) => run.workflow_id === id).sort((a, b) => b.id - a.id)[0]; + if (run?.status === 'completed') { + const key = Number.isInteger(run.run_attempt) ? fingerprint([run.id, run.run_attempt, run.updated_at, run.conclusion]) : undefined; + let runJobs = key && completedJobs.get(key); + if (!runJobs) { + runJobs = await api.all('GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs', { run_id: run.id, filter: 'latest' }, 'jobs'); + if (key && runJobs.every((job) => job.status === 'completed')) completedJobs.set(key, runJobs); + } + jobs.set(run.id, runJobs); + } + } + const human = await readHumanEvidence(reviews, comments); + const cursorChecks = checks.filter((check) => check.name === 'Cursor Bugbot' && check.app?.slug === 'cursor'); + const evidenceResults = { + 'codex-review-gate': policy.codexGate(reviews, reactions, sha, observation.started_at), + 'bugbot-review-gate': policy.bugbotGate(cursorChecks, reviews, sha), + 'human-review-gate': human.result, + 'required-ci-gate': policy.ciGate(groups, runs, jobs, workflowIds, pr), + }; + await checkIdentity(await getPr()); + return { results: evidenceResults, humanFingerprint: human.fingerprint }; + } + async function finalEvidence() { + let candidate = await readEvidence(); + for (let attempt = 0; attempt < 3; attempt++) { + if (candidate.results['human-review-gate'].state !== 'success') return candidate; + const human = await readHumanEvidence(); + await checkIdentity(await getPr()); + const rechecked = { results: { ...candidate.results, 'human-review-gate': human.result }, humanFingerprint: human.fingerprint }; + if (candidate.humanFingerprint === rechecked.humanFingerprint) return { ...rechecked, verified: true }; + candidate = rechecked; + } + throw new Error('Human evidence kept changing during final verification; no human clearance published. Rerun Review policy.'); + } + let published; + const deadline = timing.deadline ??= now() - pausedMs + 30 * 60 * 1000; + while (true) { + // Human clearance must stay current even when AI checks are bypassed. + const evidence = await finalEvidence(); + results = evidence.results; + const waitingForAI = () => ['codex-review-gate', 'bugbot-review-gate'].some((name) => results[name].state === 'pending'); + const aiWaiting = waitingForAI(); + const expired = now() - pausedMs >= deadline; + if (aiWaiting && expired) for (const name of ['codex-review-gate', 'bugbot-review-gate']) { + if (results[name].state === 'pending') results[name] = { state: 'failure', reason: 'No completed review after 30 minutes; rerun Review policy.' }; + } + const text = summary(pr, classification, results, evidence.verified ? evidence.humanFingerprint : undefined); + if (text !== published) { + const current = await getPr(); + if (current.head.sha !== sha || current.base.ref !== pr.base.ref || current.state !== 'open') return; + await checkIdentity(current); + for (const name of policy.GATES) if (!await publish(name, results[name], text)) return; + published = text; + } + if (!aiWaiting || expired) { await core.summary.addRaw(`
${text.replaceAll('&', '&').replaceAll('<', '<')}
`).write(); return; } + core.info(`Waiting for AI reviews on PR #${number}, ${sha.slice(0, 7)}.`); + await sleep(Math.min(AI_POLL_INTERVAL_MS, Math.max(0, deadline - (now() - pausedMs)))); + } + } catch (error) { + if (error instanceof RateLimitError) throw error; + const reason = `Review policy could not verify requirements: ${error.message}`; + for (const name of policy.GATES) if (gateChecks.has(name)) { + try { await publish(name, { state: 'failure' }, reason); } + catch (publicationError) { + if (publicationError instanceof RateLimitError) throw publicationError; + core.info(`Could not publish ${name}: ${publicationError.message}`); + } + } + core.setFailed(reason); + } +} + +module.exports = { Api, targets, readCodeowners, people, summary, evaluate }; diff --git a/scripts/review-policy/github.test.cjs b/scripts/review-policy/github.test.cjs new file mode 100644 index 000000000..5bb44ca8c --- /dev/null +++ b/scripts/review-policy/github.test.cjs @@ -0,0 +1,918 @@ +'use strict'; + +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const vm = require('node:vm'); +const { createHash } = require('node:crypto'); +const { evaluate, targets, Api, readCodeowners, people } = require('./github.cjs'); +const { GATES } = require('./policy.cjs'); +const { rulesetBody, ciRulesetBody, reviewSettings } = require('./admin.cjs'); + +const head = 'a'.repeat(40); +const base = 'b'.repeat(40); +const now = Date.parse('2026-10-19T10:00:00Z'); +const at = new Date(now).toISOString(); +const repo = { owner: 'worldcoin', repo: 'world-chain' }; +const context = { repo, runId: 123, payload: {}, eventName: 'workflow_dispatch' }; +const codexReview = { id: 1, user: { login: 'chatgpt-codex-connector[bot]', type: 'Bot' }, + state: 'COMMENTED', commit_id: head, submitted_at: at }; +const authorApproval = { id: 1, user: { login: 'owner', type: 'User' }, body: '/approve', created_at: at }; + +function gitTrees(versions = {}) { + const trees = new Map(); + const entry = (path, type, sha) => ({ path, type, sha, mode: type === 'tree' ? '040000' : '100644' }); + for (const [ref, changes] of Object.entries({ [base]: {}, 'ordinary-main': {}, + 'new-main': { CODEOWNERS: 'new-owners' }, changed: { CODEOWNERS: 'old-owners' }, ...versions })) { + const paths = { CODEOWNERS: 'owners', '.github/review-policy.json': 'config', + '.github/workflows': 'workflows', '.github/actions': 'actions', 'scripts/review-policy': 'scripts', ...changes }; + const root = []; + for (const directory of ['', '.github', 'scripts', 'docs']) { + const entries = Object.entries(paths).filter(([path, sha]) => sha !== null + && (path.includes('/') ? path.slice(0, path.lastIndexOf('/')) : '') === directory) + .map(([path, sha]) => entry(path.slice(directory ? directory.length + 1 : 0), + ['.github/workflows', '.github/actions', 'scripts/review-policy'].includes(path) ? 'tree' : 'blob', sha)); + if (!directory) root.push(...entries); + else { + const sha = createHash('sha1').update(JSON.stringify(entries)).digest('hex'); + trees.set(sha, { tree: entries, truncated: false }); + root.push(entry(directory, 'tree', sha)); + } + } + trees.set(ref, { tree: root, truncated: false }); + } + return trees; +} + +function fake(options = {}) { + const trees = gitTrees(options.policyVersions); + const pr = { number: 1, state: 'open', changed_files: 1, user: { login: 'owner', type: 'User' }, + head: { sha: head, ref: 'branch', repo: { id: 1 } }, base: { ref: 'main', sha: options.prBase || base, repo: { full_name: 'worldcoin/world-chain' } } }; + const checks = [ + { id: 1, name: 'Cursor Bugbot', head_sha: head, status: 'completed', conclusion: 'success', app: { slug: 'cursor' } }, + ...(options.checks || []), + ]; + const calls = []; + const statuses = []; + let ticks = 0; + let nextCheckId = Math.max(...checks.map((check) => check.id)) + 1; + const github = { request: async (route, args) => { + calls.push({ route, args }); + let data; + if (route === 'GET /repos/{owner}/{repo}/pulls/{pull_number}') { + data = structuredClone(pr); + if (options.moveHead && ++ticks > 3) data.head.sha = 'c'.repeat(40); + } else if (route === 'GET /repos/{owner}/{repo}/branches/{branch}') data = { commit: { sha: base } }; + else if (route === 'GET /repos/{owner}/{repo}/git/trees/{tree_sha}') { + data = trees.get(args.tree_sha); + if (!data) throw new Error(`Unknown Git tree: ${args.tree_sha}`); + } + else if (route === 'GET /repos/{owner}/{repo}/commits/{ref}/check-runs') data = { check_runs: structuredClone(checks) }; + else if (route === 'POST /repos/{owner}/{repo}/statuses/{sha}') { + data = { id: statuses.length + 1, ...args }; + statuses.unshift(data); + } else if (route === 'POST /repos/{owner}/{repo}/check-runs') { + data = { id: nextCheckId++, app: { slug: 'github-actions' }, ...args }; + checks.push(data); + } else if (route === 'PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}') { + data = checks.find((check) => check.id === args.check_run_id); + Object.assign(data, args); + } else if (route === 'GET /repos/{owner}/{repo}/pulls/{pull_number}/files') data = options.files || [{ filename: 'README.md' }]; + else if (route === 'GET /repos/{owner}/{repo}/contents/{path}') { + if (args.path === '.github/CODEOWNERS') throw Object.assign(new Error('Not found'), { status: 404 }); + data = { type: 'file', encoding: 'base64', size: 20, content: Buffer.from(options.codeowners || '* @owner @reviewer').toString('base64') }; + } else if (route === 'GET /repos/{owner}/{repo}/pulls') data = options.duplicate ? [pr, { ...pr, number: 2 }] : [pr]; + else if (route === 'GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}') data = { id: args.workflow_id === 'review-policy-tests.yml' ? 1 : 2 }; + else if (route === 'GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews') data = options.reviews || (options.noCodex ? [] : [codexReview]); + else if (route === 'GET /repos/{owner}/{repo}/issues/{issue_number}/comments') data = options.comments || []; + else if (route === 'GET /repos/{owner}/{repo}/issues/{issue_number}/reactions') data = options.reactions || []; + else if (route === 'GET /repos/{owner}/{repo}/actions/runs') data = { workflow_runs: options.noCI ? [] : [1, 2].map((id) => ({ + id, workflow_id: id, run_attempt: 1, event: 'pull_request', head_sha: head, pull_requests: [{ number: 1 }], status: 'completed', conclusion: 'success', + })) }; + else if (route === 'GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs') data = { jobs: [{ name: args.run_id === 1 ? 'review-policy-tests' : 'check-large-files', status: 'completed', conclusion: 'success' }] }; + else if (route === 'GET /repos/{owner}/{repo}/collaborators/{username}/permission') data = { permission: 'write' }; + else if (route === 'GET /orgs/{org}/teams/{team_slug}/members') data = options.members || []; + else throw new Error(`Unexpected API: ${route}`); + if (options.respond) data = options.respond(route, args, structuredClone(data)); + return { data: structuredClone(data) }; + } }; + const failures = []; + const messages = []; + const core = { info: (text) => messages.push(text), setFailed: (text) => failures.push(text), summary: { addRaw: () => ({ write: async () => {} }) } }; + return { github, core, checks, statuses, failures, calls, messages, pr }; +} + +async function run(options = {}) { + process.env.REVIEW_POLICY_BASE_SHA = options.base || base; + const fixture = fake(options); + let clock = now; + await evaluate({ github: fixture.github, teamGithub: options.teamAccess ? fixture.github : undefined, + context: { ...context, ...options.context }, core: fixture.core, number: 1, now: () => clock, + sleep: async (ms) => { clock += ms; options.afterSleep?.(fixture, ms); } }); + return fixture; +} + +test('PR events dispatch the controller on trusted main without attaching its cancellable evaluator to the PR', async () => { + const workflow = fs.readFileSync('.github/workflows/review-policy.yml', 'utf8'); + const request = workflow.match(/^ request:\n([\s\S]*?)^ targets:/m)?.[1]; + assert.match(request, /if: github\.event_name == 'pull_request_target'/); + assert.match(request, /permissions:\n actions: write/); + assert(!request.includes('actions/checkout')); + assert.match(workflow, /targets:\n if: >-\n github\.event_name != 'pull_request_target' &&/); + assert.match(workflow, /group: review-policy-pr-\$\{\{ matrix\.pr \}\}\n cancel-in-progress: true/); + const script = request.split(' script: |\n')[1].replace(/^ {12}/gm, ''); + const calls = []; + await vm.runInNewContext(`(async () => { ${script} })()`, { + github: { rest: { actions: { createWorkflowDispatch: async (args) => calls.push(args) } } }, + context: { repo, payload: { pull_request: { number: 1204, head: { ref: 'untrusted-pr-branch' } } } }, + }); + assert.equal(calls.length, 1); + assert.equal(calls[0].owner, repo.owner); + assert.equal(calls[0].repo, repo.repo); + assert.equal(calls[0].workflow_id, 'review-policy.yml'); + assert.equal(calls[0].ref, 'main'); + assert.equal(calls[0].inputs.pr, '1204'); + assert.equal(calls[0].request.timeout, 20000); +}); + +test('trusted controller publishes four successful checks on PR head, never on main', async () => { + const result = await run(); + assert.deepEqual(result.failures, []); + for (const name of GATES) { + const check = result.checks.find((check) => check.name === name); + assert.equal(check.head_sha, head); + assert.equal(check.conclusion, 'success', name); + assert.match(check.output.summary, /Verified human evidence fingerprint: [a-f0-9]{64}/); + } + assert(result.calls.every((call) => call.args.request.timeout === 20000)); +}); + +test('background events publish merge statuses on the PR head with matching diagnostic checks', async (t) => { + const workflow = fs.readFileSync('.github/workflows/review-policy.yml', 'utf8'); + assert.match(workflow.split(' evaluate:')[1], / statuses: write/); + for (const eventName of ['workflow_dispatch', 'workflow_run', 'issue_comment']) await t.test(eventName, async () => { + const result = await run({ context: { eventName } }); + assert.deepEqual(result.failures, []); + assert.equal(result.statuses.length, GATES.length * 2); + for (const name of GATES) { + const check = result.checks.find((check) => check.name === name); + const statuses = result.statuses.filter((status) => status.context === name); + assert.deepEqual(statuses.map((status) => status.state), ['success', 'pending']); + assert(statuses.every((status) => status.sha === head && status.target_url === `https://github.com/worldcoin/world-chain/runs/${check.id}`)); + const pending = result.calls.findIndex((call) => call.args.context === name && call.args.state === 'pending'); + const completed = result.calls.findIndex((call) => call.args.check_run_id === check.id && call.args.conclusion === 'success'); + const success = result.calls.findIndex((call) => call.args.context === name && call.args.state === 'success'); + assert(pending < completed && completed < success); + } + }); +}); + +test('head, policy or evaluator replacement during check publication prevents a successful commit status', async (t) => { + for (const change of ['head', 'policy', 'evaluator']) await t.test(change, async () => { + let changed = false; + const result = await run({ respond: (route, args, data) => { + if (route.startsWith('PATCH ') && args.conclusion === 'success') changed = true; + if (!changed) return data; + if (change === 'head' && route.endsWith('/pulls/{pull_number}')) data.head.sha = 'new-head'; + if (change === 'policy' && route.endsWith('/branches/{branch}')) data.commit.sha = 'new-main'; + if (change === 'evaluator' && route.endsWith('/check-runs')) { + data.check_runs.push({ ...data.check_runs.find((check) => check.name === GATES[0]), id: 10000 }); + } + return data; + } }); + assert.deepEqual(result.failures, []); + assert(result.statuses.every((status) => status.state === 'pending')); + }); +}); + +test('commit status publication errors cannot report a successful evaluation', async (t) => { + for (const failure of ['denied', 'mismatched response']) await t.test(failure, async () => { + const result = await run({ respond: (route, args, data) => { + if (route.endsWith('/statuses/{sha}') && args.state === 'success') { + if (failure === 'denied') throw Object.assign(new Error('Forbidden'), { status: 403 }); + return { ...data, context: 'wrong-context' }; + } + return data; + } }); + assert.equal(result.failures.length, 1); + for (const name of GATES) { + assert.equal(result.statuses.find((status) => status.context === name).state, 'failure'); + assert.equal(result.checks.find((check) => check.name === name).conclusion, 'failure'); + } + }); +}); + +test('the controller accepts Cursor reusing its reviewed patch after a rebase', async () => { + const result = await run({ checks: [{ id: 2, name: 'Cursor Bugbot', head_sha: head, + app: { slug: 'cursor' }, status: 'completed', conclusion: 'neutral', started_at: at, + output: { title: 'Bugbot Review', summary: 'Bugbot Analysis Progress (3s elapsed)\n\n✅ Reviewed patch is unchanged (3s)', + text: 'Bugbot skipped this commit because its changes match the last review.' } }] }); + assert.deepEqual(result.failures, []); + const check = result.checks.find((item) => item.name === 'bugbot-review-gate'); + assert.equal(check.head_sha, head); + assert.equal(check.conclusion, 'success'); + assert.match(check.output.summary, /Bugbot confirms the reviewed patch is unchanged/); +}); + +test('reruns find completed reviewer checks hidden by the default latest-attempt filter', async () => { + let sleeps = 0; + const result = await run({ + respond: (route, args, data) => route === 'GET /repos/{owner}/{repo}/commits/{ref}/check-runs' && args.filter !== 'all' + ? { check_runs: data.check_runs.filter((check) => check.name !== 'Cursor Bugbot') } : data, + afterSleep: () => { sleeps++; }, + }); + assert.deepEqual(result.failures, []); + assert.equal(sleeps, 0, 'completed reviews must not wait for the AI timeout'); + for (const name of GATES) assert.equal(result.checks.find((check) => check.name === name).conclusion, 'success', name); +}); + +test('unapprove updates every duplicate gate, including the newer green check GitHub displays', async () => { + const external_id = `review-policy:worldcoin/world-chain:1:${head}`; + const checks = [10, 20].map((id) => ({ id, name: 'human-review-gate', head_sha: head, external_id, + app: { slug: 'github-actions' }, status: 'completed', conclusion: 'success' })); + const result = await run({ checks, files: [{ filename: 'ordinary-config.yaml' }], + comments: [authorApproval, { ...authorApproval, id: 2, body: '/unapprove', created_at: new Date(now + 1000).toISOString() }] }); + assert.deepEqual(result.failures, []); + const humanChecks = result.checks.filter((check) => check.name === 'human-review-gate'); + assert(humanChecks.length > 2); + for (const check of humanChecks) assert.equal(check.conclusion, 'failure', `check ${check.id}`); +}); + +test('an older base SHA cached by the PR API does not replace current target policy', async () => { + const result = await run({ prBase: 'older-main' }); + assert.deepEqual(result.failures, []); + for (const name of GATES) { + const check = result.checks.find((check) => check.name === name); + assert.equal(check.conclusion, 'success', name); + assert.match(check.output.summary, new RegExp(`base ${base};`)); + } + assert(result.calls.filter((call) => call.route.includes('/contents/')).every((call) => call.args.ref === base)); +}); + +test('the target branch advancing during evaluation blocks clearance even if the PR API stays unchanged', async () => { + let reads = 0; + const result = await run({ respond: (route, _args, data) => route === 'GET /repos/{owner}/{repo}/branches/{branch}' && ++reads > 5 + ? { commit: { sha: 'new-main' } } : data }); + assert(!result.calls.some((call) => call.route.startsWith('PATCH ') && call.args.conclusion === 'success')); +}); + +test('ordinary main advances before startup or during AI polling do not interrupt the PR', async (t) => { + for (const phase of ['startup', 'polling']) await t.test(phase, async () => { + let advanced = phase === 'startup'; + let sleeps = 0; + const options = { noCodex: true, + respond: (route, _args, data) => route === 'GET /repos/{owner}/{repo}/branches/{branch}' && advanced + ? { commit: { sha: 'ordinary-main' } } : data, + afterSleep: () => { advanced = true; sleeps++; options.noCodex = false; }, + }; + const result = await run(options); + assert.deepEqual(result.failures, []); + assert.equal(sleeps, 1); + for (const name of GATES) assert.equal(result.checks.find((check) => check.name === name).conclusion, 'success', name); + const treeCalls = result.calls.filter((call) => call.route.endsWith('/git/trees/{tree_sha}')); + assert.equal(treeCalls.length, 5, 'immutable tree reads are shared and cached across identity checks'); + }); +}); + +test('policy changes during AI polling invalidate prior human clearance', async () => { + let advanced = false; + const result = await run({ noCodex: true, + respond: (route, _args, data) => route === 'GET /repos/{owner}/{repo}/branches/{branch}' && advanced + ? { commit: { sha: 'new-main' } } : data, + afterSleep: () => { advanced = true; }, + }); + assert.match(result.failures.join('\n'), /target review policy changed/); + assert.equal(result.checks.find((check) => check.name === 'human-review-gate').conclusion, 'failure'); + assert.equal(result.statuses.find((status) => status.context === 'human-review-gate').state, 'failure'); +}); + +test('re-evaluation invalidates old green checks while fresh AI evidence is pending', async () => { + const checks = GATES.map((name, id) => ({ id: id + 10, name, head_sha: head, + external_id: `review-policy:worldcoin/world-chain:1:${head}`, app: { slug: 'github-actions' }, status: 'completed', conclusion: 'success' })); + let observed = false; + const result = await run({ checks, noCodex: true, afterSleep: (fixture) => { + observed = true; + const codexChecks = fixture.checks.filter((check) => check.name === 'codex-review-gate'); + assert(codexChecks.every((check) => check.conclusion !== 'success')); + assert(codexChecks.some((check) => check.status === 'in_progress')); + } }); + assert(observed); + assert.deepEqual(result.failures, []); + assert(result.checks.filter((check) => check.name === 'codex-review-gate').every((check) => check.conclusion === 'failure')); +}); + +test('author confirmation changes during the AI wait cannot leave a successful human gate', async (t) => { + for (const change of ['revoke', 'edit', 'delete']) await t.test(change, async () => { + const options = { files: [{ filename: 'ordinary-config.yaml' }], noCodex: true, + comments: [structuredClone(authorApproval)] }; + options.afterSleep = () => { + options.noCodex = false; + if (change === 'revoke') options.comments.push({ ...authorApproval, id: 2, body: '/unapprove', created_at: new Date(now + 30000).toISOString() }); + if (change === 'edit') options.comments[0].body = 'Still reviewing'; + if (change === 'delete') options.comments = []; + }; + const result = await run(options); + assert.deepEqual(result.failures, []); + assert(result.calls.some((call) => call.args.output?.title === 'human-review-gate: success')); + assert.equal(result.checks.find((check) => check.name === 'codex-review-gate').conclusion, 'success'); + assert.equal(result.checks.find((check) => check.name === 'human-review-gate').conclusion, 'failure'); + const statuses = result.statuses.filter((status) => status.context === 'human-review-gate'); + assert.deepEqual(statuses.map((status) => status.state), ['failure', 'success', 'pending']); + const revoked = result.calls.findIndex((call) => call.args.context === 'human-review-gate' && call.args.state === 'failure'); + const failedCheck = result.calls.findIndex((call) => call.args.output?.title === 'human-review-gate: failure'); + assert(revoked < failedCheck); + }); +}); + +test('human clearance is independently verified and revoked while both AI reviewers remain unavailable', async () => { + let sleeps = 0; + let unavailable = true; + const options = { files: [{ filename: 'ordinary-config.yaml' }], noCodex: true, + comments: [structuredClone(authorApproval)], + respond: (route, _args, data) => { + if (unavailable && route === 'GET /repos/{owner}/{repo}/commits/{ref}/check-runs') { + data.check_runs = data.check_runs.filter((check) => check.name !== 'Cursor Bugbot'); + } + return data; + }, + }; + options.afterSleep = (fixture) => { + for (const name of ['codex-review-gate', 'bugbot-review-gate']) { + assert.equal(fixture.checks.find((check) => check.name === name).status, 'in_progress'); + } + const human = fixture.checks.find((check) => check.name === 'human-review-gate'); + if (++sleeps === 1) { + assert.equal(human.conclusion, 'success'); + assert.match(human.output.summary, /Verified human evidence fingerprint: [a-f0-9]{64}/); + options.comments.push({ ...authorApproval, id: 2, body: '/unapprove', created_at: new Date(now + 30000).toISOString() }); + } else { + assert.equal(human.conclusion, 'failure'); + options.noCodex = false; + unavailable = false; + } + }; + const result = await run(options); + assert.deepEqual(result.failures, []); + assert.equal(sleeps, 2); + assert.equal(result.checks.find((check) => check.name === 'human-review-gate').conclusion, 'failure'); +}); + +test('AI and CI progress updates cannot invalidate unchanged human clearance', async () => { + let revision = 0; + let pending = true; + let sleeps = 0; + const result = await run({ files: [{ filename: 'ordinary-config.yaml' }], comments: [authorApproval], + respond: (route, _args, data) => { + const progress = `Progress update ${++revision}`; + const updatedAt = new Date(now + revision).toISOString(); + if (route === 'GET /repos/{owner}/{repo}/actions/runs') { + for (const run of data.workflow_runs) Object.assign(run, { updated_at: updatedAt, + ...(pending ? { status: 'in_progress', conclusion: null } : {}) }); + } + if (route === 'GET /repos/{owner}/{repo}/commits/{ref}/check-runs') { + const cursor = data.check_runs.find((check) => check.name === 'Cursor Bugbot'); + Object.assign(cursor, { output: { summary: progress }, ...(pending ? { status: 'in_progress', conclusion: null } : {}) }); + } + if (route === 'GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews') { + return [{ ...codexReview, body: progress, ...(pending ? { state: 'PENDING', submitted_at: null } : {}) }, + { id: 2, user: { login: 'reviewer', type: 'User' }, state: 'APPROVED', submitted_at: at, body: progress }]; + } + if (route === 'GET /repos/{owner}/{repo}/issues/{issue_number}/reactions') { + return [{ id: revision, user: { login: 'reviewer', type: 'User' }, content: '+1', created_at: updatedAt }]; + } + if (route === 'GET /repos/{owner}/{repo}/issues/{issue_number}/comments') { + return [...data, { id: 2, user: { login: 'cursor[bot]', type: 'Bot' }, body: progress, created_at: at }]; + } + return data; + }, + afterSleep: (fixture) => { + sleeps++; + assert.equal(fixture.checks.find((check) => check.name === 'human-review-gate').conclusion, 'success'); + for (const name of ['codex-review-gate', 'bugbot-review-gate', 'required-ci-gate']) { + assert.equal(fixture.checks.find((check) => check.name === name).status, 'in_progress'); + } + pending = false; + }, + }); + assert.deepEqual(result.failures, []); + assert.equal(sleeps, 1); + for (const name of GATES) assert.equal(result.checks.find((check) => check.name === name).conclusion, 'success', name); +}); + +test('dismissal or changes requested during the AI wait replaces the earlier approval', async (t) => { + for (const state of ['DISMISSED', 'CHANGES_REQUESTED']) await t.test(state, async () => { + const approval = { id: 2, user: { login: 'reviewer', type: 'User' }, state: 'APPROVED', commit_id: head, submitted_at: at }; + const options = { files: [{ filename: 'ordinary-config.yaml' }], reviews: [approval] }; + options.afterSleep = () => { options.reviews = [codexReview, { ...approval, state }]; }; + const result = await run(options); + assert.deepEqual(result.failures, []); + assert(result.calls.some((call) => call.args.output?.title === 'human-review-gate: success')); + assert.equal(result.checks.find((check) => check.name === 'codex-review-gate').conclusion, 'success'); + assert.equal(result.checks.find((check) => check.name === 'human-review-gate').conclusion, 'failure'); + }); +}); + +test('a failed CI rerun during the AI wait replaces the earlier successful CI result', async () => { + let rerun = false; + const options = { noCodex: true, + afterSleep: () => { options.noCodex = false; rerun = true; }, + respond: (route, _args, data) => { + if (rerun && route === 'GET /repos/{owner}/{repo}/actions/runs') { + data.workflow_runs[0] = { ...data.workflow_runs[0], run_attempt: 2, conclusion: 'failure' }; + } + return data; + } }; + const result = await run(options); + assert.deepEqual(result.failures, []); + assert(result.calls.some((call) => call.args.output?.title === 'required-ci-gate: success')); + assert.equal(result.checks.find((check) => check.name === 'codex-review-gate').conclusion, 'success'); + assert.equal(result.checks.find((check) => check.name === 'required-ci-gate').conclusion, 'failure'); +}); + +test('CI completed during the AI wait can pass without another controller run', async () => { + const options = { noCodex: true, noCI: true }; + options.afterSleep = () => { options.noCodex = false; options.noCI = false; }; + const result = await run(options); + assert.deepEqual(result.failures, []); + for (const name of GATES) assert.equal(result.checks.find((check) => check.name === name).conclusion, 'success', name); +}); + +test('an author approval removed between final snapshots blocks merge clearance', async () => { + let reads = 0; + const result = await run({ files: [{ filename: 'ordinary-config.yaml' }], comments: [authorApproval], + respond: (route, _args, data) => route === 'GET /repos/{owner}/{repo}/issues/{issue_number}/comments' && ++reads >= 2 ? [] : data }); + assert.deepEqual(result.failures, []); + assert.equal(result.checks.find((check) => check.name === 'human-review-gate').conclusion, 'failure'); + assert(!result.calls.some((call) => call.args.output?.title === 'human-review-gate: success')); +}); + +test('discussion-only comment updates cannot invalidate human clearance', async () => { + let reads = 0; + const result = await run({ respond: (route, _args, data) => route === 'GET /repos/{owner}/{repo}/issues/{issue_number}/comments' + ? [{ ...authorApproval, body: `Discussion update ${++reads}` }] : data }); + assert.deepEqual(result.failures, []); + for (const name of GATES) assert.equal(result.checks.find((check) => check.name === name).conclusion, 'success', name); +}); + +test('human confirmation evidence that keeps changing cannot produce successful gates', async () => { + let reads = 0; + const result = await run({ respond: (route, _args, data) => route === 'GET /repos/{owner}/{repo}/issues/{issue_number}/comments' + ? (++reads % 2 ? [authorApproval] : []) : data }); + assert.equal(result.failures.length, 1); + assert.match(result.failures[0], /Human evidence kept changing/); + for (const name of GATES) assert.equal(result.checks.find((check) => check.name === name).conclusion, 'failure', name); +}); + +test('first observation survives re-evaluation; old thumbs-up cannot become fresh', async () => { + const observation = { id: 10, name: 'review-policy-observed', app: { slug: 'github-actions' }, + external_id: `review-policy:worldcoin/world-chain:1:${head}`, started_at: at }; + const reaction = { content: '+1', user: { login: 'chatgpt-codex-connector[bot]' }, created_at: '2026-10-19T09:00:00Z' }; + const result = await run({ checks: [observation], noCodex: true, reactions: [reaction] }); + assert.equal(result.checks.filter((check) => check.name === 'review-policy-observed').length, 1); + assert.equal(result.checks.find((check) => check.name === 'codex-review-gate').conclusion, 'failure'); + assert(result.calls.some((call) => call.args.output?.summary?.includes('30 minutes'))); +}); + +test('missing CI remains pending rather than reporting success', async () => { + const result = await run({ noCI: true }); + assert.equal(result.checks.find((check) => check.name === 'required-ci-gate').status, 'in_progress'); + assert.equal(result.statuses.find((status) => status.context === 'required-ci-gate').state, 'pending'); +}); + +test('head movement never publishes success after the movement', async () => { + const result = await run({ moveHead: true }); + assert(!result.calls.some((call) => call.route.startsWith('PATCH ') && call.args.conclusion === 'success')); + assert(!result.statuses.some((status) => status.state === 'success')); +}); + +test('base movement, incomplete file list and duplicate PR heads fail closed', async () => { + for (const options of [{ base: 'changed' }, { files: [{ filename: 'a' }, { filename: 'b' }] }, { duplicate: true }]) { + const result = await run(options); + assert.equal(result.failures.length, 1); + for (const name of GATES) assert.equal(result.checks.find((check) => check.name === name).conclusion, 'failure', name); + } +}); + +test('API pagination reads all pages and CODEOWNERS falls back only on 404', async () => { + let pages = 0; + const api = new Api({ request: async (_route, args) => { + pages++; + return { data: Array.from({ length: args.page === 1 ? 100 : 3 }, (_, i) => i) }; + } }, repo); + assert.equal((await api.all('GET some-route')).length, 103); + assert.equal(pages, 2); + await assert.rejects(() => readCodeowners({ content: async () => { throw Object.assign(new Error('Forbidden'), { status: 403 }); } }, base), /Forbidden/); +}); + +test('event resolution ignores untrusted checks and locates PRs when webhook PR arrays are empty', async () => { + assert.deepEqual(await targets({ github: {}, context: { ...context, eventName: 'check_run', payload: { check_run: { app: { slug: 'github-actions' } } } } }), []); + const github = { request: async () => ({ data: [{ number: 1, state: 'open', base: { ref: 'main' }, head: { sha: head } }, + { number: 2, state: 'closed', base: { ref: 'main' }, head: { sha: head } }] }) }; + assert.deepEqual(await targets({ github, context: { ...context, eventName: 'workflow_run', payload: { action: 'completed', workflow_run: { head_sha: head } } } }), [1]); +}); + +test('CI completion and rerun start wake the controller; initial CI start does not restart it', async () => { + const workflow = fs.readFileSync('.github/workflows/review-policy.yml', 'utf8'); + assert.match(workflow, /types: \[in_progress, completed\]/); + assert.match(workflow, /github\.event\.workflow_run\.run_attempt > 1/); + let calls = 0; + const github = { request: async () => { + calls++; + return { data: [{ number: 1, state: 'open', base: { ref: 'main' }, head: { sha: head } }] }; + } }; + for (const [action, run_attempt, expected] of [ + ['requested', 1, []], ['in_progress', 1, []], ['in_progress', 2, [1]], ['completed', 1, [1]], + ]) { + const payload = { action, workflow_run: { head_sha: head, run_attempt } }; + assert.deepEqual(await targets({ github, context: { ...context, eventName: 'workflow_run', payload } }), expected); + } + assert.equal(calls, 2); +}); + +test('conditional reads validate cached data with GitHub and isolate pagination and caller mutations', async () => { + let version = 1; + let thrown = false; + const github = { request: async (_route, args) => { + const etag = `"${args.page}-${version}"`; + if (args.headers?.['if-none-match'] === etag) { + if (thrown) throw Object.assign(new Error('Not modified'), { status: 304 }); + thrown = true; + return { status: 304 }; + } + return { status: 200, headers: { etag }, data: [{ page: args.page, version }] }; + } }; + const api = new Api(github, repo); + const route = 'GET /repos/{owner}/{repo}/pulls'; + (await api.call(route, { page: 1 }))[0].version = 99; + assert.deepEqual(await api.call(route, { page: 1 }), [{ page: 1, version: 1 }]); + assert.deepEqual(await api.call(route, { page: 1 }), [{ page: 1, version: 1 }]); + assert.deepEqual(await api.call(route, { page: 2 }), [{ page: 2, version: 1 }]); + version++; + assert.deepEqual(await api.call(route, { page: 1 }), [{ page: 1, version: 2 }]); +}); + +test('requests are serialized and an ETag never hides an authorization error', async () => { + let active = 0; + let maximum = 0; + let denied = false; + const api = new Api({ request: async () => { + maximum = Math.max(maximum, ++active); + await Promise.resolve(); + active--; + if (denied) throw Object.assign(new Error('Forbidden'), { status: 403 }); + return { data: [], headers: { etag: '"same"' } }; + } }, repo); + await Promise.all([api.call('GET one'), api.call('GET two'), api.call('GET one')]); + assert.equal(maximum, 1); + denied = true; + await assert.rejects(() => api.call('GET one'), /Forbidden/); +}); + +test('polling avoids duplicate AI/CI reads and unchanged historical check writes', async () => { + const checks = Array.from({ length: 10 }, (_, index) => GATES.map((name, id) => ({ + id: 10 + index * 4 + id, name, head_sha: head, app: { slug: 'github-actions' }, + external_id: `review-policy:worldcoin/world-chain:1:${head}`, status: 'completed', conclusion: 'success', + }))).flat(); + let elapsed = 0; + const options = { checks, noCodex: true, + afterSleep: (_fixture, ms) => { + assert.equal(ms, 60000); + elapsed += ms; + if (elapsed >= 5 * 60000) options.noCodex = false; + } }; + const result = await run(options); + assert.deepEqual(result.failures, []); + const count = (suffix) => result.calls.filter((call) => call.route.endsWith(suffix)).length; + assert.equal(count('/actions/runs'), 6); + assert.equal(count('/reactions'), 6); + assert.equal(count('/reviews'), 12, 'human decisions still get a second fresh read'); + assert.equal(count('/permission'), 12); + assert.equal(count('/jobs'), 2, 'completed jobs are immutable for the observed run attempt'); + const oldCodex = checks.find((check) => check.name === 'codex-review-gate'); + const writes = result.calls.filter((call) => call.route.startsWith('PATCH ') && call.args.check_run_id === oldCodex.id); + assert.deepEqual(writes.map((call) => call.args.conclusion), ['failure', 'success']); + // Four gates add eight status writes and twelve final identity reads. + assert(result.calls.length < 270, `API budget exceeded: ${result.calls.length} requests`); + for (const name of GATES) assert.equal(result.statuses.filter((status) => status.context === name).length, 2); +}); + +test('one-minute polling detects a new Codex thumbs-up without requiring a webhook', async () => { + let sleeps = 0; + const options = { noCodex: true, afterSleep: (_fixture, ms) => { + assert.equal(ms, 60000); + assert.equal(++sleeps, 1); + options.reactions = [{ content: '+1', user: codexReview.user, created_at: new Date(now + 59000).toISOString() }]; + } }; + const result = await run(options); + assert.deepEqual(result.failures, []); + assert.equal(sleeps, 1); + assert.equal(result.checks.find((check) => check.name === 'codex-review-gate').conclusion, 'success'); +}); + +test('the last poll uses the remaining time without shortening the 30-minute AI budget', async () => { + process.env.REVIEW_POLICY_BASE_SHA = base; + const fixture = fake({ noCodex: true }); + const sleeps = []; + let clock = now; + await evaluate({ github: fixture.github, context, core: fixture.core, number: 1, now: () => clock, + sleep: async (ms) => { + assert(ms > 0 && ms <= 60000); + sleeps.push(ms); + clock += ms; + if (sleeps.length === 1) clock += 25000; + }, + }); + assert.deepEqual(fixture.failures, []); + assert.equal(sleeps.length, 30); + assert.equal(sleeps.at(-1), 35000); + assert.equal(clock - now, 30 * 60000); + assert.equal(fixture.checks.find((check) => check.name === 'codex-review-gate').conclusion, 'failure'); +}); + +test('completed job cache is invalidated by a new CI attempt even with the same run conclusion', async () => { + let rerun = false; + const options = { noCodex: true, + afterSleep: () => { rerun = true; options.noCodex = false; }, + respond: (route, args, data) => { + if (rerun && route.endsWith('/actions/runs')) data.workflow_runs[0].run_attempt = 2; + if (rerun && route.endsWith('/jobs') && args.run_id === 1) data.jobs[0].conclusion = 'skipped'; + return data; + }, + }; + const result = await run(options); + assert.deepEqual(result.failures, []); + assert.equal(result.calls.filter((call) => call.route.endsWith('/jobs')).length, 3); + assert.equal(result.checks.find((check) => check.name === 'required-ci-gate').conclusion, 'failure'); +}); + +function rateLimit(headers = {}, status = 403) { + return Object.assign(new Error('API rate limit exceeded'), { status, response: { headers } }); +} + +test('rate-limit reset restarts from fresh evidence instead of retrying a stale success publication', async () => { + let throttled = false; + let waits = 0; + const options = { files: [{ filename: 'ordinary-config.yaml' }], comments: [authorApproval], + respond: (route, args, data) => { + if (!throttled && route.startsWith('PATCH ') && args.output.title === 'human-review-gate: success') { + throttled = true; + throw rateLimit({ 'x-ratelimit-remaining': '0', 'x-ratelimit-reset': String(now / 1000 + 120) }); + } + return data; + }, + afterSleep: (_fixture, ms) => { + waits++; + assert.equal(ms, 121000); + options.comments = []; + }, + }; + const result = await run(options); + assert.equal(waits, 1); + assert.deepEqual(result.failures, []); + assert(result.messages.some((message) => message.includes('rate limit'))); + assert.equal(result.checks.filter((check) => check.name === 'review-policy-observed').length, 1); + for (const check of result.checks.filter((check) => check.name === 'human-review-gate')) assert.equal(check.conclusion, 'failure'); + for (const name of GATES.filter((name) => name !== 'human-review-gate')) { + assert.equal(result.checks.filter((check) => check.name === name).at(-1).conclusion, 'success'); + } +}); + +test('rate-limit recovery respects head changes and does not publish clearance on the old head', async () => { + let throttled = false; + const result = await run({ respond: (route, _args, data) => { + if (!throttled && route.endsWith('/reviews')) { throttled = true; throw rateLimit({ 'retry-after': '90' }, 429); } + return data; + }, afterSleep: (fixture, ms) => { + assert.equal(ms, 90000); + fixture.pr.state = 'closed'; + fixture.pr.head.sha = 'new-head'; + } }); + assert.deepEqual(result.failures, []); + assert(!result.calls.some((call) => call.route.startsWith('PATCH ') && call.args.conclusion === 'success')); +}); + +test('a throttled commit-status success is re-evaluated after an approval is revoked', async () => { + let throttled = false; + const options = { files: [{ filename: 'ordinary-config.yaml' }], comments: [authorApproval], + respond: (route, args, data) => { + if (!throttled && route.endsWith('/statuses/{sha}') && args.context === 'human-review-gate' && args.state === 'success') { + throttled = true; + throw rateLimit({ 'retry-after': '60' }, 429); + } + return data; + }, afterSleep: () => { options.comments = []; }, + }; + const result = await run(options); + assert(throttled); + assert.deepEqual(result.failures, []); + assert.equal(result.statuses.find((status) => status.context === 'human-review-gate').state, 'failure'); + assert(result.checks.filter((check) => check.name === 'human-review-gate').every((check) => check.conclusion === 'failure')); +}); + +test('team-token rate limits recover separately from missing membership permissions', async () => { + let reads = 0; + let waits = 0; + const result = await run({ codeowners: '* @worldcoin/protocol', members: [{ login: 'owner', type: 'User' }], teamAccess: true, + respond: (route, _args, data) => { + if (route.endsWith('/members') && ++reads === 1) throw rateLimit({ 'retry-after': '60' }, 429); + return data; + }, afterSleep: (_fixture, ms) => { waits++; assert.equal(ms, 60000); }, + }); + assert.deepEqual(result.failures, []); + assert.equal(waits, 1); + assert(result.messages.some((message) => message.includes('team membership API rate limit'))); + assert.equal(result.checks.filter((check) => check.name === 'human-review-gate').at(-1).conclusion, 'success'); +}); + +test('persistent throttling is bounded and permission errors do not trigger quota retries', async (t) => { + for (const [name, error, expectedWaits, message] of [ + ['secondary', rateLimit({}, 429), [60000, 120000, 240000], /recovery budget exhausted/], + ['too distant reset', rateLimit({ 'x-ratelimit-remaining': '0', 'x-ratelimit-reset': String(now / 1000 + 7200) }), [], /recovery budget exhausted/], + ['forbidden', Object.assign(new Error('Forbidden'), { status: 403 }), [], /Forbidden/], + ]) await t.test(name, async () => { + const waits = []; + const result = await run({ respond: (route, _args, data) => { + if (route.endsWith('/reviews')) throw error; + return data; + }, afterSleep: (_fixture, ms) => waits.push(ms) }); + assert.deepEqual(waits, expectedWaits); + assert.equal(result.failures.length, 1); + assert.match(result.failures[0], message); + }); +}); + +test('rate-limit waiting preserves the remaining AI budget instead of expiring or resetting it', async () => { + let polls = 0; + let throttled = false; + let rateWaits = 0; + const result = await run({ noCodex: true, + respond: (route, _args, data) => { + if (!throttled && polls === 1 && route.endsWith('/reviews')) { + throttled = true; + throw rateLimit({ 'retry-after': '2400' }, 429); + } + return data; + }, afterSleep: (_fixture, ms) => { + if (ms === 60000) assert(++polls <= 30, 'recovery must not restart the AI timeout'); + else { assert.equal(ms, 2400000); rateWaits++; } + }, + }); + assert.deepEqual(result.failures, []); + assert.equal(rateWaits, 1); + assert.equal(polls, 30, 'quota waiting must not consume the AI timeout'); + const gate = result.checks.filter((check) => check.name === 'codex-review-gate').at(-1); + assert.equal(gate.conclusion, 'failure'); + assert.match(gate.output.summary, /No completed review after 30 minutes/); +}); + +test('a rate-limit response stops already queued requests until recovery', async () => { + let calls = 0; + const api = new Api({ request: async () => { calls++; throw rateLimit({}, 429); } }, repo); + const results = await Promise.allSettled([api.call('GET one'), api.call('GET two'), api.call('POST three')]); + assert(results.every((result) => result.status === 'rejected')); + assert.equal(calls, 1); +}); + +test('target discovery also waits for the quota reset before retrying', async () => { + let attempts = 0; + let clock = now; + const github = { request: async () => { + if (++attempts === 1) throw rateLimit({ 'x-ratelimit-remaining': '0', 'x-ratelimit-reset': String(now / 1000 + 600) }); + return { data: [{ number: 1 }] }; + } }; + const result = await targets({ github, context: { ...context, eventName: 'push', payload: { before: '0'.repeat(40), after: base } }, now: () => clock, + sleep: async (ms) => { assert.equal(ms, 601000); clock += ms; } }); + assert.deepEqual(result, [1]); + assert.equal(attempts, 2); +}); + +test('author commands wake the controller on create, revoke, edit and delete; chatter does not', async () => { + const issue = { number: 1, pull_request: {} }; + for (const payload of [ + { comment: { body: '/approve' } }, { comment: { body: '/unapprove' } }, + { comment: { body: 'removed' }, changes: { body: { from: '/approve' } } }, + ]) assert.deepEqual(await targets({ github: {}, context: { ...context, eventName: 'issue_comment', payload: { issue, ...payload } } }), [1]); + for (const body of ['looks good', '/signoff', '/unsignoff', '> /approve', '/approve extra']) { + assert.deepEqual(await targets({ github: {}, context: { ...context, eventName: 'issue_comment', payload: { issue, comment: { body } } } }), []); + } +}); + +test('ordinary main pushes do not list or re-evaluate open PRs', async () => { + const fixture = fake(); + const result = await targets({ github: fixture.github, context: { ...context, eventName: 'push', + payload: { before: base, after: 'ordinary-main' } } }); + assert.deepEqual(result, []); + assert.equal(fixture.calls.length, 5); + assert(fixture.calls.every((call) => call.route.endsWith('/git/trees/{tree_sha}'))); +}); + +test('policy, ownership and workflow changes refresh open PRs, including additions and deletions', async (t) => { + for (const path of ['CODEOWNERS', '.github/CODEOWNERS', 'docs/CODEOWNERS', '.github/review-policy.json', + '.github/workflows', '.github/actions', 'scripts/review-policy']) { + for (const change of ['replacement', null]) await t.test(`${path}: ${change}`, async () => { + const fixture = fake({ policyVersions: { [base]: { [path]: 'original' }, updated: { [path]: change } } }); + const result = await targets({ github: fixture.github, context: { ...context, eventName: 'push', + payload: { before: base, after: 'updated' } } }); + assert.deepEqual(result, [1]); + }); + } + const fixture = fake({ policyVersions: { added: { '.github/CODEOWNERS': 'new-owner-file' } } }); + assert.deepEqual(await targets({ github: fixture.github, context: { ...context, eventName: 'push', + payload: { before: base, after: 'added' } } }), [1]); +}); + +test('incomplete policy trees fail closed rather than skipping a required refresh', async () => { + const fixture = fake({ respond: (route, _args, data) => route.endsWith('/git/trees/{tree_sha}') + ? { ...data, truncated: true } : data }); + await assert.rejects(() => targets({ github: fixture.github, context: { ...context, eventName: 'push', + payload: { before: base, after: 'ordinary-main' } } }), /Incomplete Git tree/); + assert(!fixture.calls.some((call) => call.route.endsWith('/pulls'))); +}); + +test('unreadable team membership cannot grant owner fast path', async () => { + const api = { call: async (route) => { + if (route.includes('collaborators')) return { permission: 'write' }; + }, all: async () => { + throw Object.assign(new Error('Forbidden'), { status: 403 }); + } }; + await assert.rejects(() => people(api, { user: { login: 'owner', type: 'User' } }, [], [{ requiredOwners: ['@worldcoin/team'] }]), /Cannot verify team/); +}); + +test('repository operations and team membership use separate authenticated clients', async () => { + const repoCalls = []; + const teamCalls = []; + const api = new Api({ request: async (route, args) => { repoCalls.push({ route, args }); return { data: {} }; } }, repo, + { request: async (route, args) => { teamCalls.push({ route, args }); return { data: [] }; } }); + await api.call('POST /repos/{owner}/{repo}/check-runs', { name: 'human-review-gate' }); + await api.all('GET /orgs/{org}/teams/{team_slug}/members', { org: 'worldcoin', team_slug: 'protocol' }); + assert.equal(repoCalls.length, 1); + assert.equal(teamCalls.length, 1); + assert.equal(repoCalls[0].args.repo, 'world-chain'); + assert.equal(teamCalls[0].args.repo, undefined); + assert.equal(teamCalls[0].args.request.timeout, 20000); + await assert.rejects(() => new Api({}, repo).call('GET /orgs/{org}/teams/{team_slug}/members'), /REVIEW_POLICY_TEAM_TOKEN/); +}); + +test('protocol members get the owner fast path and outsiders need a protocol owner approval', async () => { + const members = ['owner', 'reviewer'].map((login) => ({ login, type: 'User' })); + const result = await run({ codeowners: '* @worldcoin/protocol', members, teamAccess: true }); + assert.deepEqual(result.failures, []); + const gate = (value) => value.checks.find((check) => check.name === 'human-review-gate'); + assert.equal(gate(result).conclusion, 'success'); + assert.match(gate(result).output.summary, /Owner fast path: true/); + const outsider = await run({ codeowners: '* @worldcoin/protocol', members: members.slice(1), teamAccess: true }); + assert.deepEqual(outsider.failures, []); + assert.equal(gate(outsider).conclusion, 'failure'); + const covered = await run({ codeowners: '* @worldcoin/protocol', members: members.slice(1), teamAccess: true, + reviews: [codexReview, { id: 2, user: members[1], state: 'APPROVED', submitted_at: at }] }); + assert.equal(gate(covered).conclusion, 'success'); +}); + +test('critical protocol changes still need two distinct humans from the agreed confirmation policy', async () => { + const result = await run({ codeowners: '* @worldcoin/protocol', teamAccess: true, + members: ['owner', 'reviewer'].map((login) => ({ login, type: 'User' })), + files: [{ filename: 'CODEOWNERS' }], comments: [authorApproval], + reviews: [codexReview, { id: 2, user: { login: 'reviewer', type: 'User' }, state: 'APPROVED', submitted_at: at }] }); + const gate = result.checks.find((check) => check.name === 'human-review-gate'); + assert.equal(gate.conclusion, 'success'); + assert.match(gate.output.summary, /human confirmations: reviewer, owner; required: 2/); +}); + +test('membership removals during AI review invalidate earlier owner privileges', async () => { + const members = [{ login: 'owner', type: 'User' }]; + const result = await run({ codeowners: '* @worldcoin/protocol', members, teamAccess: true, noCodex: true, + afterSleep: () => { members.length = 0; }, + respond: (route, args, data) => route === 'GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews' && !members.length ? [codexReview] : data, + }); + assert.deepEqual(result.failures, []); + assert.equal(result.checks.find((check) => check.name === 'human-review-gate').conclusion, 'failure'); +}); + +test('new team members gain owner privileges on the next evidence read without activation', async () => { + const members = []; + const result = await run({ codeowners: '* @worldcoin/protocol', members, teamAccess: true, noCodex: true, + afterSleep: () => { members.push({ login: 'owner', type: 'User' }); }, + respond: (route, args, data) => route === 'GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews' && members.length ? [codexReview] : data, + }); + assert.deepEqual(result.failures, []); + assert.equal(result.checks.find((check) => check.name === 'human-review-gate').conclusion, 'success'); +}); + +test('team ownership without a membership credential fails closed with a configuration error', async () => { + const result = await run({ codeowners: '* @worldcoin/protocol' }); + assert.match(result.failures.join('\n'), /REVIEW_POLICY_TEAM_TOKEN/); + for (const name of GATES) assert.equal(result.checks.find((check) => check.name === name).conclusion, 'failure'); +}); + +test('activation permits bypass of AI and CI checks while protecting human approvals and threads', () => { + const rule = rulesetBody(); + assert.deepEqual(rule.bypass_actors, []); + const ci = ciRulesetBody([]); + assert.deepEqual(rule.rules[0].parameters.required_status_checks.map((check) => check.context), ['human-review-gate']); + assert.deepEqual(ci.rules[0].parameters.required_status_checks.map((check) => check.context), ['codex-review-gate', 'bugbot-review-gate', 'required-ci-gate']); + assert.equal(rule.rules[1].parameters.required_review_thread_resolution, true); + assert.equal(rule.rules[1].parameters.dismiss_stale_reviews_on_push, false); + assert.deepEqual(reviewSettings({ required_pull_request_reviews: { required_approving_review_count: 1, require_code_owner_reviews: true, dismiss_stale_reviews: false, require_last_push_approval: false } }), { + required_approving_review_count: 1, require_code_owner_reviews: true, dismiss_stale_reviews: false, require_last_push_approval: false, + }); +}); diff --git a/scripts/review-policy/policy.cjs b/scripts/review-policy/policy.cjs new file mode 100644 index 000000000..7eb29db76 --- /dev/null +++ b/scripts/review-policy/policy.cjs @@ -0,0 +1,161 @@ +'use strict'; + +const RISKS = { low: 0, important: 1, critical: 2 }; +const CODEX = new Set(['chatgpt-codex-connector[bot]', 'chatgpt-codex-connector']); +const CURSOR = new Set(['cursor[bot]']); +const GATES = ['codex-review-gate', 'bugbot-review-gate', 'human-review-gate', 'required-ci-gate']; +const lower = (value) => String(value || '').toLowerCase(); +const human = (user) => user?.type === 'User' && !lower(user.login).endsWith('[bot]'); + +function glob(pattern) { + let result = ''; + for (let i = 0; i < pattern.length; i++) { + const ch = pattern[i]; + if (ch === '*' && pattern[i + 1] === '*') { + i++; + if (pattern[i + 1] === '/') { i++; result += '(?:.*/)?'; } + else result += '.*'; + } else if (ch === '*') result += '[^/]*'; + else if (ch === '?') result += '[^/]'; + else result += ch.replace(/[\\^$+?.()|{}\[\]]/g, '\\$&'); + } + return result; +} + +function matches(path, pattern) { + return new RegExp(`^${glob(pattern)}$`).test(path); +} + +function changedPaths(files) { + return [...new Set(files.flatMap((file) => [file.filename, file.previous_filename].filter(Boolean)))]; +} + +function classify(paths, config) { + if (!paths.length) throw new Error('No changed paths; refusing an empty classification.'); + const details = paths.map((path) => { + let risk = config.defaultRisk; + for (const rule of config.riskRules) { + if (rule.patterns.some((pattern) => matches(path, pattern))) risk = rule.risk; + } + if (!(risk in RISKS)) throw new Error(`Unknown risk: ${risk}`); + return { path, risk }; + }); + return { risk: details.reduce((a, b) => RISKS[a] >= RISKS[b.risk] ? a : b.risk, 'low'), details }; +} + +function parseCodeowners(text) { + return text.split(/\r?\n/).flatMap((line, index) => { + line = line.trim(); + if (!line || line.startsWith('#')) return []; + const [pattern, ...rest] = line.split(/\s+/); + const comment = rest.findIndex((part) => part.startsWith('#')); + const owners = (comment < 0 ? rest : rest.slice(0, comment)).map(lower); + if (/[\\\[\]!]/.test(pattern) || owners.some((owner) => !/^@[a-z0-9-]+(?:\/[a-z0-9_.-]+)?$/.test(owner))) { + throw new Error(`Unsupported CODEOWNERS syntax on line ${index + 1}; ownership cannot be verified.`); + } + let source = pattern.replace(/^\//, ''); + const directory = source.endsWith('/'); + source = source.replace(/\/$/, ''); + const anchored = pattern.startsWith('/') || source.includes('/'); + const regex = new RegExp(`${anchored ? '^' : '(?:^|/)'}${glob(source)}${directory ? '/' : '(?:/|$)'}`); + return [{ pattern, owners, regex }]; + }); +} + +function ownership(paths, rules) { + const global = [...rules].reverse().find((rule) => rule.pattern === '*')?.owners || []; + return paths.map((path) => { + const owners = [...rules].reverse().find((rule) => rule.regex.test(path))?.owners || []; + return { path, owners, requiredOwners: owners.length ? owners : global }; + }); +} + +function latestReviews(reviews) { + const latest = new Map(); + for (const review of [...reviews].sort((a, b) => Date.parse(a.submitted_at) - Date.parse(b.submitted_at) || a.id - b.id)) { + if (human(review.user) && ['APPROVED', 'CHANGES_REQUESTED', 'DISMISSED'].includes(review.state)) { + latest.set(lower(review.user.login), review); + } + } + return latest; +} + +function authorApproved(comments, author) { + const commands = comments.filter((comment) => human(comment.user) && lower(comment.user.login) === lower(author) + && /^\/(?:un)?approve$/.test((comment.body || '').trim())); + commands.sort((a, b) => Date.parse(a.created_at) - Date.parse(b.created_at) || a.id - b.id); + return commands.at(-1)?.body.trim() === '/approve'; +} + +function humanGate({ pr, risk, paths, reviews, comments, writable, ownerMembers }) { + const isWritable = (login) => writable.has(lower(login)); + const isOwner = (login, owners) => owners.some((owner) => ownerMembers.get(owner)?.has(lower(login))); + const author = lower(pr.user.login); + const fastPath = human(pr.user) && isWritable(author) && paths.every((path) => path.owners.length && isOwner(author, path.owners)); + const latest = latestReviews(reviews); + const blockers = [...latest].filter(([login, review]) => isWritable(login) && review.state === 'CHANGES_REQUESTED'); + const approved = [...latest].filter(([login, review]) => login !== author && isWritable(login) && review.state === 'APPROVED') + .map(([login]) => login).filter((login) => paths.some((path) => isOwner(login, path.requiredOwners))); + const missing = paths.filter((path) => !(fastPath || (human(pr.user) && isWritable(author) && isOwner(author, path.owners))) + && !approved.some((login) => isOwner(login, path.requiredOwners))); + const authorApproval = human(pr.user) && isWritable(author) && authorApproved(comments, author); + const confirmations = new Set([...approved, ...(authorApproval ? [author] : [])]); + const required = risk === 'critical' ? 2 : risk === 'important' || !fastPath ? 1 : 0; + const reasons = [ + ...blockers.map(([login]) => `${login} requests changes`), + ...missing.map((path) => `Owner approval missing: ${path.path}`), + ...(confirmations.size < required ? [`${confirmations.size}/${required} distinct human confirmations`] : []), + ]; + return { state: reasons.length ? 'failure' : 'success', fastPath, required, confirmations: [...confirmations], reasons }; +} + +function codexGate(reviews, reactions, sha, cutoff) { + const review = reviews.some((item) => CODEX.has(item.user?.login) && item.commit_id === sha && item.submitted_at + && ['COMMENTED', 'APPROVED', 'CHANGES_REQUESTED'].includes(item.state)); + const reaction = reactions.some((item) => CODEX.has(item.user?.login) && item.content === '+1' + && Date.parse(item.created_at) >= Date.parse(cutoff)); + return { state: review || reaction ? 'success' : 'pending', reason: review ? 'Review on current SHA' : reaction ? 'Fresh Codex thumbs-up (time heuristic)' : 'Waiting for Codex on current SHA' }; +} + +function bugbotGate(checks, reviews, sha) { + const check = checks.filter((item) => item.name === 'Cursor Bugbot' && item.app?.slug === 'cursor' && item.head_sha === sha) + .sort((a, b) => b.id - a.id)[0]; + if (!check || check.status !== 'completed') return { state: 'pending', reason: 'Waiting for Cursor Bugbot on current SHA' }; + if (check.conclusion === 'success') return { state: 'success', reason: 'Bugbot completed successfully' }; + if (check.conclusion === 'neutral' + && check.output?.text?.trim() === 'Bugbot skipped this commit because its changes match the last review.') { + return { state: 'success', reason: 'Bugbot confirms the reviewed patch is unchanged' }; + } + const attested = reviews.some((review) => CURSOR.has(review.user?.login) && review.commit_id === sha + && review.state === 'COMMENTED' && Date.parse(review.submitted_at) >= Date.parse(check.started_at) + && //.test(review.body || '') + && /Cursor Bugbot has reviewed your changes[\s\S]*found \d+ potential issue/.test(review.body || '')); + if (check.conclusion === 'neutral' && attested) return { state: 'success', reason: 'Bugbot completed with findings; resolve every review thread' }; + return { state: 'failure', reason: `Bugbot ${check.conclusion}; no acceptable completed review` }; +} + +function requiredCi(paths, config) { + return config.ci.filter((group) => paths.some((path) => group.patterns.some((pattern) => matches(path, pattern)))); +} + +function ciGate(groups, runs, jobsByRun, workflowIds, pr) { + const reasons = []; + let pending = false; + for (const group of groups) { + const run = runs.filter((item) => item.workflow_id === workflowIds[group.workflow] && item.head_sha === pr.head.sha + && item.event === 'pull_request' && (item.pull_requests?.some((pull) => pull.number === pr.number) + || (!item.pull_requests?.length && item.head_branch === pr.head.ref && item.head_repository?.id === pr.head.repo?.id))) + .sort((a, b) => b.id - a.id)[0]; + if (!run || run.status !== 'completed') { + pending = true; reasons.push(`${group.id}: ${run ? 'running' : 'workflow missing'}`); continue; + } + if (run.conclusion !== 'success') { reasons.push(`${group.id}: ${run.conclusion}`); continue; } + const jobs = jobsByRun.get(run.id) || []; + const missing = group.jobs.filter((name) => !jobs.some((job) => job.name === name && job.status === 'completed' && job.conclusion === 'success')); + if (missing.length) reasons.push(`${group.id}: required jobs did not succeed: ${missing.join(', ')}`); + } + const failed = reasons.some((reason) => !reason.endsWith(': running') && !reason.endsWith(': workflow missing')); + return { state: failed ? 'failure' : pending ? 'pending' : 'success', reasons }; +} + +module.exports = { GATES, human, matches, changedPaths, classify, parseCodeowners, ownership, latestReviews, authorApproved, humanGate, codexGate, bugbotGate, requiredCi, ciGate }; diff --git a/scripts/review-policy/policy.test.cjs b/scripts/review-policy/policy.test.cjs new file mode 100644 index 000000000..729376051 --- /dev/null +++ b/scripts/review-policy/policy.test.cjs @@ -0,0 +1,178 @@ +'use strict'; + +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const p = require('./policy.cjs'); +const config = require('../../.github/review-policy.json'); +const sha = 'head'; +const at = '2026-10-19T10:00:00Z'; +const user = (login) => ({ login, type: 'User' }); +const bot = (login) => ({ login, type: 'Bot' }); +const review = (login, state = 'APPROVED', extra = {}) => ({ id: 1, user: user(login), state, submitted_at: at, commit_id: sha, ...extra }); +const command = (body, extra = {}) => ({ id: 1, user: user('author'), body, created_at: at, ...extra }); + +function humans({ risk = 'low', owned = true, reviews = [], comments = [], writable = new Set(['author', 'owner', 'second']), ...extra } = {}) { + return p.humanGate({ pr: { user: user('author') }, risk, + paths: p.ownership(['src/a.rs'], p.parseCodeowners(`* @owner @second ${owned ? '@author' : ''}`)), + ownerMembers: new Map(['author', 'owner', 'second'].map((login) => [`@${login}`, new Set([login])])), + reviews, comments, writable, ...extra }); +} + +test('agreed risks include exceptions, manifests, defaults and measured fixtures', () => { + for (const [path, expected] of [ + ['pkg/contracts/src/dispute/lib/GameTypes.sol', 'critical'], ['pkg/contracts/src/fees/FeeEscrow.sol', 'important'], + ['crates/pbh/src/lib.rs', 'low'], ['proofs/measurements.json', 'important'], + ['crates/builder/Cargo.toml', 'critical'], ['crates/chainspec/src/hardfork.rs', 'critical'], + ['proofs/protocol/src/types.rs', 'critical'], ['proofs/services/defender/src/lane.rs', 'critical'], + ['proofs/services/proposer/src/lib.rs', 'important'], ['crates/builder/tests/regression.rs', 'low'], + ['proofs/measured/core/tests/case.rs', 'critical'], ['docs/proof/release.md', 'important'], + ['specs/protocol.md', 'important'], ['docs/introduction.md', 'low'], ['brand-new-service/main.rs', 'important'], + ['scripts/review-policy/policy.test.cjs', 'critical'], ['.github/workflows/example.yml', 'critical'], + ['pkg/contracts/scripts/mainnet/Deploy.s.sol', 'critical'], ['Cargo.toml', 'critical'], ['Cargo.lock', 'important'], + ]) assert.equal(p.classify([path], config).risk, expected, path); + const paths = p.changedPaths([{ filename: 'docs/old.md', previous_filename: 'crates/evm/src/lib.rs' }, { filename: 'README.md', status: 'removed' }]); + assert.equal(p.classify(paths, config).risk, 'critical'); + assert.throws(() => p.classify([], config)); +}); + +test('CODEOWNERS precedence, anchored and recursive patterns, empty owners and fallback', () => { + const rules = p.parseCodeowners('* @global\n/src/ @src\n/src/private/ @private @other\n*.js @javascript\n/src/unowned/\n# comment\n'); + const entries = p.ownership(['src/a.rs', 'src/private/a.rs', 'other/src/a.rs', 'other/deep/a.js', 'src/unowned/a.rs'], rules); + assert.deepEqual(entries.map((entry) => entry.owners), [['@src'], ['@private', '@other'], ['@global'], ['@javascript'], []]); + assert.deepEqual(entries.at(-1).requiredOwners, ['@global']); + assert.throws(() => p.parseCodeowners('[ab]* @owner')); + assert.throws(() => p.parseCodeowners('!foo @owner')); + assert.throws(() => p.parseCodeowners('* owner@example.org')); + assert.equal(p.matches('a/b/c.rs', '**/*.rs'), true); + assert.equal(p.matches('Cargo.toml', '**/Cargo.toml'), true); + assert.equal(p.matches('a/x.rs', 'a/*.rs'), true); + assert.equal(p.matches('a/b/x.rs', 'a/*.rs'), false); +}); + +test('owner fast path only applies to low risk; important needs confirmation', () => { + assert.equal(humans().state, 'success'); + assert.equal(humans({ risk: 'important' }).state, 'failure'); + assert.equal(humans({ risk: 'important', comments: [command('/approve')] }).state, 'success'); + assert.equal(humans({ risk: 'important', reviews: [review('owner')] }).state, 'success'); +}); + +test('non owners always need covering owner approval, including on low-risk PRs', () => { + assert.equal(humans({ owned: false, comments: [command('/approve')] }).state, 'failure'); + assert.equal(humans({ owned: false, reviews: [review('owner')] }).state, 'success'); + const paths = p.ownership(['a/x', 'b/y'], p.parseCodeowners('* @global\na/ @author\nb/ @owner')); + assert.equal(humans({ paths, reviews: [review('owner')] }).state, 'success'); + assert.equal(humans({ paths }).state, 'failure'); +}); + +test('critical needs two distinct humans and owner coverage; risk escalation preserves confirmations', () => { + assert.equal(humans({ risk: 'critical', comments: [command('/approve')], reviews: [review('owner')] }).state, 'success'); + assert.equal(humans({ risk: 'critical', owned: false, comments: [command('/approve')], reviews: [review('owner')] }).state, 'success'); + assert.equal(humans({ risk: 'critical', reviews: [review('owner'), review('second')] }).state, 'success'); + assert.equal(humans({ risk: 'critical', reviews: [review('owner'), review('owner', 'APPROVED', { id: 2 })] }).state, 'failure'); + assert.equal(humans({ risk: 'critical', comments: [command('/approve')] }).state, 'failure'); +}); + +test('human approvals persist after push, comments do not dismiss, changes requested and dismissal revoke', () => { + const older = review('owner', 'APPROVED', { commit_id: 'old-head' }); + assert.equal(humans({ risk: 'important', reviews: [older, review('owner', 'COMMENTED', { id: 2 })] }).state, 'success'); + assert.equal(humans({ reviews: [older, review('owner', 'CHANGES_REQUESTED', { id: 2 })] }).state, 'failure'); + assert.equal(humans({ risk: 'important', reviews: [review('owner', 'DISMISSED')] }).state, 'failure'); + assert.equal(humans({ reviews: [review('owner', 'CHANGES_REQUESTED'), review('owner', 'APPROVED', { id: 2 })] }).state, 'success'); +}); + +test('author approval is an exact standalone author command; revocation, deletion and bot exclusion', () => { + for (const text of ['> /approve', 'please /approve', '/approve extra', '```\n/approve\n```', '/signoff', '/unsignoff']) assert.equal(p.authorApproved([command(text)], 'author'), false); + assert.equal(p.authorApproved([command(' /approve\n')], 'author'), true); + assert.equal(p.authorApproved([command('/approve', { user: user('other') })], 'author'), false); + assert.equal(p.authorApproved([command('/approve', { user: bot('author') })], 'author'), false); + assert.equal(p.authorApproved([command('/approve'), command('/unapprove', { id: 2 })], 'author'), false); + assert.equal(p.authorApproved([command('/approve'), command('/unapprove', { id: 2 }), command('/approve', { id: 3 })], 'author'), true); + assert.equal(p.authorApproved([], 'author'), false); + assert.equal(humans({ risk: 'important', comments: [command('/approve')], writable: new Set() }).state, 'failure'); + assert.equal(humans({ pr: { user: bot('author') } }).state, 'failure'); +}); + +test('CODEX only accepts current SHA reviews or its own fresh thumbs-up', () => { + const codex = (extra) => review('chatgpt-codex-connector[bot]', 'COMMENTED', extra); + assert.equal(p.codexGate([codex()], [], sha, at).state, 'success'); + for (const extra of [{ commit_id: 'old' }, { state: 'PENDING' }, { state: 'DISMISSED' }]) assert.equal(p.codexGate([codex(extra)], [], sha, at).state, 'pending'); + const reaction = { user: bot('chatgpt-codex-connector[bot]'), content: '+1', created_at: at }; + assert.equal(p.codexGate([], [reaction], sha, at).state, 'success'); + assert.equal(p.codexGate([], [{ ...reaction, created_at: '2026-10-18T10:00:00Z' }], sha, at).state, 'pending'); + assert.equal(p.codexGate([], [{ ...reaction, user: user('author') }], sha, at).state, 'pending'); + assert.equal(p.codexGate([], [{ ...reaction, content: 'eyes' }], sha, at).state, 'pending'); +}); + +test('Bugbot neutral requires a matching completed review, errors and cancellations block', () => { + const check = { id: 1, name: 'Cursor Bugbot', app: { slug: 'cursor' }, head_sha: sha, status: 'completed', conclusion: 'success', started_at: at }; + const findings = review('cursor[bot]', 'COMMENTED', { body: '\nCursor Bugbot has reviewed your changes using default effort and found 1 potential issue.' }); + assert.equal(p.bugbotGate([check], [], sha).state, 'success'); + assert.equal(p.bugbotGate([{ ...check, conclusion: 'neutral' }], [findings], sha).state, 'success'); + assert.equal(p.bugbotGate([{ ...check, conclusion: 'neutral' }], [], sha).state, 'failure'); + assert.equal(p.bugbotGate([{ ...check, conclusion: 'neutral' }], [{ ...findings, commit_id: 'old' }], sha).state, 'failure'); + assert.equal(p.bugbotGate([{ ...check, conclusion: 'cancelled' }], [findings], sha).state, 'failure'); + assert.equal(p.bugbotGate([{ ...check, app: { slug: 'fake' } }], [], sha).state, 'pending'); + assert.equal(p.bugbotGate([{ ...check, head_sha: 'old' }], [], sha).state, 'pending'); + assert.equal(p.bugbotGate([check, { ...check, id: 2, status: 'in_progress' }], [findings], sha).state, 'pending'); +}); + +test('Bugbot accepts its explicit unchanged-patch attestation only on the current completed Cursor check', () => { + const check = { id: 1, name: 'Cursor Bugbot', app: { slug: 'cursor' }, head_sha: sha, + status: 'completed', conclusion: 'neutral', started_at: at, + output: { title: 'Bugbot Review', summary: 'Bugbot Analysis Progress (3s elapsed)\n\n✅ Reviewed patch is unchanged (3s)', + text: 'Bugbot skipped this commit because its changes match the last review.' } }; + const result = p.bugbotGate([check], [], sha); + assert.equal(result.state, 'success'); + assert.match(result.reason, /reviewed patch is unchanged/); + for (const [change, expected] of [ + [{ head_sha: 'old' }, 'pending'], [{ app: { slug: 'fake' } }, 'pending'], + [{ status: 'in_progress' }, 'pending'], [{ conclusion: 'cancelled' }, 'failure'], + [{ conclusion: 'failure' }, 'failure'], [{ output: undefined }, 'failure'], + [{ output: { text: 'Bugbot encountered an internal error.' } }, 'failure'], + [{ output: { text: 'Bugbot skipped this commit.' } }, 'failure'], + [{ output: { text: 'Run cancelled by a newer commit.' } }, 'failure'], + [{ output: { summary: check.output.text } }, 'failure'], + ]) assert.equal(p.bugbotGate([{ ...check, ...change }], [], sha).state, expected, JSON.stringify(change)); + assert.equal(p.bugbotGate([check, { ...check, id: 2, status: 'in_progress' }], [], sha).state, 'pending'); + assert.equal(p.bugbotGate([check, { ...check, id: 2, output: undefined }], [], sha).state, 'failure'); +}); + +test('CI requires the current PR workflow and successful individual jobs, not skipped jobs', () => { + const pr = { number: 1, head: { sha, ref: 'branch', repo: { id: 5 } } }; + const groups = [{ id: 'rust', workflow: 'rust-ci.yml', jobs: ['tests', 'clippy'] }]; + const ids = { 'rust-ci.yml': 10 }; + const run = { id: 1, workflow_id: 10, head_sha: sha, event: 'pull_request', pull_requests: [{ number: 1 }], status: 'completed', conclusion: 'success' }; + const jobs = new Map([[1, ['tests', 'clippy'].map((name) => ({ name, status: 'completed', conclusion: 'success' }))]]); + const evaluate = (runs, data = jobs) => p.ciGate(groups, runs, data, ids, pr).state; + assert.equal(evaluate([run]), 'success'); + assert.equal(evaluate([]), 'pending'); + assert.equal(evaluate([{ ...run, conclusion: 'cancelled' }]), 'failure'); + assert.equal(evaluate([{ ...run, head_sha: 'old' }]), 'pending'); + assert.equal(evaluate([{ ...run, workflow_id: 999 }]), 'pending'); + assert.equal(evaluate([{ ...run, event: 'workflow_dispatch' }]), 'pending'); + assert.equal(evaluate([run], new Map([[1, [{ name: 'tests', status: 'completed', conclusion: 'skipped' }]]])), 'failure'); + assert.equal(evaluate([{ ...run, pull_requests: [], head_branch: 'branch', head_repository: { id: 5 } }]), 'success'); + assert.equal(evaluate([{ ...run, pull_requests: [], head_branch: 'branch', head_repository: { id: 6 } }]), 'pending'); +}); + +test('CI is selected from both rename paths and shared build inputs', () => { + for (const path of ['Cargo.toml', 'justfiles/proof.just', 'rust-toolchain.toml']) assert(p.requiredCi([path], config).some((group) => group.id === 'sp1')); + for (const path of ['Justfile', 'justfiles/contracts.just', '.gitmodules']) assert(p.requiredCi([path], config).some((group) => group.id === 'contracts')); + assert.deepEqual(p.requiredCi(['README.md'], config).map((group) => group.id), ['policy', 'large-files']); +}); + +test('every configured CI selector is present in its workflow, including measurement job selectors', () => { + for (const group of config.ci) { + if (['policy', 'large-files'].includes(group.id)) continue; + const text = fs.readFileSync(`.github/workflows/${group.workflow}`, 'utf8'); + const triggers = text.split('\njobs:')[0]; + const selectors = [...triggers.matchAll(/^\s+- ["']([^"']+)["']/gm)].map((match) => match[1]); + for (const pattern of group.patterns) assert(selectors.some((trigger) => p.matches(pattern, trigger)), `${group.id}: missing trigger ${pattern}`); + if (['sp1', 'nitro'].includes(group.id)) { + const section = text.split(` ${group.id}:\n`)[1]?.split(/\n \w+:\n/)[0]; + assert(section, `${group.id}: no measurement selector`); + for (const pattern of group.patterns) assert(section.includes(`'${pattern}'`), `${group.id}: missing job selector ${pattern}`); + } + } +}); diff --git a/scripts/safe-operation.py b/scripts/safe-operation.py new file mode 100644 index 000000000..1f36c29f3 --- /dev/null +++ b/scripts/safe-operation.py @@ -0,0 +1,404 @@ +#!/usr/bin/env python3 +"""Prepare Safe calls or propose an atomic WIP-1006 council transaction; never execute.""" + +import argparse +import json +import os +from pathlib import Path +import re +import subprocess +import sys +import tempfile +import time +from urllib.error import HTTPError, URLError +from urllib.parse import urlsplit +from urllib.request import HTTPRedirectHandler, Request, build_opener + +ROOT = Path(__file__).resolve().parents[1] +ZERO = "0x" + "00" * 20 + +# Sepolia entries from safe-global/safe-deployments at 7b1fb6d615ab2d2999550ec9166554b180e813e5. +# Delegatecall targets must match both the Safe version and the deployed code hash. +LIBRARIES = { + "1.3.0": { + "signMessage": ("0x98FFBBF51bb33A056B08ddf711f289936AafF717", "0x3ac65dea3cc9dd0d7b7b800f834e3d73415b4e944bb94555c3e4a08fb137e918"), + "multiSend": ("0x998739BFdAAdde7C933B942a68053933098f9EDa", "0x81db0e4afdf5178583537b58c5ad403bd47a4ac7f9bde2442ef3e341d433126a"), + }, + "1.4.1": { + "signMessage": ("0xd53cd0aB83D845Ac265BE939c57F53AD838012c9", "0x525c754a46b79e05543a59bb61e8de3c9eee0d955a59352409cbe67ea1077528"), + "multiSend": ("0x38869bf66a61cF6bDB996A6aE40D5853Fd43B526", "0x0e4f7fc66550a322d1e7688e181b75e217e662a4f3f4d6a29b22bc61217c4b77"), + }, + "1.5.0": { + "signMessage": ("0x4FfeF8222648872B3dE295Ba1e49110E61f5b5aa", "0xd61840855da008da59a00fc03fb71455b4f70bdca1f56f9504f072ed8d90c50e"), + "multiSend": ("0x218543288004CD07832472D464648173c77D7eB7", "0xca1147a12963172a93910c5cb2bfa5ad0e941c7f03fc7eb017dd06a8ea4e5604"), + }, +} +TX_FIELDS = [ + ("to", "address"), ("value", "uint256"), ("data", "bytes"), ("operation", "uint8"), + ("safeTxGas", "uint256"), ("baseGas", "uint256"), ("gasPrice", "uint256"), + ("gasToken", "address"), ("refundReceiver", "address"), ("nonce", "uint256"), +] + + +def address(value): + if not re.fullmatch(r"0x[0-9a-fA-F]{40}", value or "") or value.lower() == ZERO: + raise ValueError("expected a nonzero 20-byte address") + return value.lower() + + +def hex_bytes(value, size=None): + if not re.fullmatch(r"0x(?:[0-9a-fA-F]{2})*", value or ""): + raise ValueError("expected 0x-prefixed bytes") + if size is not None and len(value) != 2 + size * 2: + raise ValueError(f"expected {size} bytes") + return value.lower() + + +def uint256(value): + if isinstance(value, bool) or not re.fullmatch(r"[0-9]+", str(value)) or not 0 <= int(value) < 2 ** 256: + raise ValueError("expected an unsigned 256-bit integer") + return int(value) + + +def cast(*args, allow_invalid_signature=False): + # Cast failures can echo authenticated RPC URLs, so do not relay raw stderr. + try: + result = subprocess.run(["cast", *map(str, args)], capture_output=True, text=True, timeout=60) + except subprocess.TimeoutExpired as error: + raise ValueError(f"cast {args[0]} timed out after 60 seconds") from error + if result.returncode: + if allow_invalid_signature and result.returncode == 1 and result.stderr.startswith("Error: Validation failed."): + return "" + raise ValueError(f"cast {args[0]} failed; check inputs, contract ABI and RPC availability") + return result.stdout.strip() + + +class Chain: + def __init__(self, args): + self.rpc = args.rpc_url + if not self.rpc: + raise ValueError("set L1_RPC_URL or --rpc-url") + self.chain_id = int(cast("chain-id", "--rpc-url", self.rpc, "--rpc-timeout", 50)) + if self.chain_id != args.chain_id: + raise ValueError(f"RPC chain ID {self.chain_id} differs from expected {args.chain_id}") + self.safe = address(args.safe) + self.factory = address(args.factory) if getattr(args, "factory", None) else None + self.require_code(self.safe) + self.owners = sorted(address(owner) for owner in self.call(self.safe, "getOwners()(address[])", json_result=True)) + if len(self.owners) != 2 or len(set(self.owners)) != 2 or int(self.call(self.safe, "getThreshold()(uint256)")) != 2: + raise ValueError("expected a 2-of-2 Safe with two distinct owners") + modules, _ = self.call(self.safe, "getModulesPaginated(address,uint256)(address[],address)", "0x" + "0" * 39 + "1", 1, json_result=True) + if modules: + raise ValueError("Safe modules can bypass the threshold; disable them first") + + def call(self, target, signature, *args, json_result=False): + result = cast("call", target, signature, *args, "--rpc-url", self.rpc, "--rpc-timeout", 50, "--json") + values = json.loads(result) + if isinstance(values, dict): + if values.get("success") is not True or not isinstance(values.get("data"), list): + raise ValueError("unexpected cast call JSON response") + values = values["data"] + if not isinstance(values, list) or not values: + raise ValueError("expected ABI outputs from cast call") + # Cast JSON is an array of ABI outputs, including a nested array for address[]. + value = values[0] if len(values) == 1 else values + if not json_result and isinstance(value, bool): + return "true" if value else "false" + return value if json_result else str(value) + + def require_code(self, target): + if cast("code", address(target), "--rpc-url", self.rpc, "--rpc-timeout", 50) in ("0x", "0x0"): + raise ValueError(f"no contract code at {target}") + + +def write_json(path, value): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(value, indent=2) + "\n") + print(f"Wrote {path}") + + +def builder(chain, target, data, name): + chain.require_code(target) + return { + "version": "1.0", "chainId": str(chain.chain_id), "createdAt": int(time.time() * 1000), + "meta": {"name": name, "description": "Review targets and calldata before signing.", "createdFromSafeAddress": chain.safe}, + "transactions": [{"to": address(target), "value": "0", "data": hex_bytes(data), "contractMethod": None, "contractInputsValues": None}], + } + + +def council_data(chain, game): + game = address(game) + chain.require_code(game) + if int(chain.call(game, "gameType()(uint32)")) != 1006: + raise ValueError("game is not WIP-1006") + factory = address(chain.call(game, "disputeGameFactory()(address)")) + if chain.factory and factory != chain.factory: + raise ValueError("game belongs to a different factory/network") + chain.require_code(factory) + claim = hex_bytes(chain.call(game, "rootClaim()(bytes32)"), 32) + extra_data = hex_bytes(chain.call(game, "extraData()(bytes)")) + registered, _ = chain.call(factory, "games(uint32,bytes32,bytes)(address,uint64)", 1006, claim, extra_data, json_result=True) + if registered == ZERO or address(registered) != game: + raise ValueError("game is not registered in its factory") + if int(chain.call(game, "status()(uint8)")) != 0 or chain.call(game, "gameOver()(bool)") != "false": + raise ValueError("game no longer accepts proofs") + if int(chain.call(game, "proofBitmap()(uint8)")) & 4: + raise ValueError("game already has a council proof") + verifier = address(chain.call(game, "securityCouncil()(address)")) + if address(chain.call(verifier, "council()(address)")) != chain.safe: + raise ValueError("game council differs from GOVERNANCE_SAFE") + root = hex_bytes(chain.call(game, "rootId()(bytes32)"), 32) + digest = hex_bytes(chain.call(verifier, "attestationDigest(bytes32)(bytes32)", root), 32) + expected_hash = hex_bytes(chain.call(chain.safe, "getMessageHash(bytes)(bytes32)", digest), 32) + domain = cast("keccak", cast("abi-encode", "f(bytes32,uint256,address)", + cast("keccak", "EIP712Domain(uint256 chainId,address verifyingContract)"), chain.chain_id, chain.safe)) + message = cast("keccak", cast("abi-encode", "f(bytes32,bytes32)", + cast("keccak", "SafeMessage(bytes message)"), cast("keccak", digest))) + actual_hash = hex_bytes(cast("keccak", "0x1901" + domain[2:] + message[2:]), 32) + if actual_hash != expected_hash: + raise ValueError("Safe message hash differs from the council attestation; incompatible fallback handler") + return verifier, root, digest, expected_hash + + +def libraries(chain): + version = chain.call(chain.safe, "VERSION()(string)") + if chain.chain_id != 11155111 or version not in LIBRARIES: + raise ValueError("council proposals require Sepolia and Safe 1.3.0, 1.4.1 or 1.5.0") + targets = {} + for name, (target, expected_hash) in LIBRARIES[version].items(): + code = hex_bytes(cast("code", target, "--rpc-url", chain.rpc, "--rpc-timeout", 50)) + if code == "0x" or cast("keccak", code).lower() != expected_hash: + raise ValueError(f"canonical {name} library is missing or has unexpected bytecode") + targets[name] = address(target) + return version, targets + + +def multisend(actions): + packed = "0x" + for action in actions: + data = hex_bytes(action["data"])[2:] + packed += f'{action["operation"]:02x}' + address(action["to"])[2:] + packed += f'{uint256(action["value"]):064x}{len(data) // 2:064x}' + data + return cast("calldata", "multiSend(bytes)", packed) + + +def council_transaction(chain, game, recipient=None, nonce=None): + verifier, root, digest, message_hash = council_data(chain, game) + version, targets = libraries(chain) + current_nonce = uint256(chain.call(chain.safe, "nonce()(uint256)")) + nonce = current_nonce if nonce is None else uint256(nonce) + if nonce < current_nonce: + raise ValueError("Safe nonce was already executed; prepare a new transaction") + recipient = address(recipient or chain.safe) + actions = [ + {"to": targets["signMessage"], "operation": 1, "value": "0", "data": cast("calldata", "signMessage(bytes)", digest)}, + {"to": address(game), "operation": 0, "value": "0", "data": cast("calldata", "submitProofLane(bytes)", "0x02" + recipient[2:])}, + ] + transaction = { + "to": targets["multiSend"], "value": "0", "data": multisend(actions), "operation": 1, + "safeTxGas": "0", "baseGas": "0", "gasPrice": "0", "gasToken": ZERO, "refundReceiver": ZERO, "nonce": nonce, + } + tx_hash = hex_bytes(chain.call(chain.safe, + "getTransactionHash(address,uint256,bytes,uint8,uint256,uint256,uint256,address,address,uint256)(bytes32)", + *(transaction[name] for name, _ in TX_FIELDS)), 32) + # The handler executes the batch in Safe storage and reverts its state changes after simulation. + chain.call(chain.safe, "simulate(address,bytes)(bytes)", transaction["to"], transaction["data"]) + return { + "kind": "wip1006-council", "chainId": chain.chain_id, "safe": chain.safe, "safeVersion": version, + "game": address(game), "councilVerifier": verifier, "rootId": root, "recipient": recipient, + "attestationDigest": digest, "safeMessageHash": message_hash, "actions": actions, + "safeTransaction": transaction, "safeTxHash": tx_hash, + } + + +class NoRedirects(HTTPRedirectHandler): + def redirect_request(self, request, response, code, message, headers, new_url): + return None + + +class Service: + def __init__(self, url): + parsed = urlsplit(url) + if parsed.scheme != "https" or not parsed.netloc or parsed.username or parsed.password or parsed.query or parsed.fragment: + raise ValueError("Safe service URL must use HTTPS without credentials, query or fragment") + self.url = url.rstrip("/") + self.opener = build_opener(NoRedirects()) + + def request(self, method, path, body=None): + headers = {"Content-Type": "application/json", "Accept": "application/json"} + api_key = os.environ.get("SAFE_TRANSACTION_SERVICE_API_KEY") + if api_key: + if not re.fullmatch(r"[A-Za-z0-9._~-]+", api_key): + raise ValueError("SAFE_TRANSACTION_SERVICE_API_KEY must be a bearer token without whitespace") + headers["Authorization"] = "Bearer " + api_key + request = Request(self.url + path, data=json.dumps(body).encode() if body is not None else None, + headers=headers, method=method) + try: + with self.opener.open(request, timeout=20) as response: + data = response.read(2 * 1024 * 1024 + 1) + if len(data) > 2 * 1024 * 1024: + raise ValueError("Safe service response exceeds 2 MiB") + return json.loads(data) if data else None + except HTTPError as error: + hints = { + 400: "check transaction nonce, signature and Safe indexing", + 401: "set a valid SAFE_TRANSACTION_SERVICE_API_KEY", + 403: "check API permissions and Safe indexing", + 404: "check the service URL and wait for the Safe to be indexed", + 409: "check the pending transaction queue for a nonce conflict", + 429: "Safe API quota exceeded; wait or supply an API key", + } + raise ValueError(f"Safe service {method} failed (HTTP {error.code}); " + hints.get(error.code, "check service availability")) from error + except (URLError, TimeoutError, OSError) as error: + raise ValueError(f"Safe service {method} failed or timed out; check the Safe queue before retrying a proposal") from error + except (UnicodeError, json.JSONDecodeError) as error: + raise ValueError("Safe service returned malformed JSON; check the Safe queue before retrying a proposal") from error + + +def sign_transaction(args, chain, transaction): + typed = { + "types": { + "EIP712Domain": [{"name": "chainId", "type": "uint256"}, {"name": "verifyingContract", "type": "address"}], + "SafeTx": [{"name": name, "type": type_} for name, type_ in TX_FIELDS], + }, + "primaryType": "SafeTx", "domain": {"chainId": chain.chain_id, "verifyingContract": chain.safe}, + "message": transaction, + } + wallet = ["--account", args.account] if args.account else ["--" + args.wallet] + with tempfile.TemporaryDirectory() as directory: + file = Path(directory) / "safe-transaction.json" + file.write_text(json.dumps(typed)) + try: + # Inherit stderr/stdin so Cast can show wallet prompts; no private key arguments. + result = subprocess.run(["cast", "wallet", "sign", "--data", "--from-file", str(file), "--from", args.sender, *wallet], + stdout=subprocess.PIPE, text=True, timeout=300) + except subprocess.TimeoutExpired as error: + raise ValueError("wallet signing timed out after 300 seconds; nothing was proposed") from error + if result.returncode: + raise ValueError("wallet signing failed; nothing was proposed") + return hex_bytes(result.stdout.strip(), 65) + + +def describe(proposal): + print(f'Safe: {proposal["safe"]}\nGame: {proposal["game"]}\nCouncil verifier: {proposal["councilVerifier"]}\n' + f'Root ID: {proposal["rootId"]}\nReward recipient: {proposal["recipient"]}\n' + f'Safe nonce: {proposal["safeTransaction"]["nonce"]}\nSafe transaction hash: {proposal["safeTxHash"]}\n' + 'Actions: approve council attestation, then submit the council lane (atomic)') + + +def propose(args, chain): + proposal = json.loads(Path(args.transaction).read_text()) + if not isinstance(proposal, dict) or proposal.get("kind") != "wip1006-council": + raise ValueError("expected a council-submit Safe transaction file; import CALL batches in Transaction Builder") + expected = council_transaction(chain, proposal["game"], proposal["recipient"], proposal["safeTransaction"]["nonce"]) + if proposal != expected: + raise ValueError("proposal differs from the current game, Safe, chain or canonical transaction; prepare it again") + sender = address(args.sender) + if sender not in chain.owners: + raise ValueError("proposer must be a current Safe owner") + safe = cast("to-check-sum-address", chain.safe) + service = Service(args.service_url) + nonce = proposal["safeTransaction"]["nonce"] + pending = service.request("GET", f"/v2/safes/{safe}/multisig-transactions/?executed=false&nonce={nonce}") + if not isinstance(pending, dict) or not isinstance(pending.get("results"), list) or pending.get("next"): + raise ValueError("unexpected or incomplete Safe service pending-transaction response") + for entry in pending["results"]: + if not isinstance(entry, dict) or not isinstance(entry.get("safeTxHash"), str) or uint256(entry.get("nonce")) != nonce: + raise ValueError("unexpected Safe service pending transaction") + if hex_bytes(entry["safeTxHash"], 32) != proposal["safeTxHash"]: + raise ValueError("another pending transaction uses this nonce; prepare again with --nonce ") + if pending["results"]: + print(f'Transaction {proposal["safeTxHash"]} is already proposed; confirm it in the Safe UI.') + return + describe(proposal) + signature = sign_transaction(args, chain, proposal["safeTransaction"]) + if signature[-2:] not in ("1b", "1c") or not cast("wallet", "verify", "--address", sender, "--no-hash", + proposal["safeTxHash"], signature, allow_invalid_signature=True): + raise ValueError("wallet signature does not match the proposer and Safe transaction; nothing was proposed") + # Revalidate the game and simulation after the owner finishes reviewing in their wallet. + current_chain = Chain(args) + if sender not in current_chain.owners: + raise ValueError("proposer is no longer a Safe owner; nothing was proposed") + if council_transaction(current_chain, proposal["game"], proposal["recipient"], nonce) != proposal: + raise ValueError("council transaction changed while signing; prepare it again") + body = dict(proposal["safeTransaction"]) + for name, type_ in TX_FIELDS: + if type_ == "address": + body[name] = cast("to-check-sum-address", body[name]) + body.update(contractTransactionHash=proposal["safeTxHash"], sender=cast("to-check-sum-address", sender), + signature=signature, origin="World Chain devnet council") + service.request("POST", f"/v2/safes/{safe}/multisig-transactions/", body) + print(f'Proposed {proposal["safeTxHash"]}; the other owner can confirm and execute in the Safe UI. Nothing was executed.') + print(f"Safe queue: https://app.safe.global/transactions/queue?safe=sep:{safe}") + + +def prepare(args): + chain = Chain(args) + if args.operation == "call": + data = args.data or cast("calldata", args.signature, *args.arguments) + output = builder(chain, args.target, data, args.signature or "Administrative call") + print(f"Target: {address(args.target)}\nFunction: {args.signature or 'raw calldata'}\nArguments: {args.arguments}") + elif args.operation == "approve-pcrs": + verifier = args.verifier + if not verifier: + verifier = json.loads((ROOT / f"pkg/contracts/deployments/{args.network}-nitro.json").read_text())["nitroAttestationVerifier"] + if address(chain.call(address(verifier), "owner()(address)")) != chain.safe: + raise ValueError("Safe does not own the Nitro attestation verifier") + measurements = json.loads(Path(args.measurements).read_text())["nitro"] + hashes = [cast("keccak", hex_bytes(measurements[f"pcr{i}"], 48)) for i in range(3)] + output = builder(chain, verifier, cast("calldata", "approvePCRSet(bytes32,bytes32,bytes32)", *hashes), "Approve Nitro PCRs") + elif args.operation == "council-submit": + output = council_transaction(chain, args.game, args.recipient, args.nonce) + describe(output) + else: + propose(args, chain) + return + write_json(args.out, output) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--safe", default=os.environ.get("GOVERNANCE_SAFE")) + parser.add_argument("--rpc-url", default=os.environ.get("L1_RPC_URL")) + parser.add_argument("--chain-id", type=int, default=os.environ.get("L1_CHAIN_ID", "11155111")) + parser.add_argument("--factory", default=os.environ.get("DISPUTE_GAME_FACTORY"), help="Expected factory for council operations") + parser.add_argument("--out", help="Output file for preparation commands") + sub = parser.add_subparsers(dest="operation", required=True) + call = sub.add_parser("call", help="Prepare any zero-value contract CALL by ABI or raw calldata") + call.add_argument("target") + call.add_argument("signature", nargs="?") + call.add_argument("arguments", nargs="*") + call.add_argument("--data") + pcr = sub.add_parser("approve-pcrs", help="Hash release measurements and prepare their approval") + pcr.add_argument("--network", choices=("alphanet", "betanet"), default=os.environ.get("DEVNET_NETWORK", "alphanet")) + pcr.add_argument("--verifier") + pcr.add_argument("--measurements", default=str(ROOT / "proofs/measurements.json")) + submit = sub.add_parser("council-submit", help="Prepare one atomic Safe transaction approving and submitting the council proof") + submit.add_argument("--game", required=True) + submit.add_argument("--recipient") + submit.add_argument("--nonce", type=uint256, help="Safe nonce; defaults to the next onchain nonce") + proposal = sub.add_parser("propose", help="Sign as one owner and publish the prepared council transaction to the Safe queue") + proposal.add_argument("--transaction", required=True) + proposal.add_argument("--sender", required=True, help="Proposing Safe owner address") + proposal.add_argument("--service-url", default=os.environ.get("SAFE_TRANSACTION_SERVICE_URL", "https://api.safe.global/tx-service/sep/api")) + wallet = proposal.add_mutually_exclusive_group(required=True) + for option in ("browser", "interactive", "ledger", "trezor"): + wallet.add_argument("--" + option, dest="wallet", action="store_const", const=option) + wallet.add_argument("--account", help="Proposer's encrypted Foundry keystore") + args = parser.parse_args() + if (args.operation == "propose") == bool(args.out): + parser.error("preparation requires --out; propose uses --transaction without --out") + if args.operation == "call" and (bool(args.signature) == bool(args.data) or (args.data and args.arguments)): + parser.error("provide either a function signature with arguments or --data") + try: + prepare(args) + except (ValueError, OSError, KeyError, TypeError) as error: + # File and parse errors contain public inputs; cast errors are redacted above. + print(f"Error: {error}", file=sys.stderr) + return 1 + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/test_safe_operation.py b/scripts/test_safe_operation.py new file mode 100644 index 000000000..d46cb228e --- /dev/null +++ b/scripts/test_safe_operation.py @@ -0,0 +1,373 @@ +import argparse +from copy import deepcopy +import importlib.util +import json +from pathlib import Path +import subprocess +import tempfile +import unittest +from unittest.mock import Mock, patch +from urllib.error import HTTPError, URLError + +spec = importlib.util.spec_from_file_location("safe_operation", Path(__file__).with_name("safe-operation.py")) +operation = importlib.util.module_from_spec(spec) +spec.loader.exec_module(operation) + +SAFE = "0x" + "11" * 20 +GAME = "0x" + "22" * 20 +VERIFIER = "0x" + "33" * 20 +FACTORY = "0x" + "66" * 20 +ROOT = "0x" + "44" * 32 +DIGEST = "0x" + "55" * 32 +SIGN_MESSAGE = operation.LIBRARIES["1.4.1"]["signMessage"][0].lower() +MULTISEND = operation.LIBRARIES["1.4.1"]["multiSend"][0].lower() + + +class FakeChain: + safe = SAFE + chain_id = 11155111 + factory = None + registered_game = GAME + rpc = "local-test" + nonce = 7 + status = "0" + game_over = "false" + bitmap = "0" + + def __init__(self, owners): + self.owners = sorted(owners) + self.simulated = None + + def require_code(self, target): + operation.address(target) + + def call(self, target, signature, *args, json_result=False): + if signature == "gameType()(uint32)": + return "1006" + if signature == "securityCouncil()(address)": + return VERIFIER + if signature == "disputeGameFactory()(address)": + return FACTORY + if signature == "rootClaim()(bytes32)": + return ROOT + if signature == "extraData()(bytes)": + return "0x" + if signature == "games(uint32,bytes32,bytes)(address,uint64)": + assert args == (1006, ROOT, "0x") + return [self.registered_game, "1"] + if signature == "status()(uint8)": + return self.status + if signature == "gameOver()(bool)": + return self.game_over + if signature == "proofBitmap()(uint8)": + return self.bitmap + if signature == "nonce()(uint256)": + return str(self.nonce) + if signature == "council()(address)": + return SAFE + if signature == "rootId()(bytes32)": + return ROOT + if signature == "attestationDigest(bytes32)(bytes32)": + assert args == (ROOT,) + return DIGEST + if signature == "getMessageHash(bytes)(bytes32)": + assert args == (DIGEST,) + # Independently compute the Solidity handler's 0x1901/domain/struct hash. + domain = operation.cast("keccak", operation.cast("abi-encode", "f(bytes32,uint256,address)", + operation.cast("keccak", "EIP712Domain(uint256 chainId,address verifyingContract)"), self.chain_id, SAFE)) + message = operation.cast("keccak", operation.cast("abi-encode", "f(bytes32,bytes32)", + operation.cast("keccak", "SafeMessage(bytes message)"), operation.cast("keccak", DIGEST))) + return operation.cast("keccak", "0x1901" + domain[2:] + message[2:]) + if signature.startswith("getTransactionHash("): + types = [type_ for _, type_ in operation.TX_FIELDS] + type_hash = operation.cast("keccak", "SafeTx(" + ",".join(f"{type_} {name}" for name, type_ in operation.TX_FIELDS) + ")") + hashed_args = list(args) + hashed_args[2] = operation.cast("keccak", args[2]) + types[2] = "bytes32" + struct_hash = operation.cast("keccak", operation.cast("abi-encode", "f(bytes32," + ",".join(types) + ")", type_hash, *hashed_args)) + domain = operation.cast("keccak", operation.cast("abi-encode", "f(bytes32,uint256,address)", + operation.cast("keccak", "EIP712Domain(uint256 chainId,address verifyingContract)"), self.chain_id, SAFE)) + return operation.cast("keccak", "0x1901" + domain[2:] + struct_hash[2:]) + if signature == "simulate(address,bytes)(bytes)": + assert target == SAFE and args[0] == MULTISEND + self.simulated = args + return "0x" + raise AssertionError(signature) + + +class SafeOperationTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.keys = ["0x" + "0" * 59 + "a11ce", "0x" + "0" * 61 + "b0b"] + cls.owners = [operation.cast("wallet", "address", "--private-key", key).lower() for key in cls.keys] + + def test_rejects_malformed_addresses_and_hex(self): + for value in (operation.ZERO, "0x1234", "$(command)", None): + with self.assertRaises(ValueError): + operation.address(value) + for value in ("0x1", "0xzz", "12", "0x"): + with self.assertRaises(ValueError): + operation.hex_bytes(value, 48) + for value in (True, -1, "0x1", 2 ** 256): + with self.assertRaises(ValueError): + operation.uint256(value) + + def test_cast_failure_redacts_rpc(self): + failure = subprocess.CompletedProcess([], 1, "", "failed: https://rpc.example/credential") + with patch.object(operation.subprocess, "run", return_value=failure): + with self.assertRaisesRegex(ValueError, "cast call failed") as error: + operation.cast("call", "--rpc-url", "https://rpc.example/credential") + self.assertNotIn("credential", str(error.exception)) + + def test_decodes_current_and_legacy_cast_json(self): + chain = operation.Chain.__new__(operation.Chain) + chain.rpc = "local-test" + for response in ('["42"]', '{"schema_version":1,"success":true,"data":["42"]}'): + with patch.object(operation, "cast", return_value=response): + self.assertEqual(chain.call(SAFE, "getThreshold()(uint256)"), "42") + for response in ('[true]', '{"schema_version":1,"success":true,"data":[true]}'): + with patch.object(operation, "cast", return_value=response): + self.assertEqual(chain.call(VERIFIER, "verify(bytes,bytes32,bytes)(bool)"), "true") + + def test_network_default_follows_devnet_wrapper(self): + with patch.dict(operation.os.environ, {"DEVNET_NETWORK": "betanet"}), \ + patch.object(operation.sys, "argv", ["safe-operation", "--out", "pcr.json", "approve-pcrs"]), \ + patch.object(operation, "prepare") as prepare: + self.assertEqual(operation.main(), 0) + self.assertEqual(prepare.call_args[0][0].network, "betanet") + + def test_chain_rejects_wrong_threshold_and_modules(self): + args = argparse.Namespace(rpc_url="local-test", chain_id=11155111, safe=SAFE) + def fake_cast(*args): + if args[0] == "chain-id": + return "11155111" + if args[0] == "code": + return "0x1234" + if args[2] == "getOwners()(address[])": + return json.dumps([self.owners]) + if args[2] == "getThreshold()(uint256)": + return '["1"]' + raise AssertionError(args) + with patch.object(operation, "cast", side_effect=fake_cast): + with self.assertRaisesRegex(ValueError, "2-of-2"): + operation.Chain(args) + def module_cast(*args): + if args[0] == "call" and args[2] == "getThreshold()(uint256)": + return '["2"]' + if args[0] == "call" and args[2].startswith("getModulesPaginated"): + return json.dumps([[VERIFIER], operation.ZERO]) + return fake_cast(*args) + with patch.object(operation, "cast", side_effect=module_cast): + with self.assertRaisesRegex(ValueError, "modules"): + operation.Chain(args) + with patch.object(operation, "cast", return_value="1"): + with self.assertRaisesRegex(ValueError, "chain ID"): + operation.Chain(args) + + def test_builder_exports_call_fields(self): + data = operation.cast("calldata", "setImplementation(uint32,address,bytes)", 1006, VERIFIER, "0x") + output = operation.builder(FakeChain(self.owners), GAME, data, "Register game") + self.assertEqual(output["chainId"], "11155111") + self.assertEqual(output["meta"]["createdFromSafeAddress"], SAFE) + self.assertEqual(output["transactions"][0]["value"], "0") + self.assertEqual(output["transactions"][0]["data"], data) + + def proposal(self, chain): + with patch.object(operation, "libraries", return_value=("1.4.1", {"signMessage": SIGN_MESSAGE, "multiSend": MULTISEND})): + return operation.council_transaction(chain, GAME) + + def test_council_batch_approves_exact_message_and_submits_empty_proof(self): + chain = FakeChain(self.owners) + proposal = self.proposal(chain) + transaction = proposal["safeTransaction"] + self.assertEqual(transaction["operation"], 1) + self.assertEqual(transaction["nonce"], 7) + self.assertEqual(transaction["to"], MULTISEND) + packed = operation.cast("abi-decode", "multiSend(bytes)", transaction["data"][10:], "--input")[2:] + actions = [] + while packed: + length = int(packed[106:170], 16) + actions.append((int(packed[:2], 16), "0x" + packed[2:42], int(packed[42:106], 16), "0x" + packed[170:170 + length * 2])) + packed = packed[170 + length * 2:] + self.assertEqual(len(actions), 2) + self.assertEqual(actions[0][:3], (1, SIGN_MESSAGE, 0)) + self.assertEqual(operation.cast("abi-decode", "signMessage(bytes)", actions[0][3][10:], "--input"), DIGEST) + self.assertEqual(actions[1][:3], (0, GAME, 0)) + self.assertEqual(operation.cast("abi-decode", "submitProofLane(bytes)", actions[1][3][10:], "--input"), "0x02" + SAFE[2:]) + self.assertEqual(chain.simulated, (MULTISEND, transaction["data"])) + + def test_library_targets_require_supported_version_and_matching_code(self): + chain = FakeChain(self.owners) + with patch.object(chain, "call", return_value="1.2.0"): + with self.assertRaisesRegex(ValueError, "Safe 1.3.0"): + operation.libraries(chain) + with patch.object(chain, "call", return_value="1.4.1"), patch.object(operation, "cast", return_value="0x1234"): + with self.assertRaisesRegex(ValueError, "unexpected bytecode"): + operation.libraries(chain) + for version, entries in operation.LIBRARIES.items(): + def matching_code(*args): + if args[0] == "code": + return args[1].lower() + if args[0] == "keccak": + return next(hash_ for target, hash_ in entries.values() if target.lower() == args[1]) + raise AssertionError(args) + with patch.object(chain, "call", return_value=version), patch.object(operation, "cast", side_effect=matching_code): + self.assertEqual(operation.libraries(chain)[0], version) + + def test_council_rejects_closed_or_already_proven_game(self): + for field, value, error in (("status", "1", "no longer"), ("game_over", "true", "no longer"), ("bitmap", "4", "already")): + chain = FakeChain(self.owners) + setattr(chain, field, value) + with self.assertRaisesRegex(ValueError, error): + operation.council_data(chain, GAME) + + def test_propose_requires_one_owner_transaction_signature(self): + chain = FakeChain(self.owners) + proposal = self.proposal(chain) + with tempfile.TemporaryDirectory() as directory: + folder = Path(directory) + file = folder / "council.json" + file.write_text(json.dumps(proposal)) + args = argparse.Namespace(transaction=str(file), sender=self.owners[0], account="test", wallet=None, + service_url="https://api.safe.global/tx-service/sep/api") + service = Mock() + service.request.return_value = {"results": [], "next": None} + original_run = operation.subprocess.run + def sign_only_one_owner(command, **kwargs): + if command[:3] != ["cast", "wallet", "sign"]: + return original_run(command, **kwargs) + typed = json.loads(Path(command[command.index("--from-file") + 1]).read_text()) + self.assertEqual(typed["primaryType"], "SafeTx") + self.assertEqual(typed["message"], proposal["safeTransaction"]) + # Only this proposer's key is used; no council-message signatures are collected. + return original_run(["cast", "wallet", "sign", "--data", json.dumps(typed), "--private-key", self.keys[0]], **kwargs) + with patch.object(operation, "council_transaction", return_value=proposal), \ + patch.object(operation, "Chain", return_value=chain), \ + patch.object(operation, "Service", return_value=service), \ + patch.object(operation.subprocess, "run", side_effect=sign_only_one_owner): + operation.propose(args, chain) + self.assertEqual([call.args[0] for call in service.request.call_args_list], ["GET", "POST"]) + body = service.request.call_args_list[1].args[2] + self.assertEqual(body["contractTransactionHash"], proposal["safeTxHash"]) + self.assertEqual(body["operation"], 1) + self.assertEqual(body["sender"].lower(), self.owners[0]) + + def test_propose_rejects_tampering_wrong_owner_and_invalid_signature(self): + chain = FakeChain(self.owners) + proposal = self.proposal(chain) + with tempfile.TemporaryDirectory() as directory: + file = Path(directory) / "council.json" + args = argparse.Namespace(transaction=str(file), sender=self.owners[0], service_url="https://service.invalid/api") + with patch.object(operation, "council_transaction", return_value=proposal), patch.object(operation, "sign_transaction") as sign: + for field, value in (("safe", VERIFIER), ("chainId", 1), ("rootId", DIGEST)): + changed = deepcopy(proposal) + changed[field] = value + file.write_text(json.dumps(changed)) + with self.assertRaisesRegex(ValueError, "differs"): + operation.propose(args, chain) + file.write_text(json.dumps(proposal)) + args.sender = VERIFIER + with self.assertRaisesRegex(ValueError, "current Safe owner"): + operation.propose(args, chain) + sign.assert_not_called() + args.sender = self.owners[0] + sign.return_value = operation.cast("wallet", "sign", "--no-hash", proposal["safeTxHash"], "--private-key", self.keys[1]) + service = Mock() + service.request.return_value = {"results": [], "next": None} + with patch.object(operation, "Service", return_value=service): + with self.assertRaisesRegex(ValueError, "does not match"): + operation.propose(args, chain) + self.assertEqual(service.request.call_count, 1) + + def test_propose_checks_pending_nonce_and_does_not_duplicate_proposals(self): + chain = FakeChain(self.owners) + proposal = self.proposal(chain) + with tempfile.TemporaryDirectory() as directory: + file = Path(directory) / "council.json" + file.write_text(json.dumps(proposal)) + args = argparse.Namespace(transaction=str(file), sender=self.owners[0], service_url="https://service.invalid/api") + service = Mock() + service.request.return_value = {"results": [{"nonce": 7, "safeTxHash": DIGEST}], "next": None} + with patch.object(operation, "council_transaction", return_value=proposal), \ + patch.object(operation, "Service", return_value=service), patch.object(operation, "sign_transaction") as sign: + with self.assertRaisesRegex(ValueError, "pending transaction uses this nonce"): + operation.propose(args, chain) + service.request.return_value["results"][0]["safeTxHash"] = proposal["safeTxHash"] + operation.propose(args, chain) + sign.assert_not_called() + self.assertEqual(service.request.call_count, 2) + + def test_council_nonce_rejects_already_executed_transaction(self): + chain = FakeChain(self.owners) + with patch.object(operation, "libraries", return_value=("1.4.1", {})): + with self.assertRaisesRegex(ValueError, "already executed"): + operation.council_transaction(chain, GAME, nonce=6) + + def test_propose_rechecks_nonce_after_wallet_signing(self): + chain = FakeChain(self.owners) + proposal = self.proposal(chain) + signature = operation.cast("wallet", "sign", "--no-hash", proposal["safeTxHash"], "--private-key", self.keys[0]) + with tempfile.TemporaryDirectory() as directory: + file = Path(directory) / "council.json" + file.write_text(json.dumps(proposal)) + args = argparse.Namespace(transaction=str(file), sender=self.owners[0], service_url="https://service.invalid/api") + def signing(*args): + chain.nonce = 8 + return signature + service = Mock() + service.request.return_value = {"results": [], "next": None} + with patch.object(operation, "libraries", return_value=("1.4.1", {"signMessage": SIGN_MESSAGE, "multiSend": MULTISEND})), \ + patch.object(operation, "Chain", return_value=chain), patch.object(operation, "Service", return_value=service), \ + patch.object(operation, "sign_transaction", side_effect=signing): + with self.assertRaisesRegex(ValueError, "already executed"): + operation.propose(args, chain) + self.assertEqual(service.request.call_count, 1) + + def test_wallet_timeout_stops_proposal(self): + args = argparse.Namespace(account="test", sender=self.owners[0]) + with patch.object(operation.subprocess, "run", side_effect=subprocess.TimeoutExpired("cast", 300)): + with self.assertRaisesRegex(ValueError, "nothing was proposed"): + operation.sign_transaction(args, FakeChain(self.owners), {}) + + def test_service_redacts_credentials_bounds_timeout_and_disallows_redirects(self): + for url in ("http://service.invalid", "https://user:secret@service.invalid", "https://service.invalid?key=secret"): + with self.assertRaises(ValueError): + operation.Service(url) + service = operation.Service("https://service.invalid/api") + for failure, error in ((HTTPError("https://secret.invalid", 401, "secret", {}, None), "API_KEY"), + (HTTPError("https://secret.invalid", 429, "secret", {}, None), "quota"), + (URLError("credential"), "queue before retrying")): + with patch.object(service.opener, "open", side_effect=failure) as request: + with self.assertRaisesRegex(ValueError, error) as raised: + service.request("POST", "/v2/test/", {}) + self.assertNotIn("secret", str(raised.exception)) + self.assertNotIn("credential", str(raised.exception)) + self.assertEqual(request.call_args.kwargs["timeout"], 20) + self.assertIsNone(operation.NoRedirects().redirect_request(None, None, 302, "", {}, "https://elsewhere.invalid")) + + def test_service_rejects_malformed_json_and_api_credentials(self): + service = operation.Service("https://service.invalid/api") + with patch.object(service.opener, "open") as request: + request.return_value.__enter__.return_value.read.return_value = b"not JSON" + with self.assertRaisesRegex(ValueError, "malformed JSON"): + service.request("GET", "/v2/test/") + request.reset_mock() + with patch.dict(operation.os.environ, {"SAFE_TRANSACTION_SERVICE_API_KEY": "secret\r\nheader"}): + with self.assertRaisesRegex(ValueError, "bearer token") as raised: + service.request("POST", "/v2/test/", {}) + self.assertNotIn("secret", str(raised.exception)) + request.assert_not_called() + + def test_council_rejects_wrong_network_and_unregistered_game(self): + chain = FakeChain(self.owners) + chain.factory = VERIFIER + with self.assertRaisesRegex(ValueError, "different factory/network"): + operation.council_data(chain, GAME) + chain.factory = FACTORY + chain.registered_game = SAFE + with self.assertRaisesRegex(ValueError, "not registered"): + operation.council_data(chain, GAME) + + +if __name__ == "__main__": + unittest.main() diff --git a/wips/wip-1006.md b/wips/wip-1006.md index b5f016cce..ad673f1c8 100644 --- a/wips/wip-1006.md +++ b/wips/wip-1006.md @@ -11,7 +11,7 @@ created: 2026-05-27 ## Abstract -We outline an OP Stack dispute game in which a proposer posts an output root without embedding proof material in the factory identity. At least one configured proof lane must support the root during the initial one-day challenge window. If nobody challenges and a proof was submitted, the game may resolve in favor of the proposer; without a proof it resolves against the proposer. A challenge may be submitted whether or not the initial proof already exists and raises the requirement to two independent proof lanes by seven days from game creation. The stock `DisputeGameFactory`, `AnchorStateRegistry`, `OptimismPortal2`, and `DelayedWETH` remain responsible for game creation, claim validity, withdrawals, and bond custody. +We outline an OP Stack dispute game in which a proposer posts an output root without embedding proof material in the factory identity. At least one configured proof lane must support the root during the initial one-day challenge window. If nobody challenges and a proof was submitted, the game may resolve in favor of the proposer; without a proof it resolves against the proposer. A challenge may be submitted whether or not the initial proof already exists and raises the requirement to two independent proof lanes by seven days from game creation. The stock `DisputeGameFactory`, `AnchorStateRegistry`, and `OptimismPortal2` remain responsible for game creation, claim validity, and withdrawals; a WIP-1006 `ERC20StakingVault` holds proposal and challenge bonds in a deployment-selected ERC-20 token. World Chain configures WLD as that bond token. ## Motivation @@ -52,8 +52,8 @@ requires activating a new game implementation; existing games retain their origi | `BLOCK_INTERVAL` | TBD | Exact distance each proposal MUST advance from its parent. | | `CHALLENGE_PERIOD` | `1 day` | Duration after proposal creation during which any participant MAY challenge a root and any party MAY submit the initial proof. Per-proposal `challengeDeadline = createdAt + CHALLENGE_PERIOD`. | | `PROOF_PERIOD` | `7 days` | Duration after proposal creation during which the proposer MAY defend a challenged root by accumulating lane submissions toward `PROOF_THRESHOLD`. Per-proposal `proofDeadline = createdAt + PROOF_PERIOD`. `PROOF_PERIOD` MUST be greater than `CHALLENGE_PERIOD`. A challenged root that the proposer has not defended to `PROOF_THRESHOLD` by `proofDeadline` MUST be invalidated. | -| `PROPOSER_BOND` | TBD | ETH bond supplied to `DisputeGameFactory.create` and held by `DelayedWETH`. Paid to the proposer after `DEFENDER_WINS`, split between the challenger and protocol after a challenged proof timeout, paid to the protocol after an unchallenged proof timeout, or refunded if the registry invalidates the game. | -| `CHALLENGER_BOND` | TBD | ETH bond supplied by the challenger and held by `DelayedWETH`. Split between the proposer and accepted proof-lane recipients after a successful defense, returned to the challenger after proof timeout, or refunded if the registry invalidates the game. | +| `PROPOSER_BOND` | TBD | Bond tokens locked from the creator's available vault balance during factory creation. Paid to the proposer after `DEFENDER_WINS`, split between the challenger and protocol after a challenged proof timeout, paid to the protocol after an unchallenged proof timeout, or refunded if the registry invalidates the game. | +| `CHALLENGER_BOND` | TBD | Bond tokens locked from the challenger's available vault balance at challenge time. Split between the proposer and accepted proof-lane recipients after a successful defense, returned to the challenger after proof timeout, or refunded if the registry invalidates the game. | | `PROTOCOL_FEE_RECIPIENT` | TBD | Nonzero protocol-controlled recipient credited with the proposer bond after an unchallenged proof timeout and with the portion not paid to the challenger after a challenged proof timeout. | ### Proof Lanes @@ -84,7 +84,7 @@ The factory UUID identifies a game, while each proof lane authenticates a statem | `l1OriginHash` | Factory | Previous L1 block hash captured at proposal creation. The proposer does not pass it as calldata. | | `l1OriginNumber` | Game | L1 block number paired with the factory-captured `l1OriginHash`. | -The proposer calls `DisputeGameFactory.create(gameType, rootClaim, extraData)`, where: +The proposer deposits the configured bond token into `ERC20StakingVault` and calls `DisputeGameFactory.create(gameType, rootClaim, extraData)`, where: ```text extraData = abi.encode(domainHash, l2BlockNumber, parentRef, attempt) @@ -185,11 +185,15 @@ stateDiagram-v2 A root enters the system in the `PROPOSED` state. -1. The proposer calls the stock `DisputeGameFactory.create` with the WIP-1006 game type, `rootClaim`, and canonical `extraData`, supplying the configured initialization bond. -2. The factory creates a clone of the registered WIP-1006 implementation, captures the creator and L1 head, and calls `initialize`. -3. The game validates the domain, parent registration and eligibility, exact L2 block interval, retry predecessor, and bond. +1. The proposer deposits bond tokens into its available vault balance, then calls the stock `DisputeGameFactory.create` with zero ETH. The factory creates a clone, captures its caller as `gameCreator` and the L1 head, and calls `initialize`. +2. The game validates the domain, parent registration and eligibility, exact L2 block interval, and retry predecessor, then asks the vault to lock `PROPOSER_BOND`. +3. The factory registers a game only after `initialize` returns, so the vault authenticates the caller as the deterministic clone the factory deploys for the current implementation and the caller's creation data, then debits `PROPOSER_BOND` from `gameCreator`'s available balance. Any failure reverts the entire creation. 4. The game records `createdAt = block.timestamp`, `challengeDeadline = createdAt + CHALLENGE_PERIOD`, and `proofDeadline = createdAt + PROOF_PERIOD`. -5. The proposer bond is deposited into `DelayedWETH`, and the root remains open to challenge until `challengeDeadline`. +5. The root remains open to challenge until `challengeDeadline`. + +The account calling `create` is both `gameCreator` and the bonded proposer. Once a game is registered, it remains authorized to settle through the same singleton vault even if the factory later registers a newer implementation. Game-implementation rotations MUST reuse that vault so settled balances remain available across versions. + +The DisputeGameFactory owner and vault ProxyAdmin owner MUST remain the same governance authority. This is required because the factory owner selects the implementations on whose word the vault allocates participant balances, while the ProxyAdmin owner controls the vault implementation and break-glass custody. New bond locks MUST fail closed if those owners diverge, and deployment and activation tooling MUST validate the invariant. Proof material MUST NOT be part of factory creation or `extraData`. After the game exists, any party MAY submit a valid configured proof lane before `challengeDeadline`. Offchain services MAY choose a preferred operational lane, but the onchain protocol MUST NOT privilege one lane for the initial proof. @@ -202,7 +206,7 @@ Any participant MAY challenge a proposed root before `challengeDeadline`, regard The challenge transaction: - MUST NOT require the caller to submit proof material. -- MUST require the caller to supply `CHALLENGER_BOND` as ETH and deposit it into the game's `DelayedWETH`; +- MUST atomically lock `CHALLENGER_BOND` from the caller's available vault balance; - MUST mark the root as `CHALLENGED`. - MUST NOT change the `proofDeadline` derived from proposal creation. @@ -286,12 +290,14 @@ Blacklist, retirement, pause, and respected-game-type controls MUST remain gated ### Bond Settlement -Resolution assigns normal-mode credits. After the stock dispute-game finality delay, anyone MAY call `closeGame()` to fix the bond distribution mode: +Resolution assigns normal-mode credits without releasing bond tokens. After the stock dispute-game finality delay, anyone MAY call `closeGame()` to fix the bond distribution mode: - `NORMAL` when `AnchorStateRegistry.isGameProper(game)` is true; - `REFUND` when the game has been blacklisted, retired, or otherwise made improper. -Closing SHOULD attempt to advance the anchor but MUST treat an ineligible or stale anchor update as non-fatal. Credit claims MUST use the two-phase `DelayedWETH` flow: first unlock the recipient's credit, then withdraw it after the configured delay. Claiming MAY be permissionless, but funds MUST only be transferred to the credited recipient. +Closing SHOULD attempt to advance the anchor but MUST treat an ineligible or stale anchor update as non-fatal. It MUST atomically settle the full game pot into the selected recipients' available vault balances, making those balances immediately reusable for new bonds, reject duplicate settlement, and preserve exact payout conservation. External withdrawal is account-controlled and two-phase: the account requests an amount, waits the configured delay, and withdraws bond tokens. A new request resets the delay for the full pending amount. + +The vault MUST maintain one-to-one bond-token-denominated liabilities and MUST NOT issue transferable shares or apply an exchange rate. Direct token donations MAY make assets exceed liabilities. Insolvency MUST NOT prevent internal game settlement, but an external transfer may fail until the vault is recapitalized. System pause blocks external withdrawal but does not block deposits, withdrawal requests, or challenges to existing games; game creation and closing retain their existing ASR pause checks. For challenged `DEFENDER_WINS`, `CHALLENGER_BOND` MUST be split equally between the proposer and every accepted proof-lane recipient, with any integer-division remainder credited to the proposer. For challenged `PROOF_TIMEOUT`, the challenger receives its bond plus `CHALLENGER_REWARD_BPS` of `PROPOSER_BOND`; `PROTOCOL_FEE_RECIPIENT` receives the rest of `PROPOSER_BOND`. `REFUND` mode returns the full deposited bonds to their depositors instead of applying normal-mode rewards. @@ -308,7 +314,7 @@ WIP-1006 is implemented as a new game type on the stock OP Stack dispute infrast | `IDisputeGameFactory` | Stock OP factory; registers the WIP-1006 implementation, creates clones, indexes games by UUID and list index, and captures `l1Head`. | [`DisputeGameFactory`][base-factory] | | `IDisputeGame` / `IMultiProofGame` | Per-proposal game; exposes the Portal-facing lifecycle and World Chain proof-lane extensions. | [`AggregateVerifier`][base-aggregate] | | `IAnchorStateRegistry` | Stock OP registry; evaluates registration, respect, blacklist, retirement, finality, claim validity, and the current anchor. | [`AnchorStateRegistry`][base-anchor] | -| `IDelayedWETH` | Holds proposer and challenger bonds and enforces delayed two-phase credit withdrawal. | OP Stack `DelayedWETH`. | +| `IERC20StakingVault` | Accepts participant deposits, locks WIP-1006 proposal and challenge bonds from available balances, settles finalized game payouts, and enforces delayed token withdrawal. | [`IERC20StakingVault`](../pkg/contracts/src/dispute/interfaces/IERC20StakingVault.sol) | | `IWorldChainProofVerifier` | Common interface for verifying lane proofs against a game-supplied verifier identity and game-derived public values. | [`IWorldChainProofVerifier`](../pkg/contracts/src/dispute/interfaces/IWorldChainProofVerifier.sol) | | `NitroEnclaveKeyRegistry` | Maintains TEE signer identities admitted through Nitro attestation. | [`NitroEnclaveKeyRegistry`](../pkg/contracts/src/dispute/nitro/NitroEnclaveKeyRegistry.sol) | | `SecurityCouncilVerifier` | Verifies the council Safe's ERC-1271 attestation over `rootId`. | [`SecurityCouncilVerifier`](../pkg/contracts/src/dispute/council/SecurityCouncilVerifier.sol) | @@ -319,7 +325,7 @@ WIP-1006 is implemented as a new game type on the stock OP Stack dispute infrast ## Backwards Compatibility -This proposal is implemented as a new World Chain game type registered on the existing OP Stack `DisputeGameFactory`. Existing output roots and Cannon-style games do not need to be reinterpreted. Activating the type consists of registering its implementation and initialization bond, then switching the stock `AnchorStateRegistry` respected game type after operational readiness. +This proposal is implemented as a new World Chain game type registered on the existing OP Stack `DisputeGameFactory`. Existing output roots and Cannon-style games do not need to be reinterpreted. Activating the type consists of deploying the vault, registering the game implementation, setting the factory's type-1006 ETH initialization bond to zero, and switching the stock `AnchorStateRegistry` respected game type after operational readiness. The proposal data remains aligned with the OP Stack: @@ -330,13 +336,16 @@ The proposal data remains aligned with the OP Stack: - factory identity uses the canonical `(gameType, rootClaim, extraData)` UUID; - `domainHash`, `l2BlockNumber`, `parentRef`, and `attempt` are encoded in `extraData`. -Offchain services MUST use the stock factory creation and lookup APIs plus the WIP-1006 game extensions. They do not require a custom factory or anchor registry. Proposers and defenders MAY reconstruct a selected lineage by looking up the expected transition from the current anchor; challengers use the factory index to inspect all games. A deployment MAY have its defender submit the TEE lane as the initial operational policy, but challenged games MUST still be escalated with an independent lane. +Proposers and challengers deposit enough bond tokens into their available vault balances before using the stock factory and game APIs. `deposit(account, amount)` transfers the caller's tokens and credits the selected account, and no standing allowance is required after a deposit. Offchain services do not require a custom factory or anchor registry. Proposers and defenders MAY reconstruct a selected lineage by looking up the expected transition from the current anchor; challengers use the factory index to inspect all games. A deployment MAY have its defender submit the TEE lane as the initial operational policy, but challenged games MUST still be escalated with an independent lane. ## Test Cases Before this WIP can move beyond Draft, implementations SHOULD cover at least: - a newly created game has no proof support and a factory UUID independent of later proof bytes; +- the proposer bond is locked from `gameCreator` atomically with factory creation, and creation reverts without sufficient available balance; +- the vault rejects a proposer-bond lock from any caller that is not the deterministic clone the canonical factory deploys; +- an already registered game can settle after the factory implementation is replaced; - an unchallenged root with any one valid configured lane finalizes after exactly `CHALLENGE_PERIOD`; - an unchallenged root with `PROOF_THRESHOLD` distinct lanes finalizes before `CHALLENGE_PERIOD`; - an unchallenged proofless root invalidates after exactly `CHALLENGE_PERIOD`, forfeits its proposer bond to the configured protocol recipient, and can be retried; @@ -357,7 +366,8 @@ Before this WIP can move beyond Draft, implementations SHOULD cover at least: - the validity and TEE lanes reject a proof for a different transition or verifier identity, and the Security Council lane rejects an attestation for a different `rootId`; - parent invalidation cascades and refunds both descendant participants; - retry attempts reject an ineligible predecessor and accept each specified recovery case; -- close and claim use normal mode for proper games and refund mode for blacklisted or retired games; +- close atomically settles normal mode for proper games and refund mode for blacklisted or retired games; +- vault liabilities remain exact across deposits, bond locks, settlement, delayed withdrawals, and participant-address overlap; - Portal withdrawal proof and finalization accept a claim-valid WIP-1006 game and reject blacklisted, retired, unrespected, challenger-winning, or insufficiently mature games. ## Security Considerations @@ -378,6 +388,10 @@ Before this WIP can move beyond Draft, implementations SHOULD cover at least: **Self-challenge can amplify proof work.** A proposer can challenge its own valid game through another account and force defenders to produce another lane. If the game times out, the shared owner loses the protocol share of `PROPOSER_BOND`; if it is defended, accepted proof-lane recipients share `CHALLENGER_BOND`. A proposer that also controls those recipients can still recycle the successful-defense payout, so the economics limit but do not prevent proof-amplification griefing. +**The vault ProxyAdmin is a custody trust assumption.** The deployed implementation exposes no administrative path for moving participant balances or extracting backing tokens directly. However, the ProxyAdmin owner can upgrade the singleton vault, so its compromise can still affect uncommitted balances and backing for active games. Production deployment MUST protect this role accordingly. + +**Bond-lock authentication is part of factory integrity.** The factory registers a game only after `initialize` returns, so the vault MUST authenticate a proposer bond lock by recomputing the deterministic clone address the canonical factory deploys for the current implementation and the caller's creation data. Because locks allocate deposited balances on the word of factory-selected code, they MUST fail closed unless the factory owner and the vault ProxyAdmin owner are the same authority. Participant exposure is bounded by the bond tokens deliberately deposited into the vault. + **Bond calibration is security-critical.** If `CHALLENGER_BOND` is too cheap, attackers can force valid roots into the slow path or create repeated proof work. If it is too expensive, honest watchers may fail to challenge invalid roots. `PROPOSER_BOND` must make invalid proposals expensive while keeping proposal participation viable. Exact economic parameters are out of scope for this WIP but MUST be tuned before mainnet deployment. ## Copyright diff --git a/wips/wip-1007.md b/wips/wip-1007.md index e44ec6756..8400122f4 100644 --- a/wips/wip-1007.md +++ b/wips/wip-1007.md @@ -143,11 +143,12 @@ Attaching a Flashblock Access List is OPTIONAL and controlled by builder configu A consumer that receives a flashblock whose diff contains `access_list_data` MAY use the access list to validate the flashblock via the parallel path. A consumer that uses the access list MUST perform all of the following, and MUST reject the flashblock if any step fails: -1. **Reconstruct pre-state.** Build a temporal pre-state from `access_list` over the parent block's state, applying the [Block Access Index Semantics](#block-access-index-semantics). For any account, slot, or code not present in the access list, reads MUST fall through to the parent state. -2. **Derive the post-state.** Extend the bundle state committed by prior flashblocks with the changes in `access_list` to obtain the post-flashblock bundle, and compute its state root. -3. **Re-execute in parallel.** Execute the flashblock's transactions, each at its own `block_access_index` over an isolated snapshot of the reconstructed pre-state, and aggregate the per-transaction receipts, gas, fees, and re-derived account changes. -4. **Verify the access list.** Reduce the re-derived changes to canonical form, compute their hash, and require it to equal the published `access_list_hash`. A mismatch MUST be rejected. -5. **Verify the roots and hash.** The re-computed `receipts_root` MUST equal `diff.receipts_root`, the derived `state_root` MUST equal `diff.state_root`, and the assembled block hash MUST equal `diff.block_hash`. +1. **Verify the received access list hash.** Before using `access_list` to reconstruct state, compute `keccak256(rlp(access_list))` and require it to equal the published `access_list_hash`. A mismatch MUST be rejected. +2. **Reconstruct pre-state.** Build a temporal pre-state from `access_list` over the parent block's state, applying the [Block Access Index Semantics](#block-access-index-semantics). For any account, slot, or code not present in the access list, reads MUST fall through to the parent state. +3. **Derive the post-state.** Extend the bundle state committed by prior flashblocks with the changes in `access_list` to obtain the post-flashblock bundle, and compute its state root. +4. **Re-execute in parallel.** Execute the flashblock's transactions, each at its own `block_access_index` over an isolated snapshot of the reconstructed pre-state, and aggregate the per-transaction receipts, gas, fees, and re-derived account changes. Before committing each result in transaction order, enforce the sequential block admission rules using cumulative pre-refund EVM gas and, when Jovian is active, cumulative DA footprint, including usage from prior flashblocks and the applicable deposit exemptions. +5. **Verify the re-derived access list.** Reduce the re-derived changes to canonical form, compute their hash, and require it to equal the same published `access_list_hash`. A mismatch MUST be rejected. +6. **Verify the roots and hash.** The re-computed `receipts_root` MUST equal `diff.receipts_root`, the derived `state_root` MUST equal `diff.state_root`, and the assembled block hash MUST equal `diff.block_hash`. A consumer MUST NOT surface a flashblock's state as `pending` unless validation succeeds. If `access_list_data` is absent, the consumer MUST fall back to sequential re-execution of the diff transactions against the committed state (the legacy path), which produces the same `pending` block without the access-list optimizations. diff --git a/xtask/src/devnet.rs b/xtask/src/devnet.rs index d1abdeda8..06778b280 100644 --- a/xtask/src/devnet.rs +++ b/xtask/src/devnet.rs @@ -597,7 +597,7 @@ fn signal_process(pid: u32, signal: &str) -> Result<()> { if status.success() { Ok(()) } else { - bail!("failed to send SIG{signal} to pid {pid}") + bail!("failed to send SIG{signal} to pid {pid}"); } } diff --git a/xtask/src/preflight.rs b/xtask/src/preflight.rs index 0ccaed681..2bfd18c97 100644 --- a/xtask/src/preflight.rs +++ b/xtask/src/preflight.rs @@ -121,7 +121,7 @@ pub fn run(_args: Args) -> Result<()> { std::thread::scope(|s| { s.spawn(|| { - run_cmd("cargo", &["+nightly-2026-07-01", "fmt", "--all"]); + run_cmd("cargo", &["+nightly-2026-10-10", "fmt", "--all"]); }); if contracts_changed { @@ -144,7 +144,7 @@ pub fn run(_args: Args) -> Result<()> { s.spawn(|| { let (ok, stderr) = run_cmd_capture( "cargo", - &["+nightly-2026-07-01", "fmt", "--all", "--", "--check"], + &["+nightly-2026-10-10", "fmt", "--all", "--", "--check"], ); if ok { report("Rust formatting", Status::Pass, &errors); @@ -152,7 +152,7 @@ pub fn run(_args: Args) -> Result<()> { let diag = condensed_diagnostics(&stderr); report( "Rust formatting", - Status::FailWith("cargo +nightly-2026-07-01 fmt --all".into(), diag), + Status::FailWith("cargo +nightly-2026-10-10 fmt --all".into(), diag), &errors, ); } @@ -163,7 +163,7 @@ pub fn run(_args: Args) -> Result<()> { let (ok, stderr) = run_cmd_capture_env( "cargo", &[ - "+nightly-2026-07-01", + "+nightly-2026-10-10", "clippy", "--workspace", "--all-targets", @@ -180,7 +180,7 @@ pub fn run(_args: Args) -> Result<()> { report( "Clippy", Status::FailWith( - "cargo +nightly-2026-07-01 clippy --workspace --all-targets --all-features" + "cargo +nightly-2026-10-10 clippy --workspace --all-targets --all-features" .into(), diag, ),