feat(evm): inspect lossless Solidity terminal CBOR metadata (#2790)

feat(evm): retain lossless terminal CBOR metadata

Refs morluto/rea#2388

Co-authored-by: Matheus Breguêz <matbrgz@gmail.com>
Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
morluto
2026-10-13 21:55:30 +08:00
committed by GitHub
co-authored by Matheus Breguêz Codex
parent a3daf8a07b
commit 48a683ac8c
24 changed files with 1002 additions and 5 deletions
+8
View File
@@ -2,6 +2,14 @@ import { expect, it } from "vitest";
import { evmInterfaceSchema } from "./evmInterface.js";
import { evmInterfaceFixture } from "../../../tests/fixtures/evm/interface.js";
it("accepts historical metadata omission as an unknown facet without changing the source", () => {
const value = evmInterfaceFixture();
const { metadata: _metadata, ...oldBytecode } = value.bytecode;
const old = { ...value, bytecode: oldBytecode };
expect(evmInterfaceSchema.parse(old).bytecode.metadata).toBeNull();
expect(old.bytecode).not.toHaveProperty("metadata");
});
it.each(["byte-count", "body-offset", "selector", "authenticity"])(
"rejects false interface evidence: %s",
(problem) => {
+19
View File
@@ -1,6 +1,7 @@
import { z } from "zod";
import { localPathStringSchema } from "../localPath.js";
import { solidityMetadataSchema } from "./solidityMetadata.js";
const byteOffset = z.number().int().nonnegative();
const sha256 = z.string().regex(/^[a-f0-9]{64}$/);
@@ -34,6 +35,7 @@ export const evmInterfaceSchema = z
kind: z.literal("unknown"),
deployment_authenticity: z.literal("unknown"),
hardfork: z.literal("unknown"),
metadata: solidityMetadataSchema.nullable().default(null),
}),
evidence_kind: z.literal("inferred"),
functions: z.array(
@@ -62,6 +64,23 @@ export const evmInterfaceSchema = z
message:
"Selected byte count does not match the bytecode hex representation.",
});
const metadata = value.bytecode.metadata;
if (
metadata !== null &&
metadata.status !== "unavailable" &&
(metadata.bytecode_offset === null ||
metadata.cbor_bytes === null ||
metadata.bytecode_offset + metadata.cbor_bytes + 2 !==
value.bytecode.bytes ||
metadata.cbor_bytes !==
Number.parseInt(value.bytecode.hex.slice(-4), 16))
)
context.addIssue({
code: "custom",
path: ["bytecode", "metadata"],
message:
"Metadata range must match the terminal length suffix in selected bytecode.",
});
for (const [index, fn] of value.functions.entries())
if (fn.bytecode_offset >= value.bytecode.bytes)
context.addIssue({
+89
View File
@@ -0,0 +1,89 @@
import { z } from "zod";
/** Scalar view of CBOR; uninterpreted containers remain in original bytecode. */
export const solidityMetadataScalarSchema = z.discriminatedUnion("kind", [
z.strictObject({ kind: z.literal("text"), value: z.string().max(65535) }),
z.strictObject({
kind: z.literal("integer"),
value: z
.string()
.max(21)
.regex(/^-?(?:0|[1-9][0-9]*)$/),
}),
z.strictObject({
kind: z.literal("bytes"),
value: z
.string()
.max(131070)
.regex(/^(?:[a-f0-9]{2})*$/),
}),
z.strictObject({ kind: z.literal("boolean"), value: z.boolean() }),
z.strictObject({ kind: z.literal("null") }),
z.strictObject({
kind: z.literal("uninterpreted"),
container: z.enum(["array", "map"]),
}),
]);
/** A trailer candidate, not authentication of Solidity origin or deployment. */
export const solidityMetadataSchema = z
.strictObject({
profile: z.literal("terminal-cbor-scalars-v1"),
status: z.enum(["unavailable", "decoded", "partial", "not-decoded"]),
bytecode_offset: z.number().int().nonnegative().nullable(),
cbor_bytes: z.number().int().positive().max(65535).nullable(),
entries: z
.array(
z.strictObject({
key: solidityMetadataScalarSchema,
value: solidityMetadataScalarSchema,
}),
)
.max(32767),
compiler_version: z
.strictObject({
representation: z.enum(["release-bytes", "prerelease-text"]),
value: z.string().min(1).max(65535),
})
.nullable(),
diagnostic: z.string().max(512).nullable(),
})
.superRefine((value, context) => {
const unavailable = value.status === "unavailable";
if (
unavailable
? value.bytecode_offset !== null || value.cbor_bytes !== null
: value.bytecode_offset === null || value.cbor_bytes === null
)
context.addIssue({
code: "custom",
message: "Only unavailable metadata omits the candidate range.",
});
const unexamined = unavailable || value.status === "not-decoded";
if (
unexamined &&
(value.entries.length !== 0 || value.compiler_version !== null)
)
context.addIssue({
code: "custom",
message:
"Unavailable interpretation cannot report decoded entries or compiler identity.",
});
const uninterpreted = value.entries.some(
({ key, value: entryValue }) =>
key.kind === "uninterpreted" || entryValue.kind === "uninterpreted",
);
if (
(value.status === "decoded" && uninterpreted) ||
(value.status === "partial" && !uninterpreted)
)
context.addIssue({
code: "custom",
message: "Scalar coverage must preserve uninterpreted containers.",
});
});
export type SolidityMetadata = z.infer<typeof solidityMetadataSchema>;
export type SolidityMetadataScalar = z.infer<
typeof solidityMetadataScalarSchema
>;
+3
View File
@@ -30,6 +30,7 @@ import {
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import type { InspectEvmInterfaceInput } from "../domain/evm/evmInterface.js";
import { evmInterfaceSchema } from "../domain/evm/evmInterface.js";
import { solidityMetadataSchema } from "../domain/evm/solidityMetadata.js";
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
import { err, ok, type Result } from "../domain/result.js";
@@ -67,6 +68,7 @@ const replySchema = z.discriminatedUnion("ok", [
sha256: z.string().regex(/^[a-f0-9]{64}$/),
bytes: z.number().int().nonnegative(),
hex: z.string().regex(/^(?:[a-f0-9]{2})*$/),
metadata: solidityMetadataSchema.optional(),
}),
raw: evmoleInterfaceReplySchema,
}),
@@ -331,6 +333,7 @@ export class EvmoleInterfaceProvider implements EvmInterfacePort {
"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.",
"Terminal CBOR metadata is an independently decoded candidate, not proof of Solidity origin, source identity or deployment. Nested or unsupported values retain explicit unavailable interpretation and original byte ranges.",
"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({
+2
View File
@@ -6,6 +6,7 @@ import {
EvmCarrierFailure,
} from "./EvmBytecodeCarrier.js";
import { projectEvmoleInterface } from "./EvmoleInterfaceAdapter.js";
import { inspectSolidityMetadata } from "./SolidityMetadata.js";
import {
EVM_INTERFACE_LIMITS,
EVM_FILE_SIZE_FAILURE_EXIT,
@@ -64,6 +65,7 @@ const main = async (): Promise<void> => {
sha256: createHash("sha256").update(bytes).digest("hex"),
bytes: bytes.length,
hex: Buffer.from(bytes).toString("hex"),
metadata: inspectSolidityMetadata(bytes),
},
raw: inferred.raw,
};
+96
View File
@@ -0,0 +1,96 @@
import { expect, it } from "vitest";
import { inspectSolidityMetadata } from "./SolidityMetadata.js";
const bytecode = (hex: string) => {
const payload = Buffer.from(hex, "hex");
const length = Buffer.alloc(2);
length.writeUInt16BE(payload.length);
return Buffer.concat([Buffer.from("00", "hex"), payload, length]);
};
it("reads a compiler version from actual trailer bytes without a magic-prefix assumption", () => {
const result = inspectSolidityMetadata(bytecode("a164736f6c634300081e"));
expect(result).toMatchObject({
status: "decoded",
bytecode_offset: 1,
cbor_bytes: 10,
compiler_version: { representation: "release-bytes", value: "0.8.30" },
entries: [
{
key: { kind: "text", value: "solc" },
value: { kind: "bytes", value: "00081e" },
},
],
});
});
it("preserves integer and non-text key precision beyond Number", () => {
expect(
inspectSolidityMetadata(bytecode("a1011bffffffffffffffff")).entries,
).toEqual([
{
key: { kind: "integer", value: "1" },
value: { kind: "integer", value: "18446744073709551615" },
},
]);
expect(
inspectSolidityMetadata(bytecode("a1003bffffffffffffffff")).entries[0]
?.value,
).toEqual({
kind: "integer",
value: "-18446744073709551616",
});
});
it("retains opaque nested values as partial rather than fabricating scalar values", () => {
expect(inspectSolidityMetadata(bytecode("a161788100"))).toMatchObject({
status: "partial",
entries: [
{
key: { kind: "text", value: "x" },
value: { kind: "uninterpreted", container: "array" },
},
],
});
});
it("preserves a UTF-8 BOM inside a CBOR text value rather than stripping it", () => {
expect(
inspectSolidityMetadata(bytecode("a1617864efbbbf61")).entries[0]?.value,
).toEqual({
kind: "text",
value: "\ufeffa",
});
expect(
inspectSolidityMetadata(bytecode("a167efbbbf736f6c634300081e"))
.compiler_version,
).toBeNull();
});
it.each([
["invalid text", "a1617861ff"],
["truncated value", "a16178"],
["unsupported tag", "a16178c000"],
["floating point", "a16178fa3f800000"],
["duplicate key", "a2617801617802"],
["excessive nesting", "a16178" + "81".repeat(65) + "00"],
["impossible collection", "a161788a00"],
])("keeps exact ranges and unavailable interpretation for %s", (_name, hex) => {
expect(inspectSolidityMetadata(bytecode(hex))).toMatchObject({
status: "not-decoded",
bytecode_offset: 1,
entries: [],
compiler_version: null,
});
});
it.each(["", "60006000f3", "000000", "00010001"])(
"does not claim absent Solidity metadata for an unavailable trailer: %s",
(hex) =>
expect(inspectSolidityMetadata(Buffer.from(hex, "hex"))).toMatchObject({
status: "unavailable",
bytecode_offset: null,
cbor_bytes: null,
entries: [],
}),
);
+158
View File
@@ -0,0 +1,158 @@
import { decode, Tokenizer, Type, type Token } from "cborg";
import type {
SolidityMetadata,
SolidityMetadataScalar,
} from "../domain/evm/solidityMetadata.js";
const PROFILE = "terminal-cbor-scalars-v1";
const MAX_DEPTH = 64;
const utf8 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
const decodeOptions = {
useMaps: true,
allowBigInt: true,
allowIndefinite: false,
allowUndefined: false,
allowInfinity: false,
allowNaN: false,
rejectDuplicateMapKeys: true,
retainStringBytes: true,
} as const;
/** Bound recursive decoder entry before collection interpretation/allocation. */
class BoundedMetadataTokenizer extends Tokenizer {
readonly remaining: number[] = [];
constructor(bytes: Uint8Array) {
super(bytes, decodeOptions);
}
override next(): Token {
while (this.remaining.at(-1) === 0) this.remaining.pop();
const token = super.next();
if (
Type.equals(token.type, Type.tag) ||
Type.equals(token.type, Type.float)
)
throw new Error(
"CBOR tags and floating-point values are outside this metadata profile.",
);
if (Type.equals(token.type, Type.string)) {
if (token.byteValue === undefined)
throw new Error(
"CBOR text bytes were unavailable for strict UTF-8 validation.",
);
token.value = utf8.decode(token.byteValue);
}
const parent = this.remaining.length - 1;
if (parent >= 0) this.remaining[parent]!--;
if (
Type.equals(token.type, Type.map) ||
Type.equals(token.type, Type.array)
) {
const count: unknown = token.value;
const children =
typeof count === "number"
? count * (Type.equals(token.type, Type.map) ? 2 : 1)
: NaN;
if (
!Number.isSafeInteger(children) ||
children < 0 ||
children > this.data.length
)
throw new Error(
"Declared CBOR collection exceeds the encoded item-byte bound.",
);
if (this.remaining.length >= MAX_DEPTH)
throw new Error("CBOR nesting exceeds the 64-level metadata profile.");
this.remaining.push(children);
}
return token;
}
}
const scalar = (value: unknown): SolidityMetadataScalar => {
if (typeof value === "string") return { kind: "text", value };
if (typeof value === "bigint")
return { kind: "integer", value: value.toString() };
if (typeof value === "number" && Number.isSafeInteger(value))
return { kind: "integer", value: String(value) };
if (typeof value === "boolean") return { kind: "boolean", value };
if (value === null) return { kind: "null" };
if (value instanceof Uint8Array)
return { kind: "bytes", value: Buffer.from(value).toString("hex") };
if (value instanceof Map) return { kind: "uninterpreted", container: "map" };
if (Array.isArray(value))
return { kind: "uninterpreted", container: "array" };
throw new Error(
"CBOR decoder returned a value outside the admitted profile.",
);
};
/** Parse only a plausible terminal root-map candidate; never establish absence. */
export const inspectSolidityMetadata = (
bytes: Uint8Array,
): SolidityMetadata => {
const empty: SolidityMetadata = {
profile: PROFILE,
status: "unavailable",
bytecode_offset: null,
cbor_bytes: null,
entries: [],
compiler_version: null,
diagnostic:
"No plausible terminal CBOR map was identified; Solidity origin and metadata absence remain unknown.",
};
if (bytes.length < 3) return empty;
const length = bytes[bytes.length - 2]! * 256 + bytes[bytes.length - 1]!;
const offset = bytes.length - 2 - length;
if (length === 0 || offset < 0 || bytes[offset]! >> 5 !== 5) return empty;
const selected = bytes.subarray(offset, bytes.length - 2);
const result: SolidityMetadata = {
...empty,
status: "not-decoded",
bytecode_offset: offset,
cbor_bytes: length,
};
try {
const raw: unknown = decode(selected, {
...decodeOptions,
tokenizer: new BoundedMetadataTokenizer(selected),
});
if (!(raw instanceof Map))
throw new Error("Terminal CBOR candidate did not decode to a root map.");
for (const [key, value] of raw as Map<unknown, unknown>)
result.entries.push({ key: scalar(key), value: scalar(value) });
result.status = result.entries.some(
({ key, value }) =>
key.kind === "uninterpreted" || value.kind === "uninterpreted",
)
? "partial"
: "decoded";
result.diagnostic =
result.status === "partial"
? "Nested containers are uninterpreted; their exact bytes remain at the recorded range in original bytecode."
: null;
const version: unknown = raw.get("solc");
if (version instanceof Uint8Array && version.length === 3)
result.compiler_version = {
representation: "release-bytes",
value: [...version].join("."),
};
else if (typeof version === "string" && version.length > 0)
result.compiler_version = {
representation: "prerelease-text",
value: version,
};
return result;
} catch (cause: unknown) {
return {
...result,
status: "not-decoded",
entries: [],
compiler_version: null,
diagnostic: (cause instanceof Error
? cause.message
: String(cause)
).slice(0, 512),
};
}
};