Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/verify-without-cbor-metadata.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@nomicfoundation/hardhat-verify": patch
---

Fixed verification of contracts compiled with Solidity's `metadata.appendCBOR` setting disabled.
77 changes: 7 additions & 70 deletions packages/hardhat-verify/src/internal/bytecode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,9 @@ import {
assertHardhatInvariant,
HardhatError,
} from "@nomicfoundation/hardhat-errors";
import {
getUnprefixedHexString,
hexStringToBytes,
} from "@nomicfoundation/hardhat-utils/hex";
import { getUnprefixedHexString } from "@nomicfoundation/hardhat-utils/hex";

import {
getMetadataSectionBytesLength,
inferSolcVersion,
METADATA_LENGTH_FIELD_SIZE,
} from "./metadata.js";
import { parseBytecodeMetadata } from "./metadata.js";

interface ByteOffset {
start: number;
Expand All @@ -29,18 +22,6 @@ export class Bytecode {
public readonly executableSection: string,
) {}

static async #parse(bytecode: string): Promise<Bytecode> {
const bytecodeBytes = hexStringToBytes(bytecode);

const solcVersion = await inferSolcVersion(bytecodeBytes);
const executableSection = bytecode.slice(
0,
bytecode.length - getMetadataSectionBytesLength(bytecodeBytes) * 2,
);

return new Bytecode(bytecode, solcVersion, executableSection);
}

public static async getDeployedContractBytecode(
provider: EthereumProvider,
address: string,
Expand All @@ -66,11 +47,9 @@ export class Bytecode {
);
}

return await Bytecode.#parse(deployedBytecode);
}

public hasVersionRange(): boolean {
return this.solcVersion.type !== "exact";
const { solcVersion, executableSection } =
parseBytecodeMetadata(deployedBytecode);
return new Bytecode(deployedBytecode, solcVersion, executableSection);
}

/**
Expand All @@ -91,9 +70,8 @@ export class Bytecode {
* equivalent, `false` otherwise.
*/
public compare(compilerOutputBytecode: CompilerOutputBytecode): boolean {
const unlinkedExecutableSection = inferExecutableSection(
compilerOutputBytecode.object,
);
const { executableSection: unlinkedExecutableSection } =
parseBytecodeMetadata(compilerOutputBytecode.object);

// If the lengths differ, the bytecodes cannot match, so we can return early
if (this.executableSection.length !== unlinkedExecutableSection.length) {
Expand All @@ -114,47 +92,6 @@ export class Bytecode {
}
}

/**
* Extracts the executable portion of a contract's bytecode without
* decoding it.
*
* Solidity appends metadata to the end of the bytecode. This metadata
* includes a two-byte field indicating its total length. This function
* removes that metadata segment and returns only the executable code.
*
* This approach avoids decoding issues that can occur if the bytecode
* includes linker placeholders or non-hex characters.
*
* @param bytecode The full contract bytecode as a hex string
* (with or without `0x` prefix).
* @returns The hex string of the executable code, excluding metadata.
*/
export function inferExecutableSection(bytecode: string): string {
const rawBytecode = getUnprefixedHexString(bytecode);

// Read the last 2 bytes (4 hex chars) that encode the length of
// the metadata section.
const metadataLengthBytes = hexStringToBytes(
rawBytecode.slice(-METADATA_LENGTH_FIELD_SIZE * 2),
);

// If the bytecode is too short to contain a metadata length field,
// return the entire bytecode.
if (metadataLengthBytes.length !== METADATA_LENGTH_FIELD_SIZE) {
return rawBytecode;
}

const metadataSectionLength =
getMetadataSectionBytesLength(metadataLengthBytes);

// invalid length (metadata + length field doesn't fit)
if (metadataSectionLength * 2 > rawBytecode.length) {
return rawBytecode;
}

return rawBytecode.slice(0, rawBytecode.length - metadataSectionLength * 2);
}

/**
* Replaces all known dynamic offset segments in the bytecode with zeros.
*
Expand Down
8 changes: 5 additions & 3 deletions packages/hardhat-verify/src/internal/contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,9 +117,11 @@ export class ContractInformationResolver {
const formattedSolcVersion = formatInferredSolcVersion(
deployedBytecode.solcVersion,
);
const versionDetails = deployedBytecode.hasVersionRange()
? `a Solidity version in the range ${formattedSolcVersion}`
: `the Solidity version ${formattedSolcVersion}`;
const versionDetails = {
exact: `the Solidity version ${formattedSolcVersion}`,
between: `a Solidity version in the range ${formattedSolcVersion}`,
unknown: "an unknown Solidity version",
}[deployedBytecode.solcVersion.type];

throw new HardhatError(
HardhatError.ERRORS.HARDHAT_VERIFY.GENERAL
Expand Down
197 changes: 87 additions & 110 deletions packages/hardhat-verify/src/internal/metadata.ts
Original file line number Diff line number Diff line change
@@ -1,148 +1,125 @@
import type { SemverVersion } from "@nomicfoundation/hardhat-utils/fast-semver";

import util from "node:util";

import { bytesToHexString } from "@nomicfoundation/hardhat-utils/bytes";
import { createDebug } from "@nomicfoundation/hardhat-utils/debug";
import {
getUnprefixedHexString,
hexStringToBytes,
} from "@nomicfoundation/hardhat-utils/hex";
import { decode } from "cbor2";

const log = createDebug("hardhat:verify:metadata");

export const METADATA_LENGTH_FIELD_SIZE = 2;

/**
* The Solidity compiler version inferred from a contract's deployed bytecode.
*
* Bytecode metadata was introduced in Solidity v0.4.7, and the explicit
* version field was added in v0.5.9. Below those thresholds we can only
* narrow the version down to a range.
* The Solidity compiler version inferred from a contract's bytecode metadata.
* Solidity introduced metadata in v0.4.7 and the version field in v0.5.9.
* Bytecode without metadata may also come from a modern compiler with CBOR
* metadata disabled.
*/
export type InferredSolcVersion =
| { type: "exact"; version: SemverVersion }
| { type: "lessThan"; bound: SemverVersion }
| { type: "between"; min: SemverVersion; max: SemverVersion };

const MISSING_METADATA: InferredSolcVersion = {
type: "lessThan",
bound: [0, 4, 7],
};
| { type: "between"; min: SemverVersion; max: SemverVersion }
| { type: "unknown" };

const SOLC_NOT_FOUND_IN_METADATA: InferredSolcVersion = {
type: "between",
min: [0, 4, 7],
max: [0, 5, 8],
};
interface ParsedBytecode {
executableSection: string;
solcVersion: InferredSolcVersion;
}

/**
* Attempts to infer the Solidity compiler version from the bytecode metadata.
*
* - Metadata was introduced in Solidity v0.4.7.
* See: https://docs.soliditylang.org/en/v0.4.7/miscellaneous.html#contract-metadata
* - The version field was first added in v0.5.9.
* See https://docs.soliditylang.org/en/v0.5.9/metadata.html#encoding-of-the-metadata-hash-in-the-bytecode
*
* @param bytecode The deployed bytecode as a Uint8Array.
* @returns The inferred solc version, either as an exact `x.y.z` or, when
* the metadata is missing or incomplete, as a fallback range.
* Strips a recognized Solidity CBOR section from the end of the bytecode.
* Only the suffix is decoded, so the executable code may contain unlinked
* library placeholders.
*/
export async function inferSolcVersion(
bytecode: Uint8Array,
): Promise<InferredSolcVersion> {
let solcMetadata: unknown;
export function parseBytecodeMetadata(bytecode: string): ParsedBytecode {
const rawBytecode = getUnprefixedHexString(bytecode);

return (
decodeSolcMetadata(rawBytecode) ?? {
executableSection: rawBytecode,
solcVersion: { type: "unknown" },
}
);
}

function decodeSolcMetadata(bytecode: string): ParsedBytecode | undefined {
// The final two bytes give the size of the CBOR payload in bytes.
const lengthFieldStart = bytecode.length - METADATA_LENGTH_FIELD_SIZE * 2;
const lengthField = bytecode.slice(lengthFieldStart);
if (!/^[0-9a-f]{4}$/i.test(lengthField)) {
return undefined;
}

const metadataStart = lengthFieldStart - Number.parseInt(lengthField, 16) * 2;
if (metadataStart < 0 || metadataStart === lengthFieldStart) {
return undefined;
}

let metadata: unknown;
try {
solcMetadata = await decodeSolcMetadata(bytecode);
const payload = hexStringToBytes(
bytecode.slice(metadataStart, lengthFieldStart),
);
metadata = decode(payload, { preferMap: true });
} catch {
// Decoding failed, likely an older compiler or non-Solidity bytecode
log("Failed to decode metadata.");
return MISSING_METADATA;
return undefined;
}

if (solcMetadata instanceof Uint8Array) {
if (solcMetadata.length === 3) {
const [major, minor, patch] = solcMetadata;
log(
`Detected Solidity version from metadata: ${major}.${minor}.${patch}`,
);
return { type: "exact", version: [major, minor, patch] };
}
// Unexpected length. Log raw metadata for inspection
log(
`Unexpected metadata version format: [${[...solcMetadata].join(", ")}]`,
);
if (!(metadata instanceof Map)) {
return undefined;
}

const solcVersion = inferSolcVersion(metadata);
if (solcVersion === undefined) {
return undefined;
}

// Metadata was decoded but contained no version field
log("Metadata decoded but Solidity version not found.");
return SOLC_NOT_FOUND_IN_METADATA;
return {
executableSection: bytecode.slice(0, metadataStart),
solcVersion,
};
}

function inferSolcVersion(
metadata: Map<unknown, unknown>,
): InferredSolcVersion | undefined {
const solc = metadata.get("solc");
if (solc instanceof Uint8Array && solc.length === 3) {
const [major, minor, patch] = solc;
return { type: "exact", version: [major, minor, patch] };
}

// Pre-release compilers store their full version as a string.
if (typeof solc === "string" && /^\d+\.\d+\.\d+-/.test(solc)) {
return { type: "unknown" };
}

// Solidity 0.4.7 through 0.5.8 stored a Swarm hash without a version.
const bzzr0 = metadata.get("bzzr0");
if (
solc === undefined &&
bzzr0 instanceof Uint8Array &&
bzzr0.length === 32
) {
return { type: "between", min: [0, 4, 7], max: [0, 5, 8] };
}

return undefined;
}

/**
* Formats an `InferredSolcVersion` as a human-readable string suitable for
* inclusion in error messages: an exact `x.y.z`, a `<x.y.z` upper bound, or
* an `x.y.z - x.y.z` closed range.
*/
export function formatInferredSolcVersion(v: InferredSolcVersion): string {
switch (v.type) {
case "exact":
return formatTuple(v.version);
case "lessThan":
return `<${formatTuple(v.bound)}`;
case "between":
return `${formatTuple(v.min)} - ${formatTuple(v.max)}`;
case "unknown":
return "unknown";
}
}

function formatTuple(v: SemverVersion): string {
return `${v[0]}.${v[1]}.${v[2]}`;
}

/**
* Reads the Solidity metadata section length from the end of the contract
* bytecode.
*
* Solidity appends metadata to the end of the deployed bytecode.
* The final 2 bytes (defined by METADATA_LENGTH) encode the length of the
* metadata section, using a big-endian unsigned 16-bit integer.
* See https://docs.soliditylang.org/en/latest/metadata.html#encoding-of-the-metadata-hash-in-the-bytecode
*
* This function uses a DataView to read those final 2 bytes, and returns the
* total length of the metadata section (payload + length field).
*
* @param bytecode The bytecode as an Uint8Array.
* @returns The total length (in bytes) of the metadata section at the end of
* the bytecode.
*/
export function getMetadataSectionBytesLength(bytecode: Uint8Array): number {
const view = new DataView(
bytecode.buffer,
bytecode.byteOffset + bytecode.byteLength - METADATA_LENGTH_FIELD_SIZE,
METADATA_LENGTH_FIELD_SIZE,
);

return view.getUint16(0, false) + METADATA_LENGTH_FIELD_SIZE;
}

/**
* Decodes the CBOR metadata from the given bytecode and returns the `solc`
* version field. The function throws if the metadata cannot be decoded.
*/
async function decodeSolcMetadata(bytecode: Uint8Array): Promise<unknown> {
const metadataSectionBytesLength = getMetadataSectionBytesLength(bytecode);
const metadataPayload = bytecode.slice(
-metadataSectionBytesLength,
-METADATA_LENGTH_FIELD_SIZE,
);

log(`Read metadata section length: ${metadataSectionBytesLength} bytes`);

const lastBytes = metadataPayload.slice(-100);
log(
`Last ${lastBytes.length} bytes of metadata: ${bytesToHexString(lastBytes)}`,
);

const decodedMetadata = decode(metadataPayload);
log(`Metadata decoded: ${util.inspect(decodedMetadata)}`);

// @ts-expect-error: the metadata is known to contain a `solc` field
return decodedMetadata.solc;
}
4 changes: 2 additions & 2 deletions packages/hardhat-verify/src/internal/solc-versions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,13 +81,13 @@ export function filterVersionsByInferred(
switch (inferred.type) {
case "exact":
return equals(parsed, inferred.version);
case "lessThan":
return lowerThan(parsed, inferred.bound);
case "between":
return (
greaterThanOrEqual(parsed, inferred.min) &&
lowerThanOrEqual(parsed, inferred.max)
);
case "unknown":
return true;
}
});
}
Loading