feat(evm): inspect offline bytecode interfaces through EVMole (#1051)
* feat(evm): inspect offline bytecode interfaces through evmole * fix(evm): distinguish unsupported bytecode targets * style(evm): format verifier string-prefix checks
This commit is contained in:
@@ -0,0 +1,34 @@
|
||||
import { expect, it } from "vitest";
|
||||
import {
|
||||
decodeEvmBytecodeCarrier,
|
||||
EvmCarrierFailure,
|
||||
} from "./EvmBytecodeCarrier.js";
|
||||
|
||||
it.each(["6000FF", "0x6000ff", " \t0X6000FF\r\n"])(
|
||||
"decodes explicit hex without changing selected bytes: %j",
|
||||
(text) => {
|
||||
expect(
|
||||
Buffer.from(decodeEvmBytecodeCarrier(Buffer.from(text), "hex")).toString(
|
||||
"hex",
|
||||
),
|
||||
).toBe("6000ff");
|
||||
},
|
||||
);
|
||||
it.each(["0x1", "60 00", "0xzz", "\uFEFF6000", "\u00a06000"])(
|
||||
"rejects malformed carrier rather than guessing bytecode: %j",
|
||||
(text) => {
|
||||
expect(() => decodeEvmBytecodeCarrier(Buffer.from(text), "hex")).toThrow(
|
||||
EvmCarrierFailure,
|
||||
);
|
||||
},
|
||||
);
|
||||
it("distinguishes raw bytes, empty code and malformed UTF-8", () => {
|
||||
const bytes = Uint8Array.from([0xff, 0x00]);
|
||||
const decoded = decodeEvmBytecodeCarrier(bytes, "raw");
|
||||
expect(decoded).toEqual(bytes);
|
||||
expect(decoded).not.toBe(bytes);
|
||||
expect(() => decodeEvmBytecodeCarrier(bytes, "hex")).toThrow("valid UTF-8");
|
||||
expect(decodeEvmBytecodeCarrier(Buffer.from("0x"), "hex")).toEqual(
|
||||
new Uint8Array(),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,26 @@
|
||||
/** Expected carrier encoding failure, independent of the analysis engine. */
|
||||
export class EvmCarrierFailure extends Error {}
|
||||
|
||||
/** Decode only the explicitly selected representation; source carrier bytes are retained separately. */
|
||||
export const decodeEvmBytecodeCarrier = (
|
||||
bytes: Uint8Array,
|
||||
encoding: "raw" | "hex",
|
||||
): Uint8Array => {
|
||||
if (encoding === "raw") return Uint8Array.from(bytes);
|
||||
let text: string;
|
||||
try {
|
||||
text = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(
|
||||
bytes,
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
throw new EvmCarrierFailure("Hex carrier must be valid UTF-8.", { cause });
|
||||
}
|
||||
const code = text
|
||||
.replace(/^[\x09-\x0d\x20]+|[\x09-\x0d\x20]+$/g, "")
|
||||
.replace(/^0x/i, "");
|
||||
if (!/^(?:[a-fA-F0-9]{2})*$/.test(code))
|
||||
throw new EvmCarrierFailure(
|
||||
"Hex carrier requires complete hexadecimal byte pairs, an optional 0x prefix and outer ASCII whitespace; interior separators are invalid.",
|
||||
);
|
||||
return Uint8Array.from(Buffer.from(code, "hex"));
|
||||
};
|
||||
@@ -0,0 +1,55 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { selectEvmWorkerLimits } from "./EvmWorkerLimits.js";
|
||||
|
||||
const limits = (
|
||||
soft = "unlimited",
|
||||
hard = "unlimited",
|
||||
) => `Limit Soft Limit Hard Limit Units
|
||||
Max address space ${soft} ${hard} bytes
|
||||
Max cpu time unlimited unlimited seconds
|
||||
Max file size unlimited unlimited bytes
|
||||
`;
|
||||
it("uses configured maxima without equating virtual space and RSS", () => {
|
||||
expect(selectEvmWorkerLimits(limits())).toEqual({
|
||||
ok: true,
|
||||
value: {
|
||||
addressSpaceBytes: 3221225472,
|
||||
cpuSeconds: 30,
|
||||
fileSizeBytes: 16777216,
|
||||
},
|
||||
});
|
||||
});
|
||||
it.each([
|
||||
["1073741824", "2147483648", 1073741824],
|
||||
["2147483648", "2147483648", 2147483648],
|
||||
["0", "0", 0],
|
||||
["9223372036854775807", "9223372036854775807", 3221225472],
|
||||
])(
|
||||
"preserves tighter soft/hard boundaries without integer loss: %s/%s",
|
||||
(soft, hard, expected) => {
|
||||
expect(selectEvmWorkerLimits(limits(soft, hard))).toMatchObject({
|
||||
ok: true,
|
||||
value: { addressSpaceBytes: expected },
|
||||
});
|
||||
},
|
||||
);
|
||||
it("independently preserves CPU and file output restrictions", () => {
|
||||
expect(
|
||||
selectEvmWorkerLimits(
|
||||
limits()
|
||||
.replace("time unlimited unlimited", "time 5 10")
|
||||
.replace("size unlimited unlimited", "size 4096 8192"),
|
||||
),
|
||||
).toMatchObject({ ok: true, value: { cpuSeconds: 5, fileSizeBytes: 4096 } });
|
||||
});
|
||||
it.each([
|
||||
["not-text", null],
|
||||
["soft-unlimited-hard-finite", limits("unlimited", "2147483648")],
|
||||
["soft-exceeds-hard", limits("3", "2")],
|
||||
["missing-row", limits().replace("Max file size", "Max other size")],
|
||||
["duplicate-row", limits() + "Max cpu time 1 1 seconds\n"],
|
||||
["wrong-unit", limits().replace("bytes", "pages")],
|
||||
["oversized", "x".repeat(65537)],
|
||||
])("rejects malformed/ambiguous resource observations: %s", (_label, input) => {
|
||||
expect(selectEvmWorkerLimits(input).ok).toBe(false);
|
||||
});
|
||||
@@ -0,0 +1,58 @@
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import { EVM_INTERFACE_LIMITS } from "./EvmoleRelease.js";
|
||||
|
||||
/** Selected worker soft limits to configure; inherited hard limits are left unchanged. */
|
||||
export interface EvmWorkerLimits {
|
||||
readonly addressSpaceBytes: number;
|
||||
readonly cpuSeconds: number;
|
||||
readonly fileSizeBytes: number;
|
||||
}
|
||||
|
||||
/** Read only the three selected Linux limits, retaining tighter soft/hard boundaries. */
|
||||
export const selectEvmWorkerLimits = (
|
||||
raw: unknown,
|
||||
): Result<EvmWorkerLimits, string> => {
|
||||
if (typeof raw !== "string" || Buffer.byteLength(raw) > 64 * 1024)
|
||||
return err(
|
||||
"Linux resource limits must be text within the 64 KiB parsing budget.",
|
||||
);
|
||||
const selected: number[] = [];
|
||||
for (const [name, units, maximum] of [
|
||||
["Max address space", "bytes", EVM_INTERFACE_LIMITS.addressSpaceBytes],
|
||||
["Max cpu time", "seconds", 30],
|
||||
["Max file size", "bytes", EVM_INTERFACE_LIMITS.outputBytes],
|
||||
] as const) {
|
||||
const entries = raw
|
||||
.split("\n")
|
||||
.filter((line) => line.startsWith(name + " "));
|
||||
if (entries.length !== 1)
|
||||
return err(`Linux resource limits must report exactly one ${name} row.`);
|
||||
const match = new RegExp(
|
||||
`^${name}\\s+(unlimited|[0-9]+)\\s+(unlimited|[0-9]+)\\s+${units}\\s*$`,
|
||||
).exec(entries[0] ?? "");
|
||||
if (match === null)
|
||||
return err(`Malformed inherited Linux resource limit: ${name}.`);
|
||||
let effective = BigInt(maximum);
|
||||
const soft = match[1];
|
||||
const hard = match[2];
|
||||
if (soft === undefined || hard === undefined)
|
||||
return err(`Missing ${name} values.`);
|
||||
if (
|
||||
hard !== "unlimited" &&
|
||||
(soft === "unlimited" || BigInt(soft) > BigInt(hard))
|
||||
)
|
||||
return err(`Inherited ${name} soft limit exceeds its hard limit.`);
|
||||
for (const value of [soft, hard])
|
||||
if (value !== "unlimited" && BigInt(value) < effective)
|
||||
effective = BigInt(value);
|
||||
selected.push(Number(effective));
|
||||
}
|
||||
const [addressSpaceBytes, cpuSeconds, fileSizeBytes] = selected;
|
||||
if (
|
||||
addressSpaceBytes === undefined ||
|
||||
cpuSeconds === undefined ||
|
||||
fileSizeBytes === undefined
|
||||
)
|
||||
return err("Required Linux resource limits were not selected.");
|
||||
return ok({ addressSpaceBytes, cpuSeconds, fileSizeBytes });
|
||||
};
|
||||
@@ -0,0 +1,205 @@
|
||||
import type { EvmWorkerLimits } from "./EvmWorkerLimits.js";
|
||||
import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
|
||||
import {
|
||||
AnalysisError,
|
||||
type AnalysisCapturedOutput,
|
||||
} from "../domain/analysisErrorBase.js";
|
||||
import type { ProviderProcessSnapshot } from "../process/ProviderProcess.js";
|
||||
import {
|
||||
AnalysisAccessDeniedError,
|
||||
AnalysisArtifactChangedError,
|
||||
AnalysisCapabilityUnavailableError,
|
||||
AnalysisCancelledError,
|
||||
AnalysisInputError,
|
||||
AnalysisOutputError,
|
||||
AnalysisResourceConstraintError,
|
||||
AnalysisTimeoutError,
|
||||
} from "../domain/analysisErrorCore.js";
|
||||
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
|
||||
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
|
||||
import { OwnedCommandFailure } from "../process/OwnedCommand.js";
|
||||
import {
|
||||
EVMOLE_PROVIDER_IDENTITY,
|
||||
EVM_INTERFACE_LIMITS,
|
||||
EVM_FILE_SIZE_FAILURE_EXIT,
|
||||
} from "./EvmoleRelease.js";
|
||||
|
||||
/** Correlate a reserved exit with the owned worker's actual failure branch. */
|
||||
export interface EvmFileSizeFailureEvidence {
|
||||
readonly verified: boolean;
|
||||
readonly failure: string | null;
|
||||
}
|
||||
|
||||
/** Keep carrier read, engine and owned lifecycle failures distinct. */
|
||||
export const evmInterfaceFailure = (
|
||||
cause: unknown,
|
||||
phase: "configuration" | "artifact-read" | "worker",
|
||||
path: string,
|
||||
workerLimits?: EvmWorkerLimits,
|
||||
limiter = "/usr/bin/prlimit",
|
||||
fileFailure?: EvmFileSizeFailureEvidence,
|
||||
): AnalysisError => {
|
||||
if (cause instanceof AnalysisError) return cause;
|
||||
if (cause instanceof OwnedCommandFailure) {
|
||||
const outputOptions =
|
||||
cause.snapshot === null
|
||||
? undefined
|
||||
: { capturedOutput: capturedEvmOutput(cause.snapshot) };
|
||||
if (cause.cleanupFailure !== null)
|
||||
return new ProviderCleanupError(
|
||||
EVMOLE_PROVIDER_IDENTITY.id,
|
||||
cause.resources,
|
||||
{
|
||||
reason: cause.cleanupFailure,
|
||||
...(cause.snapshot === null
|
||||
? {}
|
||||
: { captured_output: { ...capturedEvmOutput(cause.snapshot) } }),
|
||||
previous_error: {
|
||||
failure_kind: cause.reason,
|
||||
message: cause.message,
|
||||
exit_code: cause.snapshot?.exitCode ?? null,
|
||||
signal: cause.snapshot?.signal ?? null,
|
||||
stdout: cause.snapshot?.stdout.text ?? null,
|
||||
stderr: cause.snapshot?.stderr.text ?? null,
|
||||
},
|
||||
},
|
||||
{ operation: "inspect_evm_interface", cause },
|
||||
);
|
||||
if (cause.reason === "cancelled")
|
||||
return new AnalysisCancelledError("inspect_evm_interface", outputOptions);
|
||||
if (cause.reason === "timeout")
|
||||
return new AnalysisTimeoutError(
|
||||
"inspect_evm_interface",
|
||||
EVM_INTERFACE_LIMITS.timeoutMs,
|
||||
outputOptions,
|
||||
);
|
||||
if (cause.reason === "output-limit")
|
||||
return new AnalysisOutputError(
|
||||
"inspect_evm_interface",
|
||||
cause.message,
|
||||
outputOptions,
|
||||
);
|
||||
if (
|
||||
cause.reason === "process" &&
|
||||
(cause.snapshot?.signal === "SIGXCPU" ||
|
||||
cause.snapshot?.signal === "SIGXFSZ" ||
|
||||
(fileFailure?.verified === true &&
|
||||
cause.snapshot?.exitCode === EVM_FILE_SIZE_FAILURE_EXIT &&
|
||||
cause.snapshot.signal === null))
|
||||
)
|
||||
return new AnalysisResourceConstraintError(
|
||||
"inspect_evm_interface",
|
||||
cause.snapshot.signal === "SIGXCPU" ? "cpu" : "file-size",
|
||||
(cause.snapshot.signal === null
|
||||
? "Owned EVM worker reported EFBIG while writing its reply; the exact write failure cause is unknown."
|
||||
: `Owned EVM command terminated with ${cause.snapshot.signal}; the exact signal cause is unknown.`) +
|
||||
" Effective worker limits are unknown. Configured soft limits are retained separately.",
|
||||
workerLimits === undefined
|
||||
? null
|
||||
: {
|
||||
configured_soft_limits: {
|
||||
address_space_bytes: workerLimits.addressSpaceBytes,
|
||||
cpu_seconds: workerLimits.cpuSeconds,
|
||||
file_size_bytes: workerLimits.fileSizeBytes,
|
||||
},
|
||||
effective_soft_limits: null,
|
||||
},
|
||||
outputOptions,
|
||||
);
|
||||
}
|
||||
if (
|
||||
cause instanceof Error &&
|
||||
"code" in cause &&
|
||||
"syscall" in cause &&
|
||||
typeof cause.syscall === "string" &&
|
||||
cause.syscall.startsWith("spawn ")
|
||||
) {
|
||||
const reason = `Configured util-linux prlimit could not launch (${String(cause.code)}): ${limiter}. Check its executable/interpreter and host execute access.`;
|
||||
return new AnalysisCapabilityUnavailableError(
|
||||
EVMOLE_PROVIDER_IDENTITY.id,
|
||||
"inspect_evm_interface",
|
||||
reason,
|
||||
{ cause, userMessage: reason },
|
||||
);
|
||||
}
|
||||
if (cause instanceof ArtifactReaderFailure) {
|
||||
if (cause.reason === "cancelled")
|
||||
return new AnalysisCancelledError("inspect_evm_interface");
|
||||
if (cause.reason === "integrity")
|
||||
return new AnalysisArtifactChangedError(
|
||||
"inspect_evm_interface",
|
||||
path,
|
||||
cause.message,
|
||||
{ cause },
|
||||
);
|
||||
if (
|
||||
phase === "artifact-read" &&
|
||||
["limit", "path", "format"].includes(cause.reason)
|
||||
)
|
||||
return new AnalysisInputError("inspect_evm_interface", { cause }, [
|
||||
{
|
||||
path: ["path"],
|
||||
reason: cause.reason === "limit" ? "out_of_range" : "invalid_format",
|
||||
message: cause.message,
|
||||
},
|
||||
]);
|
||||
}
|
||||
if (phase === "artifact-read" && cause instanceof Error && "code" in cause) {
|
||||
if (cause.code === "EACCES" || cause.code === "EPERM")
|
||||
return new AnalysisAccessDeniedError(
|
||||
"inspect_evm_interface",
|
||||
path,
|
||||
cause.code,
|
||||
{ cause },
|
||||
);
|
||||
if (cause.code === "ENOENT" || cause.code === "ENOTDIR")
|
||||
return new AnalysisInputError("inspect_evm_interface", { cause }, [
|
||||
{
|
||||
path: ["path"],
|
||||
reason: "invalid_value",
|
||||
message: `Selected bytecode carrier could not be read (${String(cause.code)}): ${path}.`,
|
||||
},
|
||||
]);
|
||||
}
|
||||
return new ProviderAdapterError(
|
||||
EVMOLE_PROVIDER_IDENTITY.id,
|
||||
"inspect_evm_interface",
|
||||
{
|
||||
cause,
|
||||
diagnostics: {
|
||||
phase,
|
||||
path,
|
||||
...(workerLimits === undefined
|
||||
? {}
|
||||
: { configured_resource_limits: { ...workerLimits } }),
|
||||
reason: cause instanceof Error ? cause.message : String(cause),
|
||||
...(fileFailure === undefined
|
||||
? {}
|
||||
: { file_size_failure_marker: { ...fileFailure } }),
|
||||
...(cause instanceof OwnedCommandFailure
|
||||
? {
|
||||
failure_kind: cause.reason,
|
||||
exit_code: cause.snapshot?.exitCode ?? null,
|
||||
signal: cause.snapshot?.signal ?? null,
|
||||
stdout: cause.snapshot?.stdout.text ?? null,
|
||||
stderr: cause.snapshot?.stderr.text ?? null,
|
||||
...(cause.snapshot === null
|
||||
? {}
|
||||
: {
|
||||
captured_output: { ...capturedEvmOutput(cause.snapshot) },
|
||||
}),
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
/** Preserve retained worker diagnostics with their observed truncation status. */
|
||||
export const capturedEvmOutput = (
|
||||
snapshot: ProviderProcessSnapshot,
|
||||
): AnalysisCapturedOutput => ({
|
||||
stdout: snapshot.stdout.text,
|
||||
stderr: snapshot.stderr.text,
|
||||
truncated: snapshot.diagnosticTruncated === true,
|
||||
});
|
||||
@@ -0,0 +1,66 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { projectEvmoleInterface } from "./EvmoleInterfaceAdapter.js";
|
||||
|
||||
it("preserves the actual producer keys, duplicates and unknown inference absence", () => {
|
||||
const raw = {
|
||||
functions: [
|
||||
{ selector: "aabbccdd", bytecodeOffset: 1, dispatch: "abi" },
|
||||
{
|
||||
selector: "aabbccdd",
|
||||
bytecodeOffset: 2,
|
||||
dispatch: "fallback",
|
||||
arguments: "uint256",
|
||||
stateMutability: "view",
|
||||
},
|
||||
],
|
||||
};
|
||||
const result = projectEvmoleInterface(raw);
|
||||
expect(result.raw).toEqual(raw);
|
||||
expect(result.functions).toEqual([
|
||||
{
|
||||
selector: "0xaabbccdd",
|
||||
bytecode_offset: 1,
|
||||
dispatch: "abi",
|
||||
inferred_arguments: null,
|
||||
inferred_state_mutability: null,
|
||||
},
|
||||
{
|
||||
selector: "0xaabbccdd",
|
||||
bytecode_offset: 2,
|
||||
dispatch: "fallback",
|
||||
inferred_arguments: "uint256",
|
||||
inferred_state_mutability: "view",
|
||||
},
|
||||
]);
|
||||
expect(projectEvmoleInterface({}).functions).toEqual([]);
|
||||
const metadata = {
|
||||
bytecodeOffset: 1,
|
||||
cborLength: 4,
|
||||
entries: [
|
||||
{ key: "reported", value: { type: "integer", value: 9007199254740992 } },
|
||||
],
|
||||
};
|
||||
expect(
|
||||
projectEvmoleInterface({ functions: [], metadata }).raw.metadata,
|
||||
).toEqual(metadata);
|
||||
expect(
|
||||
projectEvmoleInterface({
|
||||
functions: [],
|
||||
storage: undefined,
|
||||
transientStorage: undefined,
|
||||
disassembled: undefined,
|
||||
basicBlocks: undefined,
|
||||
controlFlowGraph: undefined,
|
||||
metadata: undefined,
|
||||
}).functions,
|
||||
).toEqual([]);
|
||||
});
|
||||
it.each([
|
||||
{ functions: [{ selector: "bad", bytecodeOffset: 0, dispatch: "abi" }] },
|
||||
{
|
||||
functions: [{ selector: "aabbccdd", bytecodeOffset: -1, dispatch: "abi" }],
|
||||
},
|
||||
{ metadata: {} },
|
||||
])("rejects producer representations outside the selected profile", (raw) => {
|
||||
expect(() => projectEvmoleInterface(raw)).toThrow();
|
||||
});
|
||||
@@ -0,0 +1,59 @@
|
||||
import { z } from "zod";
|
||||
|
||||
const offset = z.number().int().nonnegative();
|
||||
const reportedMetadata = z.strictObject({
|
||||
bytecodeOffset: offset,
|
||||
cborLength: offset,
|
||||
entries: z.array(
|
||||
z.strictObject({
|
||||
key: z.string(),
|
||||
value: z.discriminatedUnion("type", [
|
||||
z.strictObject({ type: z.literal("string"), value: z.string() }),
|
||||
z.strictObject({ type: z.literal("integer"), value: z.number() }),
|
||||
z.strictObject({ type: z.literal("bytes"), value: z.string() }),
|
||||
z.strictObject({ type: z.literal("bool"), value: z.boolean() }),
|
||||
z.strictObject({ type: z.literal("undecoded"), value: z.string() }),
|
||||
]),
|
||||
}),
|
||||
),
|
||||
});
|
||||
/** Parse the exact producer representation before assigning portable field names. */
|
||||
export const evmoleInterfaceReplySchema = z.strictObject({
|
||||
// The unchanged JS binding exposes disabled facets as own undefined keys.
|
||||
// Their JSON transport representation is absence; actual facet values are
|
||||
// outside this interface-only profile and must still fail validation.
|
||||
storage: z.undefined().optional(),
|
||||
transientStorage: z.undefined().optional(),
|
||||
disassembled: z.undefined().optional(),
|
||||
basicBlocks: z.undefined().optional(),
|
||||
controlFlowGraph: z.undefined().optional(),
|
||||
// Upstream also extracts metadata when selectors are requested, regardless
|
||||
// of its metadata flag. Retain its reported values without precision claims.
|
||||
metadata: reportedMetadata.optional(),
|
||||
functions: z
|
||||
.array(
|
||||
z.strictObject({
|
||||
selector: z.string().regex(/^[a-f0-9]{8}$/),
|
||||
bytecodeOffset: offset,
|
||||
dispatch: z.enum(["abi", "fallback"]),
|
||||
arguments: z.string().optional(),
|
||||
stateMutability: z.string().optional(),
|
||||
}),
|
||||
)
|
||||
.optional(),
|
||||
});
|
||||
|
||||
/** Preserve inference strings and unknown absence; selectors use the conventional 0x display prefix. */
|
||||
export const projectEvmoleInterface = (raw: unknown) => {
|
||||
const producer = evmoleInterfaceReplySchema.parse(raw);
|
||||
return {
|
||||
raw: producer,
|
||||
functions: (producer.functions ?? []).map((fn) => ({
|
||||
selector: `0x${fn.selector}`,
|
||||
bytecode_offset: fn.bytecodeOffset,
|
||||
dispatch: fn.dispatch,
|
||||
inferred_arguments: fn.arguments ?? null,
|
||||
inferred_state_mutability: fn.stateMutability ?? null,
|
||||
})),
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,401 @@
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
import { access, readFile, stat, writeFile } from "node:fs/promises";
|
||||
import { constants } from "node:fs";
|
||||
import { isAbsolute, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
createAnalysisExecution,
|
||||
type AnalysisExecution,
|
||||
type ExecutionOptions,
|
||||
} from "../application/AnalysisProvider.js";
|
||||
import type { EvmInterfacePort } from "../application/evm/EvmInterfacePort.js";
|
||||
import { readStableArtifact } from "../artifacts/readStableArtifact.js";
|
||||
import { OwnedCommandFailure } from "../process/OwnedCommand.js";
|
||||
import type {
|
||||
AnalysisError,
|
||||
AnalysisCapturedOutput,
|
||||
} from "../domain/analysisErrorBase.js";
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
AnalysisCapabilityUnavailableError,
|
||||
AnalysisUnsupportedTargetError,
|
||||
AnalysisInputError,
|
||||
AnalysisOutputError,
|
||||
} from "../domain/analysisErrorCore.js";
|
||||
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
|
||||
import type { InspectEvmInterfaceInput } from "../domain/evm/evmInterface.js";
|
||||
import { evmInterfaceSchema } from "../domain/evm/evmInterface.js";
|
||||
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
|
||||
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import { runOwnedCommand } from "../process/OwnedCommand.js";
|
||||
import { PrivateRuntimeRoot } from "../process/PrivateRuntimeRoot.js";
|
||||
import {
|
||||
evmInterfaceFailure,
|
||||
capturedEvmOutput,
|
||||
type EvmFileSizeFailureEvidence,
|
||||
} from "./EvmoleFailures.js";
|
||||
import {
|
||||
evmoleInterfaceReplySchema,
|
||||
projectEvmoleInterface,
|
||||
} from "./EvmoleInterfaceAdapter.js";
|
||||
import {
|
||||
EVMOLE_PROVIDER_IDENTITY,
|
||||
EVM_INTERFACE_LIMITS,
|
||||
EVM_FILE_SIZE_FAILURE_EXIT,
|
||||
} from "./EvmoleRelease.js";
|
||||
import { decodeEvmBytecodeCarrier } from "./EvmBytecodeCarrier.js";
|
||||
import {
|
||||
selectEvmWorkerLimits,
|
||||
type EvmWorkerLimits,
|
||||
} from "./EvmWorkerLimits.js";
|
||||
|
||||
const OPERATION = "inspect_evm_interface";
|
||||
const replySchema = z.discriminatedUnion("ok", [
|
||||
z.strictObject({
|
||||
ok: z.literal(true),
|
||||
version: z.literal("0.9.3"),
|
||||
bytecode: z.strictObject({
|
||||
sha256: z.string().regex(/^[a-f0-9]{64}$/),
|
||||
bytes: z.number().int().nonnegative(),
|
||||
hex: z.string().regex(/^(?:[a-f0-9]{2})*$/),
|
||||
}),
|
||||
raw: evmoleInterfaceReplySchema,
|
||||
}),
|
||||
z.strictObject({
|
||||
ok: z.literal(false),
|
||||
reason: z.enum(["format", "decoder", "output-limit", "unsupported"]),
|
||||
message: z.string(),
|
||||
}),
|
||||
]);
|
||||
type Launcher = NonNullable<Parameters<typeof runOwnedCommand>[2]>["launcher"];
|
||||
|
||||
/** Run unchanged EVMole/WASM in an owned worker; no target, chain or network execution. */
|
||||
export class EvmoleInterfaceProvider implements EvmInterfacePort {
|
||||
constructor(
|
||||
readonly environment: Readonly<NodeJS.ProcessEnv> = process.env,
|
||||
readonly launcher?: Launcher,
|
||||
readonly createRuntime: () => Promise<
|
||||
Pick<PrivateRuntimeRoot, "path" | "close">
|
||||
> = () => PrivateRuntimeRoot.create({ prefix: "rea-evm-interface-" }),
|
||||
) {}
|
||||
|
||||
/** Bind recovered interface candidates to both original carrier and decoded byte identity. */
|
||||
async inspect(
|
||||
input: InspectEvmInterfaceInput,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<AnalysisExecution, AnalysisError>> {
|
||||
let root: Pick<PrivateRuntimeRoot, "path" | "close"> | undefined;
|
||||
let retainedOutput: AnalysisCapturedOutput | undefined;
|
||||
let phase: "configuration" | "artifact-read" | "worker" = "configuration";
|
||||
let workerLimits: EvmWorkerLimits | undefined;
|
||||
const limiter =
|
||||
this.environment.REA_EVM_PRLIMIT_COMMAND ?? "/usr/bin/prlimit";
|
||||
let result: Result<AnalysisExecution, AnalysisError>;
|
||||
try {
|
||||
if (options?.signal?.aborted) throw new AnalysisCancelledError(OPERATION);
|
||||
if (process.platform !== "linux" || process.arch !== "x64")
|
||||
throw new AnalysisCapabilityUnavailableError(
|
||||
EVMOLE_PROVIDER_IDENTITY.id,
|
||||
OPERATION,
|
||||
"Initial real-verified offline EVM interface profile supports Linux x64 only.",
|
||||
);
|
||||
try {
|
||||
if (!isAbsolute(limiter))
|
||||
throw new Error(
|
||||
"REA_EVM_PRLIMIT_COMMAND must be an absolute executable path.",
|
||||
);
|
||||
await access(limiter, constants.X_OK);
|
||||
if (!(await stat(limiter)).isFile())
|
||||
throw new Error(
|
||||
"Configured prlimit must be a regular executable file, not a directory.",
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
const reason = `Offline EVM interface inspection requires caller-supplied util-linux prlimit: ${limiter}; ${cause instanceof Error ? cause.message : String(cause)}`;
|
||||
throw new AnalysisCapabilityUnavailableError(
|
||||
EVMOLE_PROVIDER_IDENTITY.id,
|
||||
OPERATION,
|
||||
reason,
|
||||
{ cause, userMessage: reason },
|
||||
);
|
||||
}
|
||||
let inheritedLimits: string;
|
||||
try {
|
||||
inheritedLimits = await readFile("/proc/self/limits", "utf8");
|
||||
} catch (cause: unknown) {
|
||||
const reason = `Could not read inherited Linux resource limits at /proc/self/limits: ${cause instanceof Error ? cause.message : String(cause)}`;
|
||||
throw new AnalysisCapabilityUnavailableError(
|
||||
EVMOLE_PROVIDER_IDENTITY.id,
|
||||
OPERATION,
|
||||
reason,
|
||||
{ cause, userMessage: reason },
|
||||
);
|
||||
}
|
||||
const limits = selectEvmWorkerLimits(inheritedLimits);
|
||||
if (!limits.ok)
|
||||
throw new AnalysisCapabilityUnavailableError(
|
||||
EVMOLE_PROVIDER_IDENTITY.id,
|
||||
OPERATION,
|
||||
limits.error,
|
||||
{ userMessage: limits.error },
|
||||
);
|
||||
workerLimits = limits.value;
|
||||
phase = "artifact-read";
|
||||
const carrier = await readStableArtifact(
|
||||
input.path,
|
||||
EVM_INTERFACE_LIMITS.inputBytes,
|
||||
options?.signal,
|
||||
);
|
||||
phase = "worker";
|
||||
root = await this.createRuntime();
|
||||
const snapshotPath = join(root.path, "carrier.snapshot");
|
||||
const requestPath = join(root.path, "request.json");
|
||||
const replyPath = join(root.path, "reply.json");
|
||||
await writeFile(snapshotPath, carrier.bytes, {
|
||||
flag: "wx",
|
||||
mode: 0o600,
|
||||
...(options?.signal === undefined ? {} : { signal: options.signal }),
|
||||
});
|
||||
await writeFile(
|
||||
requestPath,
|
||||
JSON.stringify({
|
||||
snapshot_path: snapshotPath,
|
||||
reply_path: replyPath,
|
||||
failure_marker_path: join(root.path, "resource.failure"),
|
||||
encoding: input.encoding,
|
||||
}),
|
||||
{ flag: "wx", mode: 0o600 },
|
||||
);
|
||||
const { NODE_OPTIONS: _ambientNodeOptions, ...environment } =
|
||||
this.environment;
|
||||
const execution = await runOwnedCommand(
|
||||
{
|
||||
command: limiter,
|
||||
arguments: [
|
||||
`--as=${String(workerLimits.addressSpaceBytes)}:`,
|
||||
`--fsize=${String(workerLimits.fileSizeBytes)}:`,
|
||||
"--core=0:",
|
||||
`--cpu=${String(workerLimits.cpuSeconds)}:`,
|
||||
"--",
|
||||
process.execPath,
|
||||
"--max-old-space-size=256",
|
||||
"--v8-pool-size=1",
|
||||
"--disable-wasm-trap-handler",
|
||||
fileURLToPath(
|
||||
new URL("./EvmoleInterfaceWorker.js", import.meta.url),
|
||||
),
|
||||
requestPath,
|
||||
],
|
||||
cwd: root.path,
|
||||
expectedCommand: null,
|
||||
runId: `rea-evm-interface-${randomUUID()}`,
|
||||
hostEnvironment: environment,
|
||||
},
|
||||
{
|
||||
timeoutMs: EVM_INTERFACE_LIMITS.timeoutMs,
|
||||
diagnosticBytes: EVM_INTERFACE_LIMITS.diagnosticBytes,
|
||||
},
|
||||
{
|
||||
...(options?.signal === undefined ? {} : { signal: options.signal }),
|
||||
...(this.launcher === undefined ? {} : { launcher: this.launcher }),
|
||||
},
|
||||
);
|
||||
const capturedOutput = capturedEvmOutput(execution);
|
||||
retainedOutput = capturedOutput;
|
||||
let reply: z.output<typeof replySchema>;
|
||||
try {
|
||||
const file = await readStableArtifact(
|
||||
replyPath,
|
||||
EVM_INTERFACE_LIMITS.outputBytes,
|
||||
options?.signal,
|
||||
);
|
||||
reply = replySchema.parse(JSON.parse(file.bytes.toString("utf8")));
|
||||
} catch (cause: unknown) {
|
||||
if (options?.signal?.aborted)
|
||||
throw new AnalysisCancelledError(OPERATION, { capturedOutput });
|
||||
throw new AnalysisOutputError(
|
||||
OPERATION,
|
||||
`Owned interface worker reply failed for ${input.path}: ${cause instanceof Error ? cause.message : String(cause)}`,
|
||||
{ cause, capturedOutput },
|
||||
);
|
||||
}
|
||||
if (!reply.ok) {
|
||||
if (reply.reason === "unsupported")
|
||||
throw new AnalysisUnsupportedTargetError(
|
||||
OPERATION,
|
||||
input.path,
|
||||
reply.message,
|
||||
{ capturedOutput },
|
||||
);
|
||||
if (reply.reason === "format")
|
||||
throw new AnalysisInputError(OPERATION, { capturedOutput }, [
|
||||
{
|
||||
path: ["path"],
|
||||
reason: "invalid_format",
|
||||
message: reply.message,
|
||||
},
|
||||
]);
|
||||
if (reply.reason === "output-limit")
|
||||
throw new AnalysisOutputError(OPERATION, reply.message, {
|
||||
capturedOutput,
|
||||
});
|
||||
throw new ProviderAdapterError(EVMOLE_PROVIDER_IDENTITY.id, OPERATION, {
|
||||
diagnostics: {
|
||||
phase,
|
||||
failure_kind: reply.reason,
|
||||
reason: reply.message,
|
||||
stdout: execution.stdout.text,
|
||||
stderr: execution.stderr.text,
|
||||
captured_output: { ...capturedOutput },
|
||||
},
|
||||
});
|
||||
}
|
||||
const selectedBytes = decodeEvmBytecodeCarrier(
|
||||
carrier.bytes,
|
||||
input.encoding,
|
||||
);
|
||||
const selectedHex = Buffer.from(selectedBytes).toString("hex");
|
||||
const decodedHash = createHash("sha256")
|
||||
.update(selectedBytes)
|
||||
.digest("hex");
|
||||
if (
|
||||
decodedHash !== reply.bytecode.sha256 ||
|
||||
selectedHex !== reply.bytecode.hex ||
|
||||
selectedBytes.length !== reply.bytecode.bytes
|
||||
)
|
||||
throw new AnalysisOutputError(
|
||||
OPERATION,
|
||||
"Decoded bytecode representation does not match the selected carrier, encoding or reported SHA-256.",
|
||||
{ capturedOutput },
|
||||
);
|
||||
const limitations = [
|
||||
`Configured worker resource soft limits: address_space_bytes=${String(workerLimits.addressSpaceBytes)}, cpu_seconds=${String(workerLimits.cpuSeconds)}, file_size_bytes=${String(workerLimits.fileSizeBytes)}. Selected from inherited tighter limits; original hard limits are retained. Effective worker limits are not independently probed.`,
|
||||
"Upstream may also report terminal metadata while recovering selectors. Its reported values are retained in raw_result, but integer precision and non-text-key coverage are unknown in the JS binding; complete original bytecode remains available.",
|
||||
"Recovered selectors, argument strings and mutability are upstream inferences, not verified ABI signatures or names. Empty results do not prove the absence of callable dispatch.",
|
||||
"Bytecode kind, hardfork and deployed-contract authenticity are unknown. This inspection performs no target runtime execution, chain/RPC lookup or network request.",
|
||||
"Original carrier and decoded bytecode SHA-256 are distinct identities; SHA-256 is not the Ethereum Keccak code hash.",
|
||||
"The owned worker has a 256 MiB JavaScript heap, 3 GiB virtual address-space limit and 30-second deadline. Virtual address space is distinct from resident memory; limits fail without partial success.",
|
||||
];
|
||||
const validated = evmInterfaceSchema.safeParse({
|
||||
artifact: {
|
||||
path: input.path,
|
||||
sha256: carrier.sha256,
|
||||
bytes: carrier.bytes.length,
|
||||
encoding: input.encoding,
|
||||
},
|
||||
bytecode: {
|
||||
...reply.bytecode,
|
||||
digest_algorithm: "sha256",
|
||||
kind: "unknown",
|
||||
deployment_authenticity: "unknown",
|
||||
hardfork: "unknown",
|
||||
},
|
||||
evidence_kind: "inferred",
|
||||
functions: projectEvmoleInterface(reply.raw).functions,
|
||||
discovery_completeness: "unknown",
|
||||
runtime_execution: "not-performed",
|
||||
diagnostics: {
|
||||
stdout: execution.stdout.text,
|
||||
stderr: execution.stderr.text,
|
||||
truncated: capturedOutput.truncated,
|
||||
},
|
||||
limitations,
|
||||
});
|
||||
if (!validated.success)
|
||||
throw new AnalysisOutputError(
|
||||
OPERATION,
|
||||
`Interface worker returned invalid bytecode-relative evidence: ${validated.error.issues[0]?.message ?? "schema mismatch"}`,
|
||||
{ capturedOutput },
|
||||
);
|
||||
const report = validated.data;
|
||||
result = ok(
|
||||
createAnalysisExecution(report, EVMOLE_PROVIDER_IDENTITY, {
|
||||
rawResult: reply.raw,
|
||||
subject: { path: input.path, format: "file", sha256: carrier.sha256 },
|
||||
locations: [{ kind: "artifact-path", path: input.path }],
|
||||
limitations,
|
||||
}),
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
let fileFailure: EvmFileSizeFailureEvidence | undefined;
|
||||
if (
|
||||
cause instanceof OwnedCommandFailure &&
|
||||
cause.snapshot?.exitCode === EVM_FILE_SIZE_FAILURE_EXIT &&
|
||||
cause.snapshot.signal === null &&
|
||||
root !== undefined
|
||||
) {
|
||||
try {
|
||||
const marker = await readStableArtifact(
|
||||
join(root.path, "resource.failure"),
|
||||
1,
|
||||
);
|
||||
if (!marker.bytes.equals(Buffer.from("F")))
|
||||
throw new Error(
|
||||
"Private worker failure marker does not match the observed exit status.",
|
||||
);
|
||||
fileFailure = { verified: true, failure: null };
|
||||
} catch (markerFailure: unknown) {
|
||||
fileFailure = {
|
||||
verified: false,
|
||||
failure:
|
||||
markerFailure instanceof Error
|
||||
? markerFailure.message
|
||||
: String(markerFailure),
|
||||
};
|
||||
}
|
||||
}
|
||||
result = err(
|
||||
options?.signal?.aborted &&
|
||||
(cause === options.signal.reason ||
|
||||
(cause instanceof Error && cause.name === "AbortError"))
|
||||
? new AnalysisCancelledError(
|
||||
OPERATION,
|
||||
retainedOutput === undefined
|
||||
? undefined
|
||||
: { capturedOutput: retainedOutput },
|
||||
)
|
||||
: evmInterfaceFailure(
|
||||
cause,
|
||||
phase,
|
||||
input.path,
|
||||
workerLimits,
|
||||
limiter,
|
||||
fileFailure,
|
||||
),
|
||||
);
|
||||
}
|
||||
if (root !== undefined) {
|
||||
try {
|
||||
await root.close();
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
new ProviderCleanupError(
|
||||
EVMOLE_PROVIDER_IDENTITY.id,
|
||||
[root.path],
|
||||
{
|
||||
reason: cause instanceof Error ? cause.message : String(cause),
|
||||
previous_error: result.ok
|
||||
? null
|
||||
: projectAnalysisError(result.error),
|
||||
...(retainedOutput === undefined
|
||||
? {}
|
||||
: { captured_output: { ...retainedOutput } }),
|
||||
},
|
||||
{ operation: OPERATION },
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
return result.ok && options?.signal?.aborted
|
||||
? err(
|
||||
new AnalysisCancelledError(
|
||||
OPERATION,
|
||||
retainedOutput === undefined
|
||||
? undefined
|
||||
: { capturedOutput: retainedOutput },
|
||||
),
|
||||
)
|
||||
: result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
decodeEvmBytecodeCarrier,
|
||||
EvmCarrierFailure,
|
||||
} from "./EvmBytecodeCarrier.js";
|
||||
import { projectEvmoleInterface } from "./EvmoleInterfaceAdapter.js";
|
||||
import {
|
||||
EVM_INTERFACE_LIMITS,
|
||||
EVM_FILE_SIZE_FAILURE_EXIT,
|
||||
} from "./EvmoleRelease.js";
|
||||
|
||||
const requestSchema = z.strictObject({
|
||||
snapshot_path: z.string(),
|
||||
reply_path: z.string(),
|
||||
failure_marker_path: z.string(),
|
||||
encoding: z.enum(["raw", "hex"]),
|
||||
});
|
||||
class UnsupportedContainer extends Error {}
|
||||
|
||||
const main = async (): Promise<void> => {
|
||||
const requestPath = process.argv[2];
|
||||
if (requestPath === undefined)
|
||||
throw new Error("Owned worker request path missing.");
|
||||
const request = requestSchema.parse(
|
||||
JSON.parse(await readFile(requestPath, "utf8")),
|
||||
);
|
||||
let reply: unknown;
|
||||
try {
|
||||
const bytes = decodeEvmBytecodeCarrier(
|
||||
await readFile(request.snapshot_path),
|
||||
request.encoding,
|
||||
);
|
||||
if (bytes[0] === 0xef && bytes[1] === 0x00)
|
||||
throw new UnsupportedContainer(
|
||||
"Container marker EF00 is outside the verified flat-bytecode interface profile.",
|
||||
);
|
||||
const modulePath = import.meta.resolve("evmole/no_tla");
|
||||
const metadata = z
|
||||
.object({ version: z.literal("0.9.3") })
|
||||
.parse(
|
||||
JSON.parse(
|
||||
await readFile(new URL("../package.json", modulePath), "utf8"),
|
||||
),
|
||||
);
|
||||
const engine = await import("evmole/no_tla");
|
||||
engine.initSync({
|
||||
module: await readFile(
|
||||
new URL(import.meta.resolve("evmole/evmole_bg.wasm")),
|
||||
),
|
||||
});
|
||||
const inferred = projectEvmoleInterface(
|
||||
engine.contractInfo(Buffer.from(bytes).toString("hex"), {
|
||||
selectors: true,
|
||||
arguments: true,
|
||||
stateMutability: true,
|
||||
}),
|
||||
);
|
||||
reply = {
|
||||
ok: true,
|
||||
version: metadata.version,
|
||||
bytecode: {
|
||||
sha256: createHash("sha256").update(bytes).digest("hex"),
|
||||
bytes: bytes.length,
|
||||
hex: Buffer.from(bytes).toString("hex"),
|
||||
},
|
||||
raw: inferred.raw,
|
||||
};
|
||||
} catch (cause: unknown) {
|
||||
reply = {
|
||||
ok: false,
|
||||
reason:
|
||||
cause instanceof EvmCarrierFailure
|
||||
? "format"
|
||||
: cause instanceof UnsupportedContainer
|
||||
? "unsupported"
|
||||
: "decoder",
|
||||
message: cause instanceof Error ? cause.message : String(cause),
|
||||
};
|
||||
}
|
||||
let encoded = JSON.stringify(reply);
|
||||
if (Buffer.byteLength(encoded) > EVM_INTERFACE_LIMITS.outputBytes)
|
||||
encoded = JSON.stringify({
|
||||
ok: false,
|
||||
reason: "output-limit",
|
||||
message: "Complete interface evidence exceeds the 16 MiB reply budget.",
|
||||
});
|
||||
try {
|
||||
await writeFile(request.reply_path, encoded, { flag: "wx", mode: 0o600 });
|
||||
} catch (cause: unknown) {
|
||||
if (cause instanceof Error && "code" in cause && cause.code === "EFBIG") {
|
||||
try {
|
||||
await writeFile(request.failure_marker_path, "F", {
|
||||
flag: "wx",
|
||||
mode: 0o600,
|
||||
});
|
||||
} catch (markerFailure: unknown) {
|
||||
process.stderr.write(
|
||||
`File-size failure marker unavailable: ${markerFailure instanceof Error ? markerFailure.message : String(markerFailure)}\n`,
|
||||
);
|
||||
}
|
||||
process.exitCode = EVM_FILE_SIZE_FAILURE_EXIT;
|
||||
} else throw cause;
|
||||
}
|
||||
};
|
||||
|
||||
await main();
|
||||
@@ -0,0 +1,16 @@
|
||||
/** Unchanged locked npm/WASM profile; provenance is independent of chain deployment authenticity. */
|
||||
export const EVMOLE_PROVIDER_IDENTITY = {
|
||||
id: "evmole-interface",
|
||||
name: "REA EVM interface adapter",
|
||||
version: "evmole@0.9.3",
|
||||
} as const;
|
||||
/** Worker-reserved status for an observed EFBIG write without a complete reply. */
|
||||
export const EVM_FILE_SIZE_FAILURE_EXIT = 76;
|
||||
/** Complete offline inspection budgets; worker JavaScript heap is bounded separately. */
|
||||
export const EVM_INTERFACE_LIMITS = {
|
||||
inputBytes: 4 * 1024 * 1024,
|
||||
outputBytes: 16 * 1024 * 1024,
|
||||
timeoutMs: 30_000,
|
||||
diagnosticBytes: 1024 * 1024,
|
||||
addressSpaceBytes: 3 * 1024 * 1024 * 1024,
|
||||
} as const;
|
||||
Reference in New Issue
Block a user