From 0c61611ca1c4cdd359d690458b24c81863c23fbb Mon Sep 17 00:00:00 2001 From: 3alpha <15694175+3alpha@users.noreply.github.com> Date: Mon, 30 Nov 2026 15:25:05 +0100 Subject: [PATCH] feat(spec): accept and check the manifest nodes field Node packages declare the nodes they run in `nodes`. The SDK no longer warns about the field, checks that each declaration is complete and free of addresses, and documents it in the package spec. --- doc/package-spec.md | 84 ++++++++++- src/spec/checkPackageSpec.ts | 17 ++- src/spec/manifestReferences.ts | 21 ++- src/spec/nodes.ts | 218 +++++++++++++++++++++++++++++ src/spec/rules.ts | 10 +- test/files/variantMerge.test.ts | 73 ++++++++++ test/spec/checkPackageSpec.test.ts | 197 ++++++++++++++++++++++++++ 7 files changed, 615 insertions(+), 5 deletions(-) create mode 100644 src/spec/nodes.ts diff --git a/doc/package-spec.md b/doc/package-spec.md index e1f5cd43..f04a75ad 100644 --- a/doc/package-spec.md +++ b/doc/package-spec.md @@ -33,16 +33,20 @@ Repository counts and migration observations belong to dated audit reports; see **SPEC-M06: A variant `upstream[]` keeps the root's positions.** Root and variant manifests are merged by array position. A variant may list fewer or more entries than the root, but an entry at an existing position must refer to the same `repo`. -**SPEC-M07: Only fields from the manifest schema.** Fields outside the published manifest schema (plus `upnpDisable`, supported by DAPPMANAGER but not yet published) are ignored or stripped at install. +**SPEC-M07: Only fields from the manifest schema.** Fields outside the published manifest schema (plus `upnpDisable` and `nodes`, supported by DAPPMANAGER but not yet published) are ignored or stripped at install. **SPEC-M08: `repository.url` points to the package repository.** When a manifest declares `repository`, its URL is the package's own GitHub repository (`https://` or `git+https://`, with or without `.git`). **SPEC-M09: Exposable services exist in the compose.** `exposable[].serviceName` names a service in the compose. -**SPEC-M10: Manifest service references exist in the resolved compose.** Explicit `mainService`, `chain.serviceName`, `backup[].service` and `globalEnvs[].services[]` references name services present after root and variant files are merged. Omitted optional references retain their runtime defaults; the spec does not choose a service implicitly. Findings identify the manifest field, its defining source fragment and the affected variant. +**SPEC-M10: Manifest service references exist in the resolved compose.** Explicit `mainService`, `chain.serviceName`, `backup[].service`, `globalEnvs[].services[]`, `nodes` keys and `nodes..validatorService` references name services present after root and variant files are merged. Omitted optional references retain their runtime defaults; the spec does not choose a service implicitly. Findings identify the manifest field, its defining source fragment and the affected variant. **SPEC-M11: Global environment names match the runtime catalogue.** Entries in `globalEnvs[].envs` use short names from the `GLOBAL_ENVS` catalogue bundled with `@dappnode/types`, for example `PUBLIC_IP`, `HOSTNAME` or `ENVS_ACTIVE`. DAPPMANAGER adds `_DAPPNODE_GLOBAL_` at install, so `_DAPPNODE_GLOBAL_PUBLIC_IP` in the manifest would be prefixed twice. Catalogue keys are not aliases: the key `ACTIVE` maps to `ENVS_ACTIVE`, which is the valid manifest value. Catalogue updates must be released through shared types and consumed by the SDK before packages adopt newly supported names. +**SPEC-M12: Node declarations are complete.** Checked on the merged manifest of each variant (see [Node declarations](#node-declarations)). Every entry of `nodes` is an object with a string `role` and `probe.kind` and, after merging, a string `network`. A missing `network` is reported in the variant manifest. `ethereum-execution` nodes declare `probe.rpcPort` and `probe.enginePort`, `ethereum-beacon` nodes `probe.apiPort`, as port numbers. A `status-report` node declares `report`. With `report: "healthcheck"` the service defines a `healthcheck` in the compose. Unknown `role`, `probe.kind` and `report` values are not reported: the contract only grows and DAPPMANAGER ignores what it does not know. + +**SPEC-M13: Node declarations contain no addresses.** No value under `nodes` looks like a URL (`scheme://`, `//`) or a hostname (`localhost`, an IP address, `name:port`, a dotted domain), and no key is named like an address (`url`, `uri`, `host`, `hostname`, `endpoint`, as a whole word of the key, e.g. `rpcUrl`). DAPPMANAGER decides which address to call; a package declares ports only. + ### Manifest semantics The source manifest describes package metadata and installation instructions. A template root and its variant manifests are source fragments; the merged result is the installable manifest and is validated against the full shared schema. Root fragments need not repeat each variant’s required identity fields. @@ -59,6 +63,82 @@ The current manifest merge recursively combines objects, replaces scalar values For example, if the root upstream list is `[app, scripts]` and a variant supplies only a compatible `[appOverride]`, the resolved list is `[mergedApp, scripts]`. SPEC-M06 requires the root and variant to retain the same repository at every overlapping position. Checks of argument values and service references run on this resolved result. A move to whole-array replacement or merging by a stable key requires a coordinated migration across the SDK and consumers. +### Node declarations + +A node package declares in the optional top-level `nodes` field which of its services run a node, and reports what each node's client is doing through that service's Docker healthcheck. The package says what its own client is doing; DAPPMANAGER decides whether the node is synced, waiting on another node or stalled, and how long is left. Today DAPPMANAGER reads the healthcheck reports of `ethereum-execution` nodes (looked up by `role: execution` and `report: "healthcheck"`). The `status-report` probe kind and the HTTP report source are defined but not consumed yet. + +`nodes` is keyed by compose service name. Each entry: + +| Field | Value | +|---|---| +| `role` | Required. `execution`, `consensus`, `node` or `validator`. | +| `network` | Required after merging. The DAPPMANAGER network name: `mainnet`, `gnosis`, `hoodi`, `sepolia`, `lukso`. | +| `probe.kind` | Required. `ethereum-execution`, `ethereum-beacon` or `status-report`. | +| `probe.rpcPort`, `probe.enginePort` | Required for `ethereum-execution`: JSON-RPC and Engine API ports of the service. | +| `probe.apiPort` | Required for `ethereum-beacon`: Beacon API port of the service. | +| `report` | `"healthcheck"` when the service's healthcheck prints a status report. `{ "http": { "port", "path" } }` is reserved for a report served by the service. | +| `validatorService`, `requires`, `probe.maxHeadAgeSeconds` | Defined by the schema (validator client service of a consensus node, `[{ "network", "role" }]` this node needs, head age after which a `status-report` node is shown as behind); not used by DAPPMANAGER yet. | + +Ports are the service's own ports; never add hostnames or URLs (SPEC-M13). Values outside these lists are allowed and ignored by DAPPMANAGER. + +In a template, the root manifest holds everything the variants share and each variant manifest adds only the network. Objects are deep-merged by service name (see [Variant inheritance](#variant-inheritance)): + +```json +"nodes": { + "reth": { + "role": "execution", + "probe": { "kind": "ethereum-execution", "rpcPort": 8545, "enginePort": 8551 }, + "report": "healthcheck" + } +} +``` + +```json +"nodes": { "reth": { "network": "mainnet" } } +``` + +The SDK checks the merged result: SPEC-M10 (the key and `validatorService` are compose services), SPEC-M12 (complete) and SPEC-M13 (no addresses). + +#### Status report + +With `report: "healthcheck"`, the service's healthcheck prints one JSON object as the last line of stdout, at most 2,048 bytes. Only `version` and `state` are required; leave out what is unknown instead of sending `null` or `0`. + +| Field | Value | +|---|---| +| `version` | `1`. | +| `state` | `starting` (the node's API does not answer yet: start-up, snapshot or checkpoint download, database opening), `syncing`, `synced` or `error`. The client's own view. | +| `phase` | What the node is doing, e.g. `"Downloading state"`. Sentence case, no trailing period, at most 60 characters. | +| `progress` | Progress of the current phase, 0-100. Omit it when it cannot be measured; never 100 while the phase runs (cap at 99.9). | +| `height`, `headTime` | Latest block the node serves and its timestamp in Unix seconds. | +| `position`, `target` | For a phase measured in blocks: the block the phase has reached, and the block the node syncs towards when the client knows it. | +| `unit` | Unit of `height`, `position` and `target`. Default `blocks`. | +| `peers` | Connected peers. | +| `awaitingTarget` | `true` when the client has nothing to sync towards yet (an execution client no consensus client has driven since it started). Omit it otherwise. | +| `background` | Work that continues after reaching the head, e.g. `"Indexing transactions"`, at most 60 characters. | +| `issues` | Up to 5 problems the client reports about itself, at most 120 characters each. Not "No peers": DAPPMANAGER derives that from `peers`. | +| `details` | Up to 8 `{ "label", "value" }` pairs, already formatted, at most 80 characters each, for a troubleshooting tooltip. | + +A phase is measured either with `progress` or with `position` and `target`, not both; for a block-measured phase DAPPMANAGER computes the percentage, blocks left and time left. Strings are untrusted: DAPPMANAGER removes control characters, cuts them to the lengths above and shows them as plain text. A report larger than 2,048 bytes, with another `version` or an unknown `state` is ignored, and so is the latest report once it is older than three healthcheck intervals. + +For an `ethereum-execution` node, DAPPMANAGER decides synced or not itself (latest block recent, consensus client at the head) and ignores `state: synced`. It takes `phase`, `progress`, `position`, `target`, `awaitingTarget`, `background`, `issues` and `details` from the report, shows `phase` and `progress` of a `starting` report while the RPC does not answer, and with `awaitingTarget: true` shows "Waiting for the consensus client" while the consensus client is not at the head. + +#### Healthcheck + +```yaml +healthcheck: + test: ["CMD", "/usr/local/bin/node-status"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 60s +``` + +- Exit 0 whenever the script printed a report with state `starting`, `syncing` or `synced`; non-zero only for `error` or when nothing could be determined. A syncing node must not be unhealthy. +- Nothing else on stdout on success. Diagnostics go to stderr and stay short: Docker keeps 4,096 bytes of combined output per run. +- Answer before the node's API is up: report `starting`, with a `phase` (and `progress` when the entrypoint leaves one to read) for long pre-start work. +- Finish well inside the timeout: every network call has its own 2-3 s timeout and calls only `127.0.0.1` or `localhost`. Write nothing to the data directory and never print credentials or secrets. +- POSIX `sh` with `curl` and `jq` only. Client-specific logic stays in the package; shared helpers (JSON-RPC calls, Prometheus metrics, printing the report) live in `dappnode/staker-package-scripts`. + ### Templates (multi-variant packages) **SPEC-T01: The template root manifest has no `name` or `version`.** When a package has variants, each variant manifest declares its own `name` and `version` and the root holds only shared fields. A named root becomes a phantom package for pin cleanup, dashboards and on-chain sync. diff --git a/src/spec/checkPackageSpec.ts b/src/spec/checkPackageSpec.ts index 65d0fcb9..a1c535a9 100644 --- a/src/spec/checkPackageSpec.ts +++ b/src/spec/checkPackageSpec.ts @@ -12,13 +12,14 @@ import { checkManifestReferences, manifestFieldIsDefined } from "./manifestReferences.js"; +import { checkNodes } from "./nodes.js"; const manifestFileName = "dappnode_package.json"; const packageNamePattern = /^[a-z0-9]+(-[a-z0-9]+)*\.(dnp|public)\.dappnode\.eth$/; const variantNamePattern = /^[a-z0-9]+(-[a-z0-9]+)*$/; /** Supported by DAPPMANAGER but not yet in the published manifest schema. */ -const knownUnreleasedManifestFields = ["upnpDisable"]; +const knownUnreleasedManifestFields = ["upnpDisable", "nodes"]; /** Single release files that are copied (not merged) from the root or the variant. */ const singleCopiedReleaseFiles = [ "avatar", @@ -427,6 +428,20 @@ export function checkPackageSpec({ ); } + for (const finding of checkNodes(sourceManifest, compose, { + inTemplate: isTemplate + })) { + // A missing network belongs in the package's own manifest (the variant, in a template). + const dir = finding.fixInVariant + ? manifestDirs[manifestDirs.length - 1] + : manifestOrigin(m => manifestFieldIsDefined(m, finding.field)); + const checked = + pkg.variant && (finding.perVariant || dir !== rootDir) + ? ` Checked for variant "${pkg.variant}".` + : ""; + add(finding.rule, `${finding.message}${checked}`, manifestFileIn(dir)); + } + const services = Object.keys(compose.services || {}); for (const exposable of manifest.exposable || []) if (exposable.serviceName && !services.includes(exposable.serviceName)) { diff --git a/src/spec/manifestReferences.ts b/src/spec/manifestReferences.ts index eb5cec4b..a3fa9113 100644 --- a/src/spec/manifestReferences.ts +++ b/src/spec/manifestReferences.ts @@ -1,4 +1,5 @@ import { Compose, GLOBAL_ENVS, Manifest } from "@dappnode/types"; +import { getManifestNodes, nodeField } from "./nodes.js"; interface ManifestReferenceFinding { rule: "SPEC-M10" | "SPEC-M11"; @@ -38,6 +39,20 @@ export function checkManifestReferences( checkService(`backup[${i}].service`, entry?.service) ); + for (const [service, node] of Object.entries( + getManifestNodes(manifest) || {} + )) { + const field = nodeField(service); + if (!services.has(service)) + findings.push({ + rule: "SPEC-M10", + field, + message: `${field} declares a node for service "${service}", which is not in the compose.` + }); + if (node && typeof node === "object" && "validatorService" in node) + checkService(`${field}.validatorService`, node.validatorService); + } + if (Array.isArray(manifest.globalEnvs)) manifest.globalEnvs.forEach((entry, i) => { if (Array.isArray(entry?.services)) @@ -72,7 +87,11 @@ export function manifestFieldIsDefined( field: string ): boolean { let value: unknown = manifest; - for (const key of field.replace(/\[(\d+)\]/g, ".$1").split(".")) { + // Paths such as backup[0].service or nodes["bind.dnp.dappnode.eth"].role + const keys = [ + ...field.matchAll(/([^.[\]]+)|\[(\d+)\]|\[("(?:[^"\\]|\\.)*")\]/g) + ].map(([, name, index, quoted]) => name ?? index ?? JSON.parse(quoted)); + for (const key of keys) { if ( value === null || typeof value !== "object" || diff --git a/src/spec/nodes.ts b/src/spec/nodes.ts new file mode 100644 index 00000000..beab342d --- /dev/null +++ b/src/spec/nodes.ts @@ -0,0 +1,218 @@ +import { Compose } from "@dappnode/types"; + +/** + * Checks of the manifest `nodes` field (doc/package-spec.md, SPEC-M12 and SPEC-M13). + * The service references in it are checked with the other references (SPEC-M10). + */ + +export interface NodeFinding { + rule: "SPEC-M12" | "SPEC-M13"; + /** Manifest field the finding is about, used to find the source fragment that defines it. */ + field: string; + message: string; + /** The fix belongs in the manifest that names the package (the variant, in a template). */ + fixInVariant?: boolean; + /** The result depends on the variant's compose, not only on the manifest. */ + perVariant?: boolean; +} + +/** Contract values the dappmanager knows today. Other values are allowed: the contract only grows. */ +export const nodeRoles = ["execution", "consensus", "node", "validator"]; +export const nodeProbeKinds = [ + "ethereum-execution", + "ethereum-beacon", + "status-report" +]; + +/** Ports each known probe kind is called on. */ +const probePorts: Record = { + "ethereum-execution": ["rpcPort", "enginePort"], + "ethereum-beacon": ["apiPort"] +}; + +/** Words that name an address in a key such as rpcUrl, beacon_host or ENDPOINT. */ +const addressWords = new Set([ + "url", + "urls", + "uri", + "uris", + "host", + "hosts", + "hostname", + "hostnames", + "endpoint", + "endpoints" +]); +/** Keys whose values are not addresses even when they contain dots: an HTTP path, a compose service. */ +const notHostnameKeys = new Set(["path", "validatorService"]); + +/** The manifest `nodes` field, if it is an object. `@dappnode/types` 0.1.41 does not type it yet. */ +export function getManifestNodes( + manifest: unknown +): Record | undefined { + const nodes = isObject(manifest) ? manifest.nodes : undefined; + return isObject(nodes) ? nodes : undefined; +} + +/** `nodes.reth`, or `nodes["bind.dnp.dappnode.eth"]` for a service name with dots. */ +export function nodeField(service: string, ...rest: string[]): string { + const key = /^[\w-]+$/.test(service) + ? `.${service}` + : `[${JSON.stringify(service)}]`; + return ["nodes" + key, ...rest].join("."); +} + +/** Checks the merged manifest of one package (root and variant) against its merged compose. */ +export function checkNodes( + manifest: unknown, + compose: Compose, + { inTemplate = false }: { inTemplate?: boolean } = {} +): NodeFinding[] { + const findings: NodeFinding[] = []; + const nodes = getManifestNodes(manifest); + if (!nodes) return findings; + const services = compose.services || {}; + + for (const [service, node] of Object.entries(nodes)) { + const field = nodeField(service); + if (!isObject(node)) { + findings.push({ + rule: "SPEC-M12", + field, + message: `${field} must be an object with role, probe and network.` + }); + continue; + } + const complete = (sub: string, message: string, extra = {}) => + findings.push({ + rule: "SPEC-M12", + field: nodeField(service, ...sub.split(".").filter(Boolean)), + message, + ...extra + }); + + if (typeof node.role !== "string") + complete( + "role", + `${field}.role must be a string: ${nodeRoles.join(", ")}.` + ); + + const probe = isObject(node.probe) ? node.probe : undefined; + const kind = probe?.kind; + if (typeof kind !== "string") + complete( + "probe.kind", + `${field}.probe.kind must be a string: ${nodeProbeKinds.join(", ")}.` + ); + + if (typeof node.network !== "string") + complete( + "network", + inTemplate + ? `${field} has no network after merging the root and variant manifests; set "network" in each variant manifest.` + : `${field} has no network; set "network", for example "mainnet".`, + { fixInVariant: true } + ); + + if (typeof kind === "string" && Object.hasOwn(probePorts, kind)) { + const missing = probePorts[kind].filter(port => !isPort(probe?.[port])); + if (missing.length > 0) + complete( + "probe", + `${field}.probe has no valid ${missing.join( + " or " + )}; ${kind} nodes declare ${probePorts[kind].join( + " and " + )} as port numbers.` + ); + } + + if (kind === "status-report" && node.report === undefined) + complete( + "probe.kind", + `${field} uses probe kind status-report but has no report; set "report": "healthcheck".` + ); + + if (node.report === "healthcheck" && service in services) { + const healthcheck = (services[service] as { healthcheck?: unknown }) + .healthcheck; + if (!hasHealthcheck(healthcheck)) + complete( + "report", + `${field} reports through its healthcheck, but service "${service}" defines no healthcheck in the compose.`, + { perVariant: true } + ); + } + + findings.push(...findAddresses(node, field)); + } + return findings; +} + +/** Keys named like an address, and string values that look like a URL or a hostname. */ +function findAddresses(value: unknown, field: string, key = ""): NodeFinding[] { + if (Array.isArray(value)) + return value.flatMap((item, i) => + findAddresses(item, `${field}[${i}]`, key) + ); + if (isObject(value)) + return Object.entries(value).flatMap(([k, v]) => { + const sub = `${field}.${k}`; + return keyNamesAddress(k) + ? [ + { + rule: "SPEC-M13" as const, + field: sub, + message: `${sub} names an address; declare ports only, the dappmanager decides which address to call.` + } + ] + : findAddresses(v, sub, k); + }); + if (typeof value === "string" && looksLikeAddress(value, key)) + return [ + { + rule: "SPEC-M13", + field, + message: `${field} is "${value}", which looks like a URL or hostname; declare ports only, the dappmanager decides which address to call.` + } + ]; + return []; +} + +function keyNamesAddress(key: string): boolean { + return key + .replace(/([a-z0-9])([A-Z])/g, "$1 $2") + .toLowerCase() + .split(/[^a-z0-9]+/) + .some(word => addressWords.has(word)); +} + +function looksLikeAddress(value: string, key: string): boolean { + const text = value.trim(); + if (/^[a-z][a-z0-9+.-]*:\/\//i.test(text) || text.startsWith("//")) + return true; + if (notHostnameKeys.has(key)) return false; + return ( + /^localhost(:\d+)?(\/.*)?$/i.test(text) || + /^\d{1,3}(\.\d{1,3}){3}(:\d+)?(\/.*)?$/.test(text) || + /^[a-z0-9-]+(\.[a-z0-9-]+)*:\d+(\/.*)?$/i.test(text) || + /^([a-z0-9-]+\.)+[a-z][a-z0-9-]*[a-z0-9](\/.*)?$/i.test(text) + ); +} + +function hasHealthcheck(healthcheck: unknown): boolean { + if (!isObject(healthcheck) || healthcheck.disable === true) return false; + const test = healthcheck.test; + return !( + (Array.isArray(test) && test[0] === "NONE") || + (typeof test === "string" && test.trim() === "NONE") + ); +} + +function isPort(value: unknown): boolean { + return Number.isInteger(value) && Number(value) > 0 && Number(value) < 65536; +} + +function isObject(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} diff --git a/src/spec/rules.ts b/src/spec/rules.ts index 80a623d8..ad43d23c 100644 --- a/src/spec/rules.ts +++ b/src/spec/rules.ts @@ -45,12 +45,20 @@ export const specRules = { }, "SPEC-M10": { title: "Manifest service references exist in compose", - why: "mainService, chain, backup and global-env service references must resolve after root and variant files are merged." + why: "mainService, chain, backup, global-env and node service references must resolve after root and variant files are merged." }, "SPEC-M11": { title: "Global environment names match the runtime catalogue", why: "DAPPMANAGER prefixes short global-env names at install; unknown or already-prefixed names cannot be injected." }, + "SPEC-M12": { + title: "Node declarations are complete", + why: "DAPPMANAGER matches a node by role, network and probe kind, calls it on the declared ports and reads its status report from the declared source; an incomplete entry gets no status." + }, + "SPEC-M13": { + title: "Node declarations contain no addresses", + why: "DAPPMANAGER decides which address to call from the package and service; a URL or hostname in the manifest is never used and goes stale." + }, // Templates (multi-variant packages) "SPEC-T01": { title: "Template root manifest has no name or version", diff --git a/test/files/variantMerge.test.ts b/test/files/variantMerge.test.ts index 3c9dde8c..9990b937 100644 --- a/test/files/variantMerge.test.ts +++ b/test/files/variantMerge.test.ts @@ -4,6 +4,9 @@ import yaml from "js-yaml"; import { expect } from "chai"; import { readSetupWizardIfExists } from "../../src/files/setupWizard/readSetupWizardIfExists.js"; import { readNotificationsIfExists } from "../../src/files/notifications/readNotificationsIfExists.js"; +import { generatePackagesProps } from "../../src/tasks/buildAndUpload/generatePackagesProps.js"; +import { readManifest, writeManifest } from "../../src/files/index.js"; +import { ManifestFormat } from "../../src/files/manifest/types.js"; import { temporaryDirectory } from "../helpers/fixtures.js"; describe("root and variant config merging", () => { @@ -16,6 +19,76 @@ describe("root and variant config merging", () => { }); afterEach(() => fs.rmSync(root, { recursive: true, force: true })); + it("deep-merges manifest nodes by service and keeps them when the manifest is written", () => { + // Root holds what every variant shares, each variant only its network. + const rootNodes = { + reth: { + role: "execution", + probe: { kind: "ethereum-execution", rpcPort: 8545, enginePort: 8551 }, + report: "healthcheck" + } + }; + fs.writeFileSync( + path.join(root, "dappnode_package.json"), + JSON.stringify({ description: "Reth", nodes: rootNodes, license: "MIT" }) + ); + fs.writeFileSync( + path.join(root, "docker-compose.yml"), + yaml.dump({ services: { reth: { image: "reth:1.0.0" } } }) + ); + const hoodi = path.join(root, "package_variants", "hoodi"); + fs.mkdirSync(hoodi); + for (const [dir, network] of [ + [variant, "mainnet"], + [hoodi, "hoodi"] + ]) { + fs.writeFileSync( + path.join(dir, "dappnode_package.json"), + JSON.stringify({ + name: `reth-${network}.dnp.dappnode.eth`, + version: "0.1.0", + nodes: { reth: { network } } + }) + ); + fs.writeFileSync( + path.join(dir, "docker-compose.yml"), + yaml.dump({ services: { reth: {} } }) + ); + } + + const packages = generatePackagesProps({ + variants: ["mainnet", "hoodi"], + rootDir: root, + variantsDirPath: path.join(root, "package_variants") + }); + for (const [pkg, network] of [ + [packages[0], "mainnet"], + [packages[1], "hoodi"] + ] as const) { + const nodes = (pkg.manifest as { nodes?: unknown }).nodes; + expect(nodes, network).to.deep.equal({ + reth: { ...rootNodes.reth, network } + }); + // The root position and order of the field and its keys survive a write. + const out = path.join(root, `out-${network}`); + fs.mkdirSync(out); + writeManifest(pkg.manifest, ManifestFormat.json, { dir: out }); + const written = readManifest([{ dir: out }]).manifest; + expect(JSON.stringify(written)).to.equal(JSON.stringify(pkg.manifest)); + expect(Object.keys(written).slice(0, 3)).to.deep.equal([ + "description", + "nodes", + "license" + ]); + } + // The root manifest is not changed by the merge. + expect( + JSON.parse( + fs.readFileSync(path.join(root, "dappnode_package.json"), "utf8") + ).nodes + ).to.deep.equal(rootNodes); + }); + it("replaces arrays inside a setup-wizard field instead of merging them by index", () => { fs.writeFileSync( path.join(root, "setup-wizard.yml"), diff --git a/test/spec/checkPackageSpec.test.ts b/test/spec/checkPackageSpec.test.ts index 66c6d0f7..746cdfc5 100644 --- a/test/spec/checkPackageSpec.test.ts +++ b/test/spec/checkPackageSpec.test.ts @@ -483,6 +483,203 @@ describe("package spec checks", function () { ).to.equal(true); }); + describe("node declarations", () => { + const rethNode = { + role: "execution", + probe: { kind: "ethereum-execution", rpcPort: 8545, enginePort: 8551 }, + report: "healthcheck" + }; + const healthcheck = { + test: ["CMD", "/usr/local/bin/node-status"], + interval: "30s", + timeout: "10s", + retries: 3, + start_period: "60s" + }; + const writeTemplate = ( + rootNodes: object, + variants: Record, + services: object = { reth: { image: "reth:1.0.0", healthcheck } } + ) => { + write("dappnode_package.json", { nodes: rootNodes }); + write("docker-compose.yml", yaml.dump({ services })); + for (const [variant, nodes] of Object.entries(variants)) { + write(`package_variants/${variant}/dappnode_package.json`, { + name: `reth-${variant}.dnp.dappnode.eth`, + version: "0.1.0", + ...(nodes ? { nodes } : {}) + }); + write( + `package_variants/${variant}/docker-compose.yml`, + yaml.dump({ services: { reth: {} } }) + ); + } + }; + + it("accepts a root declaration completed by each variant's network, and unknown values", () => { + writeTemplate( + { + reth: rethNode, + // Values outside today's contract are allowed: the contract only grows. + sidecar: { + role: "indexer", + probe: { kind: "bitcoin-core" }, + report: { http: { port: 8080, path: "/status.json" } } + } + }, + { + mainnet: { + reth: { network: "mainnet" }, + sidecar: { network: "mainnet" } + }, + hoodi: { reth: { network: "hoodi" }, sidecar: { network: "hoodi" } } + }, + { + reth: { image: "reth:1.0.0", healthcheck }, + sidecar: { image: "sidecar:1.0.0" } + } + ); + // No SPEC-M07 either, although the installed manifest schema predates the field. + expect(check(dir)).to.deep.equal([]); + }); + + it("reports a variant that leaves the network out in that variant's manifest", () => { + writeTemplate( + { reth: rethNode }, + { mainnet: { reth: { network: "mainnet" } }, hoodi: undefined } + ); + const findings = check(dir); + expect(findings).to.have.length(1); + expect(findings[0].rule).to.equal("SPEC-M12"); + expect(findings[0].message) + .to.include("nodes.reth has no network") + .and.include('variant "hoodi"'); + expect(findings[0].file).to.equal( + path.join(dir, "package_variants/hoodi/dappnode_package.json") + ); + }); + + it("reports incomplete declarations and unknown services once, in the root", () => { + writeTemplate( + { + reth: { + ...rethNode, + probe: { kind: "ethereum-execution", rpcPort: "8545" } + }, + beacon: { + role: "consensus", + probe: { kind: "ethereum-beacon" }, + validatorService: "validator" + }, + status: { probe: { kind: "status-report" } }, + ghost: { + role: "node", + probe: { kind: "status-report" }, + report: "healthcheck" + }, + broken: "reth" + }, + { + mainnet: { + reth: { network: "mainnet" }, + beacon: { network: "mainnet" }, + status: { network: "mainnet" }, + ghost: { network: "mainnet" }, + broken: undefined + }, + hoodi: { + reth: { network: "hoodi" }, + beacon: { network: "hoodi" }, + status: { network: "hoodi" }, + ghost: { network: "hoodi" } + } + }, + { + reth: { image: "reth:1.0.0" }, + beacon: { image: "beacon:1.0.0" }, + status: { image: "status:1.0.0" }, + broken: { image: "broken:1.0.0" } + } + ); + const findings = check(dir); + const messages = (rule: string) => + findings.filter(f => f.rule === rule).map(f => f.message); + expect(rulesOf(findings)).to.deep.equal(["SPEC-M10", "SPEC-M12"]); + expect(messages("SPEC-M10")).to.have.length(4); + expect(messages("SPEC-M10").join("\n")) + .to.include('nodes.ghost declares a node for service "ghost"') + .and.include( + 'nodes.beacon.validatorService refers to service "validator"' + ); + expect(messages("SPEC-M12")).to.have.members([ + "nodes.reth.probe has no valid rpcPort or enginePort; ethereum-execution nodes declare rpcPort and enginePort as port numbers.", + "nodes.beacon.probe has no valid apiPort; ethereum-beacon nodes declare apiPort as port numbers.", + "nodes.status.role must be a string: execution, consensus, node, validator.", + 'nodes.status uses probe kind status-report but has no report; set "report": "healthcheck".', + 'nodes.reth reports through its healthcheck, but service "reth" defines no healthcheck in the compose. Checked for variant "mainnet".', + 'nodes.reth reports through its healthcheck, but service "reth" defines no healthcheck in the compose. Checked for variant "hoodi".', + "nodes.broken must be an object with role, probe and network." + ]); + // Values inherited from the root are reported in the root manifest. + expect( + findings + .filter(f => f.rule === "SPEC-M12") + .every(f => f.file === path.join(dir, "dappnode_package.json")) + ).to.equal(true); + }); + + it("reports hostnames and URLs, and keys named like an address", () => { + write("dappnode_package.json", { + name: "reth.dnp.dappnode.eth", + version: "0.1.0", + nodes: { + reth: { + ...rethNode, + network: "mainnet", + probe: { ...rethNode.probe, rpcUrl: "http://reth:8545" }, + requires: [ + { network: "mainnet", role: "consensus", host: "beacon" } + ], + report: "http://reth.reth.dappnode:8080/status" + }, + "bind.dnp.dappnode.eth": { + role: "node", + network: "localhost:8545", + probe: { kind: "status-report", beaconEndpoint: "x" }, + report: { http: { port: 80, path: "//example.com/status" } } + }, + other: { + role: "node", + network: "geth.dappnode", + probe: { kind: "status-report" }, + report: { http: { port: 80, path: "/status" } } + } + } + }); + write( + "docker-compose.yml", + yaml.dump({ + services: { + reth: { image: "reth:1.0.0", healthcheck }, + "bind.dnp.dappnode.eth": { image: "bind:1.0.0" }, + other: { image: "other:1.0.0" } + } + }) + ); + const findings = check(dir); + expect(rulesOf(findings)).to.deep.equal(["SPEC-M13"]); + expect(findings.map(f => f.message.split(" ")[0])).to.have.members([ + "nodes.reth.probe.rpcUrl", + "nodes.reth.requires[0].host", + "nodes.reth.report", + 'nodes["bind.dnp.dappnode.eth"].network', + 'nodes["bind.dnp.dappnode.eth"].probe.beaconEndpoint', + 'nodes["bind.dnp.dappnode.eth"].report.http.path', + "nodes.other.network" + ]); + }); + }); + it("lets core packages keep container_name, which the installer relies on", () => { write("dappnode_package.json", { name: "bind.dnp.dappnode.eth",