diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index c835a6829..3da789f6c 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -33,6 +33,7 @@ jobs: runs-on: ubuntu-latest outputs: reduced: ${{ github.event_name == 'workflow_dispatch' || github.event.pull_request.draft == true || (github.event_name == 'push' && github.ref_type == 'branch' && github.repository != 'simplex-chat/simplexmq') }} + resolver: ${{ steps.changes.outputs.resolver }} steps: - name: Reject a manual run on a tag if: github.event_name == 'workflow_dispatch' && github.ref_type == 'tag' @@ -40,6 +41,33 @@ jobs: echo "::error::A manual run starts on a branch; to retry a release, re-run the jobs of its tag push." exit 1 + - name: Clone project to check changes + if: github.event_name != 'push' + uses: actions/checkout@v3 + with: + fetch-depth: 2 + + - name: Check changes + id: changes + shell: bash + env: + GH_TOKEN: ${{ github.token }} + run: | + case "$GITHUB_EVENT_NAME" in + pull_request) + base=HEAD^1 + ;; + workflow_dispatch) + base=$(gh api "repos/$GITHUB_REPOSITORY/compare/master...$GITHUB_REF_NAME" --jq .merge_base_commit.sha) + git fetch -q --depth=1 origin "$base" + ;; + *) + echo "resolver=true" >> "$GITHUB_OUTPUT" + exit 0 + ;; + esac + git diff --quiet "$base" HEAD -- scripts/resolver/service .github/workflows/build.yml || echo "resolver=true" >> "$GITHUB_OUTPUT" + - name: Clone project if: startsWith(github.ref, 'refs/tags/v') uses: actions/checkout@v3 @@ -95,6 +123,7 @@ jobs: cache_o0: ${{ github.event_name == 'push' && (github.ref == 'refs/heads/master' || github.ref == 'refs/heads/stable') }} image_cache: ghcr.io/${{ github.repository_owner }}/simplexmq-build-cache:${{ matrix.os }}-${{ matrix.arch }}-ghc${{ matrix.ghc }} source_hashes: dist-newstyle/sources.sha256 + resolver: ${{ needs.maybe-release.outputs.resolver == 'true' && matrix.os == '24.04' && matrix.arch == 'x86-64' && matrix.client_postgres != true }} runs-on: ${{ matrix.runner }} services: &build-services postgres: @@ -158,6 +187,52 @@ jobs: with: submodules: recursive + - name: Set up uv + if: env.resolver == 'true' + # uv takes Python from .python-version, the version of the Dockerfile's runtime stage. + uses: astral-sh/setup-uv@c18668ad3cf93ea998bef934396af7bb5c839dc7 # v10.2.0 + + - name: Lint resolver + if: env.resolver == 'true' + working-directory: scripts/resolver/service + run: uv run --frozen ruff check . + + - name: Set up Node + if: env.resolver == 'true' + uses: actions/setup-node@v7 + with: + node-version: 22 + + - name: Build names dev chain + if: env.resolver == 'true' + env: + SNRC_DEV_CHAIN: ${{ runner.temp }}/dev-chain + SIMPLEX_DOMAINS_REPO: https://github.com/simplex-chat/simplex.domains + SIMPLEX_DOMAINS_COMMIT: 65f02f1faa53bc350d8bc63e35b7d411cce4406a + run: | + git clone -q --filter=blob:none "$SIMPLEX_DOMAINS_REPO" "$SNRC_DEV_CHAIN/simplex.domains" + cd "$SNRC_DEV_CHAIN/simplex.domains" + git checkout -q "$SIMPLEX_DOMAINS_COMMIT" + for stage in contracts anvil; do + docker build -q --target "$stage" -t "names-$stage" -f webapp/dev/Dockerfile . + done + mkdir "$SNRC_DEV_CHAIN/ens-contracts" + contracts=$(docker create names-contracts) + docker cp "$contracts:/src/ens-contracts/artifacts" "$SNRC_DEV_CHAIN/ens-contracts/artifacts" + docker rm "$contracts" + anvil=$(docker create names-anvil) + docker cp "$anvil:/usr/local/bin/anvil" "$SNRC_DEV_CHAIN/anvil" + docker rm "$anvil" + cd webapp + npm ci --no-audit --no-fund + + - name: Test resolver + if: env.resolver == 'true' + working-directory: scripts/resolver/service + env: + SNRC_DEV_CHAIN: ${{ runner.temp }}/dev-chain + run: uv run --frozen pytest -v + - name: Set up Docker Buildx if: matrix.should_run == true uses: simplex-chat/docker-setup-buildx-action@v3 @@ -552,29 +627,3 @@ jobs: should_run: true client_postgres: true steps: *build-steps - -# ============================= -# Resolver test job -# ============================= - -# The SNRC resolver is Python, so this job needs none of the Haskell toolchain -# above and runs independently of it. - - resolver-test: - name: "resolver (python)" - runs-on: ubuntu-latest - steps: - - name: Clone project - uses: actions/checkout@v3 - - - name: Set up uv - # uv takes Python from .python-version, the version of the Dockerfile's runtime stage. - uses: astral-sh/setup-uv@c18668ad3cf93ea998bef934396af7bb5c839dc7 # v10.2.0 - - - name: Lint - working-directory: scripts/resolver/service - run: uv run --frozen ruff check . - - - name: Test - working-directory: scripts/resolver/service - run: uv run --frozen pytest -v diff --git a/.github/workflows/resolver-mainnet.yml b/.github/workflows/resolver-mainnet.yml new file mode 100644 index 000000000..e4411a733 --- /dev/null +++ b/.github/workflows/resolver-mainnet.yml @@ -0,0 +1,26 @@ +name: resolver mainnet + +on: + schedule: + - cron: "17 6 * * *" + workflow_dispatch: + pull_request: + paths: + - .github/workflows/resolver-mainnet.yml + +jobs: + mainnet: + name: "resolver on mainnet" + runs-on: ubuntu-latest + steps: + - name: Clone project + uses: actions/checkout@v3 + + - name: Set up uv + uses: astral-sh/setup-uv@c18668ad3cf93ea998bef934396af7bb5c839dc7 # v10.2.0 + + - name: Test known names + working-directory: scripts/resolver/service + env: + SNRC_MAINNET_RPC: ${{ secrets.SNRC_MAINNET_RPC || 'https://ethereum-rpc.publicnode.com' }} + run: uv run --frozen pytest -v test_ground_truth.py -k MainnetTests diff --git a/scripts/ci/README.md b/scripts/ci/README.md index 1c9a1a30a..94b29b68e 100644 --- a/scripts/ci/README.md +++ b/scripts/ci/README.md @@ -9,7 +9,17 @@ | a push to a draft pull request
a manual run (workflow_dispatch)
a push to master or stable in a fork | reduced | build-reduced: 2 entries, ubuntu-24.04 x86-64, GHC 9.6.3, at -O0 (-O2 on pushes), without the standard build | | a pull request marked ready for review, and later pushes to it
a push to master or stable in simplex-chat/simplexmq
a push of a v* tag | full | build: 6 entries (GHC 8.10.7 and 9.6.3, x86-64 and aarch64), at -O0 on pull requests and -O2 on pushes | -Both builds also run maybe-release and resolver (python). Tests run on the x86-64 entries, after xftp-web is built with Node.js 22 (`npm install`, `npm run build`) for the XFTP Web Client tests. In both builds, the ubuntu-24.04 x86-64 entry named "PostgreSQL agent store" builds and runs only the tests built with `-fclient_postgres -fslow_servers` (agent with the PostgreSQL store, and XFTP servers that delay responses for the slow-server test, which the other builds skip), in the build directory dist-client-postgres, in step "Test with PostgreSQL agent store", in parallel with the other entries; its build directory has its own cache key. After the tests, step "Check generated files" fails if a test changed a tracked file: the schema dump and query plan tests overwrite their files, so a stale file fails here even when the test passes on retry. The reduced build restores the -O0 build caches saved by master pushes; the Docker image cache is tagged by ISO week, so the first run of a week rebuilds the image. +Both builds also run maybe-release. Tests run on the x86-64 entries, after xftp-web is built with Node.js 22 (`npm install`, `npm run build`) for the XFTP Web Client tests. In both builds, the ubuntu-24.04 x86-64 entry named "PostgreSQL agent store" builds and runs only the tests built with `-fclient_postgres -fslow_servers` (agent with the PostgreSQL store, and XFTP servers that delay responses for the slow-server test, which the other builds skip), in the build directory dist-client-postgres, in step "Test with PostgreSQL agent store", in parallel with the other entries; its build directory has its own cache key. After the tests, step "Check generated files" fails if a test changed a tracked file: the schema dump and query plan tests overwrite their files, so a stale file fails here even when the test passes on retry. The reduced build restores the -O0 build caches saved by master pushes; the Docker image cache is tagged by ISO week, so the first run of a week rebuilds the image. + +The ubuntu-24.04 x86-64 entry without the PostgreSQL agent store also lints and tests the resolver (scripts/resolver/service, steps "Lint resolver" and "Test resolver"): +- on a push; +- on a pull request or a manual run that changes scripts/resolver/service or build.yml. A manual run is compared with its merge base with master. + +In "Build names dev chain", the `contracts` and `anvil` stages of `webapp/dev/Dockerfile` of simplex.domains, at the commit set in the step, are built, the compiled ens-contracts artifacts and anvil are copied out of them, and the webapp's dependencies are installed. In test_ground_truth.py, anvil is started, the `.simplex` contracts are deployed and seeded with the webapp's `dev/deploy.ts`, the other states the tests need are seeded over JSON-RPC, and the resolver's answer for each seeded name is checked. + +`resolver-mainnet.yml` checks the resolver's answers for known mainnet names daily, on a manual run and on a pull request that changes it. The RPC is the secret `SNRC_MAINNET_RPC`, or a public endpoint without it. + +Local run: scripts/resolver/README.md, "Resolver API reference". ## Test selection diff --git a/scripts/resolver/README.md b/scripts/resolver/README.md index 2f0c59d67..fd83bdf43 100644 --- a/scripts/resolver/README.md +++ b/scripts/resolver/README.md @@ -149,6 +149,13 @@ uv run pytest uv run ruff check . ``` +`test_ground_truth.py` runs only with its variables set: `SNRC_DEV_CHAIN`, a directory with `anvil`, `ens-contracts/artifacts` and a simplex.domains checkout in `simplex.domains` with its webapp's dependencies installed, prepared as in the CI step "Build names dev chain", with Node.js 22.18 or later, and `SNRC_MAINNET_RPC`, a mainnet JSON-RPC endpoint: + +```sh +SNRC_DEV_CHAIN=../dev-chain uv run pytest test_ground_truth.py +SNRC_MAINNET_RPC=https://ethereum-rpc.publicnode.com uv run pytest test_ground_truth.py -k MainnetTests +``` + Dependencies are locked in `uv.lock`; the Docker image installs exactly those. Three routes, versioned separately from the protocol so each only changes when diff --git a/scripts/resolver/service/test_ground_truth.py b/scripts/resolver/service/test_ground_truth.py new file mode 100644 index 000000000..aeb8f05a6 --- /dev/null +++ b/scripts/resolver/service/test_ground_truth.py @@ -0,0 +1,279 @@ +import json +import os +import socket +import subprocess +import sys +import tempfile +import time +import unittest +from urllib.error import HTTPError +from urllib.request import Request, urlopen + +from eth_hash.auto import keccak + +HERE = os.path.dirname(os.path.abspath(__file__)) +DEV_CHAIN = os.environ.get("SNRC_DEV_CHAIN", "") +MAINNET_RPC = os.environ.get("SNRC_MAINNET_RPC", "") +DAY = 86400 +BAKERY_CONTACT = "https://smp8.simplex.im/a#Y8m3qT0vLw2Ab7cD9eF1gH3jK5mN7pQ9rSAAAAAAAAA" +BAKERY_CHANNEL = "https://smp9.simplex.im/c#Rk27xN4pDe9Tz1Wb3Yc5Vd7Xf9Hg2Jk4LmAAAAAAAAA" +CONTACT = "https://localhost/a#ground-truth" +MENU_CONTACT = "https://localhost/a#menu" +TRADEMARK = 2 +COMMUNITY = 3 + + +def get(url): + try: + with urlopen(url, timeout=30) as r: + return r.status, json.load(r) + except HTTPError as e: + return e.code, json.load(e) + + +def wait_for(url, process): + for _ in range(600): + if process.poll() is not None: + raise RuntimeError(f"{process.args[0]} exited with {process.returncode}") + try: + urlopen(url, timeout=1).close() + return + except HTTPError: + return + except OSError: + time.sleep(0.5) + raise TimeoutError(url) + + +def free_port(): + with socket.socket() as s: + s.bind(("127.0.0.1", 0)) + return s.getsockname()[1] + + +def start_resolver(test_class, env): + port = free_port() + process = subprocess.Popen( + [sys.executable, os.path.join(HERE, "snrc-resolve.py")], + env={**os.environ, **env, "SNRC_BIND": "127.0.0.1", "SNRC_PORT": str(port), "SNRC_WORKERS": "1"}, + ) + test_class.addClassCleanup(process.terminate) + url = f"http://127.0.0.1:{port}" + wait_for(url + "/health", process) + return url + + +def rpc(chain, method, *params): + request = Request(chain, json.dumps({"jsonrpc": "2.0", "id": 1, "method": method, "params": params}).encode(), {"Content-Type": "application/json"}) + with urlopen(request, timeout=30) as r: + body = json.load(r) + if "error" in body: + raise RuntimeError(f"{method}: {body['error']}") + return body["result"] + + +def namehash(name): + node = bytes(32) + for label in reversed(name.split(".")): + node = keccak(node + keccak(label.encode())) + return node + + +def call_data(signature, *args): + params = signature[signature.index("(") + 1 : -1] + types = params.split(",") if params else [] + return "0x" + (keccak(signature.encode())[:4] + encode(types, args)).hex() + + +def encode(types, values): + heads, tails = [], [] + offset = 32 * len(types) + for type_, value in zip(types, values, strict=True): + if type_ in ("string", "string[]"): + tail = encode_dynamic(type_, value) + heads.append(offset.to_bytes(32, "big")) + tails.append(tail) + offset += len(tail) + else: + heads.append(encode_static(value)) + return b"".join(heads + tails) + + +def encode_static(value): + if isinstance(value, bytes): + return value + if isinstance(value, str): + value = int(value, 16) + return int(value).to_bytes(32, "big") + + +def encode_dynamic(type_, value): + if type_ == "string[]": + return len(value).to_bytes(32, "big") + encode(["string"] * len(value), value) + data = value.encode() + return len(data).to_bytes(32, "big") + data + bytes(-len(data) % 32) + + +def read(chain, contract, signature, *args): + return rpc(chain, "eth_call", {"to": contract, "data": call_data(signature, *args)}, "latest") + + +def send(chain, tx): + tx_hash = rpc(chain, "eth_sendTransaction", tx) + for _ in range(100): + receipt = rpc(chain, "eth_getTransactionReceipt", tx_hash) + if receipt: + if receipt["status"] != "0x1": + raise RuntimeError(f"{tx_hash} reverted") + return receipt + time.sleep(0.1) + raise TimeoutError(tx_hash) + + +def transact(chain, sender, contract, signature, *args): + return send(chain, {"from": sender, "to": contract, "data": call_data(signature, *args)}) + + +def start_chain(test_class): + port = free_port() + anvil = subprocess.Popen( + [os.path.join(DEV_CHAIN, "anvil"), "--port", str(port), "--block-time", "1", "--mixed-mining"], + stdout=subprocess.DEVNULL, + ) + test_class.addClassCleanup(anvil.terminate) + chain = f"http://127.0.0.1:{port}" + wait_for(chain, anvil) + return chain + + +def deploy(chain): + with tempfile.TemporaryDirectory() as out: + deployment = os.path.join(out, "local-chain.json") + subprocess.run( + ["node", "dev/deploy.ts"], + cwd=os.path.join(DEV_CHAIN, "simplex.domains", "webapp"), + env={ + **os.environ, + "RPC_URL": chain, + "ENS_CONTRACTS_DIR": os.path.join(DEV_CHAIN, "ens-contracts"), + "LOCAL_CHAIN_OUT": deployment, + "MIN_COMMITMENT_AGE": "1", + }, + check=True, + ) + with open(deployment) as f: + return json.load(f) + + +def seed_lookup_states(chain, contracts): + owner, holder = contracts["owner"], contracts["holder"] + registry, registrar, resolver, policy = contracts["ens"], contracts["baseRegistrar"], contracts["resolver"], contracts["namePolicy"] + transact(chain, owner, registrar, "addController(address)", owner) + transact(chain, owner, registrar, "registerWithLabel(string,address,uint256,uint256)", "lapsed", holder, DAY, 0) + transact(chain, owner, registrar, "registerWithLabel(string,address,uint256,uint256)", "expiring", holder, 30 * DAY, 0) + transact(chain, holder, registry, "setResolver(bytes32,address)", namehash("expiring.simplex"), resolver) + transact(chain, holder, resolver, "setText(bytes32,string,string)", namehash("expiring.simplex"), "simplex.contact", CONTACT) + subnames = "0x" + read(chain, registrar, "subnameHook()")[-40:] + transact(chain, holder, registry, "setApprovalForAll(address,bool)", subnames, True) + transact(chain, holder, subnames, "createSubname(bytes32,string)", namehash("bakery.simplex"), "menu") + transact(chain, holder, resolver, "setText(bytes32,string,string)", namehash("menu.bakery.simplex"), "simplex.contact", MENU_CONTACT) + transact(chain, owner, policy, "addReservedNames(string[],uint8)", ["brandname"], TRADEMARK) + transact(chain, owner, policy, "addReservedNames(string[],uint8)", ["privacy"], COMMUNITY) + grace = int(read(chain, registrar, "GRACE_PERIOD()"), 16) + rpc(chain, "evm_increaseTime", hex(grace + 2 * DAY)) + rpc(chain, "evm_mine") + + +def deploy_multicall(chain, sender): + with open(os.path.join(DEV_CHAIN, "ens-contracts", "artifacts", "contracts", "mocks", "Multicall3.sol", "Multicall3.json")) as f: + bytecode = json.load(f)["bytecode"] + return send(chain, {"from": sender, "data": bytecode})["contractAddress"] + + +class GroundTruthTestCase(unittest.TestCase): + def registration(self, name): + status, body = get(f"{self.url}/v2/resolve/{name}") + self.assertEqual(status, 200, body) + return body["lastBlockTs"], body["registration"] + + def assert_registered(self, name, contact=None): + now, reg = self.registration(name) + self.assertEqual(reg["type"], "registered", name) + self.assertGreater(reg["graceUntil"], now) + if contact is not None: + self.assertEqual(reg["nameRecord"]["simplexContact"], contact) + return now, reg + + def assert_type(self, name, type_, **fields): + reg = self.registration(name)[1] + self.assertEqual(reg["type"], type_, name) + for key, value in fields.items(): + self.assertEqual(reg[key], value, name) + + +@unittest.skipUnless(DEV_CHAIN, "SNRC_DEV_CHAIN is not set") +class LocalChainTests(GroundTruthTestCase): + @classmethod + def setUpClass(cls): + chain = start_chain(cls) + contracts = deploy(chain) + seed_lookup_states(chain, contracts) + cls.holder = contracts["holder"].lower() + cls.url = start_resolver(cls, { + "SNRC_RPC": chain, + "SNRC_MULTICALL": deploy_multicall(chain, contracts["owner"]), + "SNRC_REGISTRY_SIMPLEX": contracts["ens"], + "SNRC_REGISTRAR_SIMPLEX": contracts["baseRegistrar"], + "SNRC_CONTROLLER_SIMPLEX": contracts["controller"], + }) + + def test_a_live_name_is_registered_with_its_records(self): + now, reg = self.assert_registered("bakery.simplex", [BAKERY_CONTACT]) + self.assertGreater(reg["expires"], now) + self.assertEqual(reg["nameRecord"]["simplexChannel"], [BAKERY_CHANNEL]) + self.assertEqual(reg["nameRecord"]["owner"], self.holder) + self.assert_registered("harbour.simplex", []) + + def test_a_name_in_grace_is_registered(self): + now, reg = self.assert_registered("expiring.simplex", [CONTACT]) + self.assertLess(reg["expires"], now) + + def test_a_held_subname_is_registered(self): + reg = self.assert_registered("menu.bakery.simplex", [MENU_CONTACT])[1] + self.assertEqual(reg["nameRecord"]["name"], "menu.bakery.simplex") + self.assertEqual(reg["nameRecord"]["owner"], self.holder) + + def test_names_nobody_holds_are_available_at_the_launch_price(self): + pricing = {"registrationPrices": {"6": 20000, "7": 10000}, "basePrice": 5000, "minLabelLength": 6} + for name in ("sunflower.simplex", "lapsed.simplex", "menu.expiring.simplex"): + self.assert_type(name, "available", pricing=pricing) + + def test_reserved_names_carry_their_reason(self): + for name, reason in (("simplex.simplex", "internal"), ("brandname.simplex", "trademark"), ("privacy.simplex", "community")): + self.assert_type(name, "reserved", reservedReason=reason) + + def test_v1_answers_each_state_by_its_status(self): + status, body = get(f"{self.url}/resolve/bakery.simplex") + self.assertEqual((status, body["simplexContact"]), (200, [BAKERY_CONTACT])) + for name, code in (("sunflower.simplex", 404), ("lapsed.simplex", 410), ("menu.expiring.simplex", 404)): + self.assertEqual(get(f"{self.url}/resolve/{name}")[0], code, name) + + +@unittest.skipUnless(MAINNET_RPC, "SNRC_MAINNET_RPC is not set") +class MainnetTests(GroundTruthTestCase): + @classmethod + def setUpClass(cls): + cls.url = start_resolver(cls, {"SNRC_RPC": MAINNET_RPC}) + + def test_known_names_are_registered(self): + self.assert_registered("foobar.testing", ["https://smp16.simplex.im/a#Q_F00BA7"]) + self.assert_registered("bitcoin.testing") + self.assert_registered("evgenypoberezkin.simplex") + + def test_reserved_names_carry_their_reason(self): + for name in ("simplex.testing", "simplex.simplex"): + self.assert_type(name, "reserved", reservedReason="internal") + + def test_a_name_nobody_registered_is_available(self): + for name in ("groundtruthcheck.testing", "groundtruthcheck.simplex"): + self.assert_type(name, "available")