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:
Ysopwnable
2026-10-08 15:32:05 +08:00
committed by GitHub
parent c5d165bd03
commit 7af7bc88ce
62 changed files with 3250 additions and 63 deletions
+9
View File
@@ -31,6 +31,7 @@ type ToolAvailabilityReason = "available" | ToolUnavailabilityReason;
type ProviderDescriptor = ProviderCapability;
export type AvailabilityPolicy = {
readonly evmInterfaceEnabled?: boolean;
readonly processCaptureEnabled: boolean;
readonly optionalProviderLoadFailures?: OptionalProviderLoadFailures;
readonly binaryLayoutEnabled?: boolean;
@@ -289,6 +290,14 @@ const workflowAvailabilityFor = ({
remediation:
"On Linux x64, set absolute REA_PWNTOOLS_PYTHON to caller-supplied Python with pwntools 4.15.0. No active binary target is required.",
};
if (name === "inspect_evm_interface")
return policy.evmInterfaceEnabled === true
? { reason: "available", remediation: null }
: {
reason: "provider_missing",
remediation:
"The bundled offline EVM interface profile is currently real-verified on Linux x64. No active binary target or chain endpoint is required.",
};
if (kind === "firmware-provider") {
const enabled =
name === "inspect_firmware_regions"
+15
View File
@@ -0,0 +1,15 @@
import type {
AnalysisExecution,
ExecutionOptions,
} from "../AnalysisProvider.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import type { InspectEvmInterfaceInput } from "../../domain/evm/evmInterface.js";
import type { Result } from "../../domain/result.js";
/** Replaceable offline interface-recovery engine, independent of wallets and chain clients. */
export interface EvmInterfacePort {
inspect(
input: InspectEvmInterfaceInput,
options?: ExecutionOptions,
): Promise<Result<AnalysisExecution, AnalysisError>>;
}
@@ -0,0 +1,124 @@
import { expect, it } from "vitest";
import { EvmInterfaceService } from "./EvmInterfaceService.js";
import {
evmInterfaceExecution,
evmInterfaceFixture,
} from "../../../tests/fixtures/evm/interface.js";
import { err, ok } from "../../domain/result.js";
import { parseEvidence } from "../../domain/evidence.js";
import { AnalysisCapabilityUnavailableError } from "../../domain/analysisErrorCore.js";
it("returns full inline inferred Evidence and unmodified upstream representation", async () => {
const value = evmInterfaceFixture();
const service = new EvmInterfaceService({
inspect: () => Promise.resolve(ok(evmInterfaceExecution(value))),
});
const result = await service.inspect({
path: value.artifact.path,
encoding: "hex",
});
if (!result.ok) throw result.error;
const evidence = parseEvidence(result.value);
expect(evidence.normalized_result).toEqual(value);
expect(evidence.raw_result).toEqual({ functions: [] });
expect(evidence.confidence).toBe("inferred");
expect(evidence.subject?.digest.sha256).toBe(value.artifact.sha256);
});
it.each([
{ path: "relative.hex", encoding: "hex" },
{ path: "/selected", encoding: "auto" },
{ path: "/selected" },
{ path: "/selected", encoding: "raw", approval: true },
])("rejects invalid selection before effects: %j", async (input) => {
const service = new EvmInterfaceService({
inspect: () => {
throw new Error("must not start");
},
});
expect(await service.inspect(input)).toMatchObject({
ok: false,
error: { _tag: "AnalysisInputError" },
});
});
it.each(["carrier", "encoding", "digest", "no-subject"])(
"rejects mismatched producer binding: %s",
async (problem) => {
const value = evmInterfaceFixture();
if (problem === "carrier") value.artifact.path = "/other";
if (problem === "encoding") value.artifact.encoding = "raw";
const observed = evmInterfaceExecution(value);
const execution = {
...observed,
subject:
problem === "no-subject"
? null
: {
path: "/artifacts/source-owned.hex",
sha256:
problem === "digest" ? "b".repeat(64) : value.artifact.sha256,
format: "file" as const,
},
};
const service = new EvmInterfaceService({
inspect: () => Promise.resolve(ok(execution)),
});
expect(
await service.inspect({
path: "/artifacts/source-owned.hex",
encoding: "hex",
}),
).toMatchObject({
ok: false,
error: { _tag: "AnalysisOutputError", capturedOutput: value.diagnostics },
});
},
);
it("preserves meaningful provider failure and cancellation before/after execution", async () => {
const failure = new AnalysisCapabilityUnavailableError(
"evm",
"inspect_evm_interface",
"Selected limiter missing",
);
const service = new EvmInterfaceService({
inspect: () => Promise.resolve(err(failure)),
});
expect(await service.inspect({ path: "/code", encoding: "raw" })).toEqual(
err(failure),
);
const controller = new AbortController();
const observed = evmInterfaceFixture();
observed.diagnostics = {
stdout: "selected\u0000",
stderr: "warning",
truncated: true,
};
const cancelled = new EvmInterfaceService({
inspect: () => {
controller.abort();
return Promise.resolve(ok(evmInterfaceExecution(observed)));
},
});
expect(
await cancelled.inspect(
{ path: "/artifacts/source-owned.hex", encoding: "hex" },
{ signal: controller.signal },
),
).toMatchObject({
ok: false,
error: {
_tag: "AnalysisCancelledError",
capturedOutput: observed.diagnostics,
},
});
const untouched = new EvmInterfaceService({
inspect: () => {
throw new Error("must not start");
},
});
expect(
await untouched.inspect(
{ path: "/code", encoding: "raw" },
{ signal: controller.signal },
),
).toMatchObject({ ok: false, error: { _tag: "AnalysisCancelledError" } });
});
@@ -0,0 +1,92 @@
import { isAbsolute } from "node:path";
import { z } from "zod";
import type { ExecutionOptions } from "../AnalysisProvider.js";
import type { EvmInterfacePort } from "./EvmInterfacePort.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import {
AnalysisCancelledError,
AnalysisInputError,
AnalysisOutputError,
} from "../../domain/analysisErrorCore.js";
import { createEvidence, type Evidence } from "../../domain/evidence.js";
import {
inspectEvmInterfaceInputSchema,
evmInterfaceSchema,
} from "../../domain/evm/evmInterface.js";
import { projectInputIssues } from "../../domain/inputIssueProjection.js";
import { err, ok, type Result } from "../../domain/result.js";
const OPERATION = "inspect_evm_interface";
const diagnosticsSchema = z.object({
diagnostics: evmInterfaceSchema.shape.diagnostics,
});
/** Shared carrier validation and typed inline Evidence for CLI/MCP. */
export class EvmInterfaceService {
constructor(readonly provider: EvmInterfacePort) {}
/** Preserve selected byte identity while clearly labeling recovered ABI candidates as inferences. */
async inspect(
rawInput: unknown,
options?: ExecutionOptions,
): Promise<Result<Evidence, AnalysisError>> {
if (options?.signal?.aborted)
return err(new AnalysisCancelledError(OPERATION));
const input = inspectEvmInterfaceInputSchema.safeParse(rawInput);
if (!input.success)
return err(
new AnalysisInputError(
OPERATION,
{ cause: input.error },
projectInputIssues(input.error.issues, rawInput),
),
);
if (!isAbsolute(input.data.path))
return err(
new AnalysisInputError(OPERATION, undefined, [
{
path: ["path"],
reason: "invalid_format",
message: "Expected an absolute filesystem path on this host.",
},
]),
);
const inspected = await this.provider.inspect(input.data, options);
if (!inspected.ok) return inspected;
const diagnostics = diagnosticsSchema.safeParse(inspected.value.result);
const outputOptions = diagnostics.success
? { capturedOutput: diagnostics.data.diagnostics }
: undefined;
if (options?.signal?.aborted)
return err(new AnalysisCancelledError(OPERATION, outputOptions));
const execution = inspected.value;
const report = evmInterfaceSchema.safeParse(execution.result);
if (
!report.success ||
report.data.artifact.path !== input.data.path ||
report.data.artifact.encoding !== input.data.encoding ||
execution.subject?.path !== input.data.path ||
execution.subject.sha256 !== report.data.artifact.sha256
)
return err(
new AnalysisOutputError(
OPERATION,
"Interface adapter returned malformed data or changed the selected carrier identity/encoding.",
outputOptions,
),
);
return ok(
createEvidence(execution.subject, execution.provider, {
operation: OPERATION,
parameters: input.data,
result: report.data,
...(execution.rawResult === null
? {}
: { rawResult: execution.rawResult }),
confidence: "inferred",
locations: execution.locations,
limitations: execution.limitations,
}),
);
}
}
+2
View File
@@ -1,3 +1,4 @@
import { registerEvmCommands } from "./cli/evmCommands.js";
import { registerBinaryDiagnosticsCommands } from "./cli/binaryDiagnosticsCommands.js";
import { Cli } from "incur";
@@ -56,6 +57,7 @@ export const createCli = (
registerSetupCommands(cli, logger);
registerCoreAnalysisCommands(cli, logger, resultOutput);
registerUtilityCommands(cli, logger, environment);
registerEvmCommands(cli, logger, environment);
registerArtifactCommands(cli, logger);
registerManagedCommands(cli, logger);
registerAndroidCommands(cli, logger, environment);
+37
View File
@@ -0,0 +1,37 @@
import { z } from "incur";
import { resolve } from "node:path";
import { createEvmInterfaceService } from "../composition/evm.js";
import { CLI_COMMANDS } from "../cliCommandNames.js";
import { logCliCommand } from "../cliLogging.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import type { Logger } from "../logger.js";
import type { CliInstance } from "./types.js";
import { withCommandCancellation } from "./commandCancellation.js";
/** Resolve operator paths and preserve explicit encoding through the shared workflow. */
export const registerEvmCommands = (
cli: CliInstance,
logger: Logger,
environment: Readonly<NodeJS.ProcessEnv>,
): void => {
const service = createEvmInterfaceService(environment);
cli.command(CLI_COMMANDS.inspectEvmInterface, {
description: "Infer interface candidates from explicit local EVM bytecode",
args: z.object({
path: z.string().describe("Local bytecode carrier"),
encoding: z
.enum(["raw", "hex"])
.describe("Selected carrier representation"),
}),
run: ({ args }) =>
withCommandCancellation((signal) =>
logCliCommand(logger, CLI_COMMANDS.inspectEvmInterface, async () => {
const result = await service.inspect(
{ path: resolve(args.path), encoding: args.encoding },
{ signal },
);
return result.ok ? result.value : projectAnalysisError(result.error);
}),
),
});
};
+1
View File
@@ -1,5 +1,6 @@
/** Canonical names used by every one-shot CLI command registration. */
export const CLI_COMMANDS = Object.freeze({
inspectEvmInterface: "inspect-evm-interface",
inspectWebNetworkCapture: "inspect-web-network-capture",
observeWebExecution: "observe-web-execution",
inspectWebEventListeners: "inspect-web-event-listeners",
+8
View File
@@ -0,0 +1,8 @@
import { EvmInterfaceService } from "../application/evm/EvmInterfaceService.js";
import { EvmoleInterfaceProvider } from "../evm/EvmoleInterfaceProvider.js";
/** Compose offline interface analysis without import-time I/O or dependency acquisition. */
export const createEvmInterfaceService = (
environment: Readonly<NodeJS.ProcessEnv> = process.env,
): EvmInterfaceService =>
new EvmInterfaceService(new EvmoleInterfaceProvider(environment));
+2
View File
@@ -1,3 +1,4 @@
import { EVM_TOOL_CONTRACTS } from "./evm/evmToolContracts.js";
import { BINARY_DIAGNOSTICS_TOOL_CONTRACTS } from "./native/binaryDiagnosticsToolContracts.js";
import { describe, expect, it } from "vitest";
import { z } from "zod";
@@ -72,6 +73,7 @@ describe("tool contract surface", () => {
...NATIVE_TOOL_CONTRACTS,
...BINARY_DIAGNOSTICS_TOOL_CONTRACTS,
...ARTIFACT_TOOL_CONTRACTS,
...EVM_TOOL_CONTRACTS,
...ANDROID_TOOL_CONTRACTS,
...FIRMWARE_TOOL_CONTRACTS,
...MANAGED_TOOL_CONTRACTS,
+2
View File
@@ -5,6 +5,7 @@ import { jsonValueSchema } from "../domain/jsonValue.js";
const categorySchema = z.enum([
"invalid_input",
"unsupported_provider",
"unsupported_target",
"integrity_mismatch",
"truncated",
"cancelled",
@@ -37,6 +38,7 @@ export const analysisErrorProjectionSchema = z.discriminatedUnion("code", [
generic("artifact_changed"),
generic("unreadable_output"),
generic("capability_unavailable"),
generic("unsupported_target"),
generic("provider_unavailable"),
generic("provider_timeout"),
generic("resource_constraint"),
+26
View File
@@ -0,0 +1,26 @@
import {
inspectEvmInterfaceInputSchema,
evmInterfaceSchema,
} from "../../domain/evm/evmInterface.js";
import type { ToolContract } from "../toolContractTypes.js";
import { toolContractMetadata } from "../toolEffects.js";
import { evidenceResultOf } from "../toolOutputSchemas.js";
/** Target-free EVM capabilities are independent of archive/Apple artifact providers. */
export const EVM_TOOL_CONTRACTS = [
{
name: "inspect_evm_interface",
...toolContractMetadata("inspect_evm_interface"),
kind: "artifact-provider",
description:
"Inspect an explicit local flat EVM bytecode carrier and infer dispatch selectors, argument strings and mutability without executing the target or accessing a chain/RPC endpoint. Choose raw or hex encoding explicitly. Returns original carrier and decoded-byte SHA-256, full bytecode and interface candidates inline as inferred Evidence; bytecode kind, hardfork, deployed authenticity and discovery completeness remain unknown. Initial real-verified Linux x64 profile uses unchanged bundled EVMole 0.9.3/WASM in a bounded owned worker; EOF-style EF00 containers are unsupported. No signature lookup, wallet action or transaction broadcast.",
inputSchema: inspectEvmInterfaceInputSchema,
outputSchema: evidenceResultOf(evmInterfaceSchema),
examples: [
{
title: "Inspect a local runtime bytecode hex carrier",
input: { path: "/artifacts/runtime.hex", encoding: "hex" },
},
],
},
] as const satisfies readonly ToolContract[];
+2
View File
@@ -1,3 +1,4 @@
import { EVM_TOOL_CONTRACTS } from "./evm/evmToolContracts.js";
import { BINARY_DIAGNOSTICS_TOOL_CONTRACTS } from "./native/binaryDiagnosticsToolContracts.js";
import { describe, expect, it } from "vitest";
@@ -26,6 +27,7 @@ const GROUPS = {
native: NATIVE_TOOL_CONTRACTS,
binary_diagnostics: BINARY_DIAGNOSTICS_TOOL_CONTRACTS,
artifact: ARTIFACT_TOOL_CONTRACTS,
evm: EVM_TOOL_CONTRACTS,
managed: MANAGED_TOOL_CONTRACTS,
android: ANDROID_TOOL_CONTRACTS,
firmware: FIRMWARE_TOOL_CONTRACTS,
+2
View File
@@ -1,3 +1,4 @@
import { EVM_TOOL_CONTRACTS } from "./evm/evmToolContracts.js";
import { BINARY_DIAGNOSTICS_TOOL_CONTRACTS } from "./native/binaryDiagnosticsToolContracts.js";
import { NATIVE_TOOL_CONTRACTS } from "./native/nativeToolContracts.js";
import { ARTIFACT_TOOL_CONTRACTS } from "./artifactToolContracts.js";
@@ -26,6 +27,7 @@ export const TOOL_CONTRACTS = [
...NATIVE_TOOL_CONTRACTS,
...BINARY_DIAGNOSTICS_TOOL_CONTRACTS,
...ARTIFACT_TOOL_CONTRACTS,
...EVM_TOOL_CONTRACTS,
...MANAGED_TOOL_CONTRACTS,
...ANDROID_TOOL_CONTRACTS,
...FIRMWARE_TOOL_CONTRACTS,
+5
View File
@@ -41,6 +41,11 @@ const sessionEvidence = effects({ mutatesSession: true });
/** Explicit effect audit for every public tool. */
export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
inspect_evm_interface: effects({
mutatesSession: true,
writesFilesystem: true,
launchesProcess: true,
}),
inspect_web_network_capture: effects({
mutatesSession: true,
writesFilesystem: true,
+1
View File
@@ -6,6 +6,7 @@ const ANALYSIS_ERROR_TAGS = [
"AnalysisArtifactChangedError",
"AnalysisOutputError",
"AnalysisCapabilityUnavailableError",
"AnalysisUnsupportedTargetError",
"AnalysisCancelledError",
"AnalysisTimeoutError",
"AnalysisResourceConstraintError",
+13
View File
@@ -4,6 +4,19 @@ import {
type AnalysisErrorOptions,
} from "./analysisErrorBase.js";
/** A readable supplied artifact lies outside this operation's supported target formats. */
export class AnalysisUnsupportedTargetError extends AnalysisError {
readonly _tag = "AnalysisUnsupportedTargetError";
constructor(
readonly operation: string,
readonly path: string,
readonly reason: string,
options?: AnalysisErrorOptions,
) {
super(`Unsupported target for ${operation} at ${path}: ${reason}`, options);
}
}
/** Provider reported a resource failure, distinct from malformed input or unsupported coverage. */
export class AnalysisResourceConstraintError extends AnalysisError {
readonly _tag = "AnalysisResourceConstraintError";
+6
View File
@@ -2,6 +2,7 @@ import {
AnalysisAccessDeniedError,
AnalysisArtifactChangedError,
AnalysisInputError,
AnalysisUnsupportedTargetError,
AnalysisResourceConstraintError,
} from "./analysisErrorCore.js";
import { ArtifactOperationError } from "./artifactOperationError.js";
@@ -33,6 +34,8 @@ import { type AnalysisErrorProjection } from "./analysisErrorProjection.js";
export const analysisErrorRemediationAction = (
error: AnalysisError,
): string => {
if (error instanceof AnalysisUnsupportedTargetError)
return "Select a target supported by this operation or choose an operation supporting the reported target format.";
if (error instanceof AnalysisResourceConstraintError)
return error.resource === "cpu"
? "Review the reported worker CPU limits and observed signal. Retry with sufficient CPU time or a smaller artifact; REA retains tighter inherited limits."
@@ -125,6 +128,7 @@ const STATIC_ERROR_CATEGORIES: Readonly<
AnalysisAccessDeniedError: "unavailable",
AnalysisArtifactChangedError: "integrity_mismatch",
AnalysisCapabilityUnavailableError: "unsupported_provider",
AnalysisUnsupportedTargetError: "unsupported_target",
ProviderSelectionError: "unsupported_provider",
EvidenceIntegrityError: "integrity_mismatch",
AnalysisCancelledError: "cancelled",
@@ -137,6 +141,7 @@ const STATIC_ERROR_CATEGORIES: Readonly<
};
export const analysisErrorUserMessage = (error: AnalysisError): string => {
if (error instanceof AnalysisUnsupportedTargetError) return error.message;
if (error instanceof AnalysisResourceConstraintError) return error.reason;
if (error instanceof AnalysisAccessDeniedError)
return "Host filesystem permissions denied read access to the selected path.";
@@ -270,6 +275,7 @@ const KNOWN_ERROR_TAGS = {
AnalysisArtifactChangedError: true,
AnalysisOutputError: true,
AnalysisCapabilityUnavailableError: true,
AnalysisUnsupportedTargetError: true,
AnalysisCancelledError: true,
AnalysisTimeoutError: true,
AnalysisResourceConstraintError: true,
@@ -1,6 +1,7 @@
import { describe, expect, it } from "vitest";
import {
AnalysisCapabilityUnavailableError,
AnalysisUnsupportedTargetError,
AnalysisInputError,
AnalysisOutputError,
AnalysisCancelledError,
@@ -28,6 +29,32 @@ const retainedOutput = {
truncated: true,
};
it("distinguishes unsupported target formats from unavailable provider capabilities", () => {
const projected = projectAnalysisError(
new AnalysisUnsupportedTargetError(
"inspect_evm_interface",
"/selected/runtime.hex",
"EOF-style EF00 container is unsupported.",
{ capturedOutput: retainedOutput },
),
);
expect(projected).toMatchObject({
code: "unsupported_target",
category: "unsupported_target",
retryable: false,
details: {
operation: "inspect_evm_interface",
path: "/selected/runtime.hex",
reason: "EOF-style EF00 container is unsupported.",
captured_output: retainedOutput,
},
});
expect(projected.message).toContain("EF00");
expect(projected.remediation.action).toContain("target format");
expect(projected.remediation.action).not.toContain("doctor");
expect(analysisErrorProjectionSchema.safeParse(projected).success).toBe(true);
});
it.each([
["memory", null],
["memory", { address_space_bytes: 67108864 }],
+10
View File
@@ -11,6 +11,7 @@ import {
AnalysisArtifactChangedError,
AnalysisCancelledError,
AnalysisCapabilityUnavailableError,
AnalysisUnsupportedTargetError,
AnalysisInputError,
AnalysisOutputError,
AnalysisTimeoutError,
@@ -140,6 +141,7 @@ const STATIC_ERROR_CODES = {
AnalysisAccessDeniedError: "access_denied",
AnalysisArtifactChangedError: "artifact_changed",
AnalysisCapabilityUnavailableError: "capability_unavailable",
AnalysisUnsupportedTargetError: "unsupported_target",
AnalysisCancelledError: "cancelled",
HopperCancelledError: "cancelled",
AnalysisTimeoutError: "provider_timeout",
@@ -187,6 +189,12 @@ const errorDetails = (
const requestErrorDetails = (
error: AnalysisError,
): Readonly<Record<string, JsonValue>> | undefined => {
if (error instanceof AnalysisUnsupportedTargetError)
return {
operation: error.operation,
path: error.path,
reason: error.reason,
};
if (error instanceof AnalysisResourceConstraintError)
return {
operation: error.operation,
@@ -420,6 +428,7 @@ export interface AnalysisErrorProjection extends Readonly<
| "artifact_changed"
| "unreadable_output"
| "capability_unavailable"
| "unsupported_target"
| "provider_unavailable"
| "provider_timeout"
| "resource_constraint"
@@ -437,6 +446,7 @@ export interface AnalysisErrorProjection extends Readonly<
readonly category:
| "invalid_input"
| "unsupported_provider"
| "unsupported_target"
| "integrity_mismatch"
| "truncated"
| "cancelled"
+36
View File
@@ -0,0 +1,36 @@
import { expect, it } from "vitest";
import { evmInterfaceSchema } from "./evmInterface.js";
import { evmInterfaceFixture } from "../../../tests/fixtures/evm/interface.js";
it("preserves original carrier and decoded byte identity as distinct observations", () => {
const fixture = evmInterfaceFixture();
expect(evmInterfaceSchema.parse(fixture)).toEqual(fixture);
expect(fixture.artifact.sha256).not.toBe(fixture.bytecode.sha256);
});
it.each(["byte-count", "body-offset", "selector", "authenticity"])(
"rejects false interface evidence: %s",
(problem) => {
const value = evmInterfaceFixture();
const raw = {
...value,
...(problem === "authenticity"
? {
bytecode: {
...value.bytecode,
deployment_authenticity: "verified",
},
}
: {}),
};
if (problem === "byte-count") raw.bytecode.bytes++;
if (problem === "body-offset" || problem === "selector")
raw.functions.push({
selector: problem === "selector" ? "bad" : "0xaabbccdd",
bytecode_offset: problem === "body-offset" ? 5 : 0,
dispatch: "abi",
inferred_arguments: null,
inferred_state_mutability: null,
});
expect(evmInterfaceSchema.safeParse(raw).success).toBe(false);
},
);
+76
View File
@@ -0,0 +1,76 @@
import { z } from "zod";
const byteOffset = z.number().int().nonnegative();
const sha256 = z.string().regex(/^[a-f0-9]{64}$/);
/** Select the carrier representation explicitly; no RPC or deployed-contract lookup is implied. */
export const inspectEvmInterfaceInputSchema = z.strictObject({
path: z
.string()
.min(1)
.describe("Absolute path to caller-selected local bytecode carrier"),
encoding: z
.enum(["raw", "hex"])
.describe(
"Raw bytes or UTF-8 hex with optional 0x prefix and outer ASCII whitespace",
),
});
/** Recovered interface candidates are inferences, independently of observed byte identity. */
export const evmInterfaceSchema = z
.strictObject({
artifact: z.strictObject({
path: z.string().min(1),
sha256,
bytes: byteOffset,
encoding: z.enum(["raw", "hex"]),
}),
bytecode: z.strictObject({
sha256,
bytes: byteOffset,
hex: z.string().regex(/^(?:[0-9a-f]{2})*$/),
digest_algorithm: z.literal("sha256"),
kind: z.literal("unknown"),
deployment_authenticity: z.literal("unknown"),
hardfork: z.literal("unknown"),
}),
evidence_kind: z.literal("inferred"),
functions: z.array(
z.strictObject({
selector: z.string().regex(/^0x[0-9a-f]{8}$/),
bytecode_offset: byteOffset,
dispatch: z.enum(["abi", "fallback"]),
inferred_arguments: z.string().nullable(),
inferred_state_mutability: z.string().nullable(),
}),
),
discovery_completeness: z.literal("unknown"),
runtime_execution: z.literal("not-performed"),
diagnostics: z.strictObject({
stdout: z.string(),
stderr: z.string(),
truncated: z.boolean(),
}),
limitations: z.array(z.string()),
})
.superRefine((value, context) => {
if (value.bytecode.hex.length !== value.bytecode.bytes * 2)
context.addIssue({
code: "custom",
path: ["bytecode"],
message:
"Selected byte count does not match the bytecode hex representation.",
});
for (const [index, fn] of value.functions.entries())
if (fn.bytecode_offset >= value.bytecode.bytes)
context.addIssue({
code: "custom",
path: ["functions", index, "bytecode_offset"],
message: "Inferred body offset lies outside the selected bytecode.",
});
});
export type InspectEvmInterfaceInput = z.infer<
typeof inspectEvmInterfaceInputSchema
>;
export type EvmInterface = z.infer<typeof evmInterfaceSchema>;
+34
View File
@@ -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(),
);
});
+26
View File
@@ -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"));
};
+55
View File
@@ -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);
});
+58
View File
@@ -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 });
};
+205
View File
@@ -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,
});
+66
View File
@@ -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();
});
+59
View File
@@ -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,
})),
};
};
+401
View File
@@ -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;
}
}
+108
View File
@@ -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();
+16
View File
@@ -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;
+1 -1
View File
@@ -5,5 +5,5 @@ export const PACKAGE_METADATA = {
serverSdkVersion: "2.3.1",
clientSdkVersion: "2.3.1",
coreSdkVersion: "2.3.1",
skillVersion: "31",
skillVersion: "32",
} as const;
+13
View File
@@ -1,3 +1,6 @@
import type { EvmInterfaceService } from "../application/evm/EvmInterfaceService.js";
import { createEvmInterfaceService } from "../composition/evm.js";
import { registerEvmTools } from "./registerEvmTools.js";
import { registerBinaryDiagnosticsTools } from "./registerBinaryDiagnosticsTools.js";
import { createBinaryLayoutService } from "../composition/binaryDiagnostics.js";
import type { BinaryLayoutService } from "../application/binaryDiagnostics/BinaryLayoutService.js";
@@ -62,6 +65,7 @@ const ACTIVE_TARGET_INSTRUCTIONS =
"REA analyzes the active reverse-engineering target. Use the analysis tool that answers the question directly. Search or list symbols when discovery is needed; analyze_function provides a function dossier, and focused procedure tools return individual facets.";
export interface CreateServerOptions {
readonly evmInterface?: EvmInterfaceService;
readonly logger?: Logger;
readonly binaryLayout?: BinaryLayoutService;
readonly firmwareAnalysis?: FirmwareAnalysisPort;
@@ -89,6 +93,9 @@ const installSessionToolAvailability = (
const policy = sessionAvailabilityPolicy(options.availabilityPolicy, {
optionalProviderLoadFailures: options.optionalProviderLoadFailures,
optionalFeatures: {
evmInterfaceEnabled:
options.evmInterface !== undefined ||
(process.platform === "linux" && process.arch === "x64"),
webModuleResolutionEnabled:
options.webModuleTrace !== undefined ||
isAbsolute(process.env.REA_BROWSER_EXECUTABLE ?? ""),
@@ -205,6 +212,12 @@ export const createServer = (
toolLogger,
recordEvidence,
);
registerEvmTools(
server,
options.evmInterface ?? createEvmInterfaceService(),
toolLogger,
recordEvidence,
);
registerFirmwareTools(
server,
new FirmwareAnalysisService(
+32
View File
@@ -0,0 +1,32 @@
import type { McpServer } from "@modelcontextprotocol/server";
import type { EvmInterfaceService } from "../application/evm/EvmInterfaceService.js";
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
import { toolContract } from "../contracts/toolContracts.js";
import type { Logger } from "../logger.js";
import { logToolExecution } from "./toolLogging.js";
import { toolRegistrationOptions } from "./toolRegistrationOptions.js";
import { toCallToolResult } from "./toolResult.js";
/** Bind the named EVM contract to shared validation and session Evidence recording. */
export const registerEvmTools = (
server: McpServer,
service: EvmInterfaceService,
logger: Logger,
recordEvidence?: EvidenceWriter["recordEvidence"],
): void => {
const contract = toolContract("inspect_evm_interface");
server.registerTool(
contract.name,
toolRegistrationOptions(contract),
async (input, context) => {
const result = await logToolExecution(logger, contract.name, () =>
service.inspect(input, { signal: context.mcpReq.signal }),
);
if (!result.ok) return toCallToolResult(result, contract);
const recorded = recordEvidence?.(result.value);
return recorded !== undefined && !recorded.ok
? toCallToolResult(recorded, contract)
: toCallToolResult(result, contract);
},
);
};
+3
View File
@@ -10,6 +10,7 @@ export interface SessionAvailabilityDefaults {
| undefined;
readonly optionalFeatures?: Pick<
SessionAvailability,
| "evmInterfaceEnabled"
| "browserObservationEnabled"
| "browserScenarioEnabled"
| "electronObservationEnabled"
@@ -32,6 +33,8 @@ export const sessionAvailabilityPolicy = (
const policy =
configured ??
(() => ({
evmInterfaceEnabled:
defaults.optionalFeatures?.evmInterfaceEnabled ?? false,
processCaptureEnabled: platform !== "win32",
binaryLayoutEnabled:
defaults.optionalFeatures?.binaryLayoutEnabled ?? false,