Skip to content

Commit 9f1a8e8

Browse files
committed
Mask Solidity immutables before comparing runtime bytecode
The remaining bytecode-comparison failure is OZ UUPSUpgradeable's \`address private immutable __self = address(this)\`. solc patches the deployed impl's own address into the runtime bytecode at the immutable slot, so a freshly compiled local artifact (zero at the slot) differs from on-chain code over a 32-byte span. Sacd has three references to __self in the runtime, all 32 bytes, starting at byte 9025/9066/9423 — the divergence at byte 9037 sits inside the first. Pull immutableReferences out of hardhat's build-info, mask those byte ranges in both live and local code before comparing, and add a focused secondary check that the patched __self equals the impl address itself.
1 parent 050a3e1 commit 9f1a8e8

1 file changed

Lines changed: 88 additions & 10 deletions

File tree

‎scripts/validateOnTenderly.ts‎

Lines changed: 88 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -162,23 +162,39 @@ async function main() {
162162
checks.push({ label: 'Implementation address has code', ok: false, detail: 'no code at impl address' })
163163
} else {
164164
const artifact = await hre.artifacts.readArtifact('Sacd')
165-
// Solidity appends a CBOR metadata blob (IPFS hash + solc version) to runtime
166-
// bytecode. Its content varies with source-file paths and compile timestamp,
167-
// so two compiles of identical source from different machines disagree there.
168-
// Polygonscan verification strips it; we do the same before comparing.
165+
// Two things make a deployed runtime byte-different from a freshly compiled
166+
// local artifact, even when the source is identical:
167+
// 1. The CBOR metadata blob at the tail (IPFS hash of metadata.json +
168+
// solc version) varies with absolute source paths and compile times.
169+
// 2. Solidity immutables get patched with their runtime values at deploy.
170+
// OZ's UUPSUpgradeable has `address immutable __self = address(this)`,
171+
// so the impl's own address gets baked in at the immutable slot.
172+
// Strip metadata; mask out the immutable byte ranges (from solc's
173+
// immutableReferences in the build-info); compare the remainder.
169174
const liveStripped = stripMetadata(liveCode)
170175
const localStripped = stripMetadata(artifact.deployedBytecode)
171-
const exact = liveCode === artifact.deployedBytecode
172-
const codeMatches = liveStripped === localStripped
176+
177+
const immRefs = await loadImmutableRefs(hre, artifact)
178+
const liveMasked = maskImmutables(liveStripped, immRefs)
179+
const localMasked = maskImmutables(localStripped, immRefs)
180+
const immValues = readImmutableValues(liveStripped, immRefs)
181+
182+
const codeMatches = liveMasked === localMasked
183+
const onlyMetadataDiffered = liveStripped === localStripped
184+
173185
let detail: string
174-
if (exact) {
186+
if (liveCode === artifact.deployedBytecode) {
175187
detail = `exact match (${(liveCode.length - 2) / 2} bytes)`
176188
} else if (codeMatches) {
177-
detail = `match after stripping Solidity metadata blob — code identical, only metadata differs (benign; expected when compiled on different machines)`
189+
const immStr = immValues.length === 0 ? '' : ` Patched immutables: ${immValues.join(', ')}.`
190+
const stripped = onlyMetadataDiffered
191+
? 'only the trailing CBOR metadata blob differs'
192+
: 'differences are confined to metadata + immutable slots'
193+
detail = `match after stripping Solidity metadata + masking immutables — code identical (${stripped}; benign).${immStr}`
178194
} else {
179-
const div = firstDivergence(liveStripped, localStripped)
195+
const div = firstDivergence(liveMasked, localMasked)
180196
detail =
181-
`code differs even after stripping metadata; first divergence at byte ${div} ` +
197+
`code differs even after stripping metadata and masking immutables; first divergence at byte ${div} ` +
182198
`(live ${(liveStripped.length - 2) / 2} bytes vs local ${(localStripped.length - 2) / 2} bytes) — ` +
183199
`the deployed impl is NOT the source you have checked out`
184200
}
@@ -187,6 +203,21 @@ async function main() {
187203
ok: codeMatches,
188204
detail,
189205
})
206+
207+
// Sanity check: the patched __self immutable, if present, should equal the
208+
// impl address itself. If it doesn't, the deployed bytecode is something
209+
// weird (different impl deployed at this address, or layout assumption
210+
// wrong). This is a strong, focused check independent of the bulk compare.
211+
const selfMatch = immValues.find((v) => v.toLowerCase() === liveImpl.toLowerCase())
212+
if (immValues.length > 0) {
213+
checks.push({
214+
label: 'UUPS __self immutable equals impl address',
215+
ok: !!selfMatch,
216+
detail: selfMatch
217+
? `found ${selfMatch} baked into runtime bytecode`
218+
: `expected ${liveImpl} among baked-in immutables but found only [${immValues.join(', ')}]`,
219+
})
220+
}
190221
}
191222

192223
for (const c of checks) console.log(fmt(c))
@@ -661,6 +692,53 @@ function stripMetadata(bytecode: string): string {
661692
return '0x' + hex.slice(0, hex.length - totalToStripChars)
662693
}
663694

695+
type ImmRange = { start: number; length: number }
696+
697+
// Pulls solc's immutableReferences out of the build-info for the given artifact.
698+
// The shape is { astId: [{start, length}, ...] }; we flatten to a list of
699+
// byte ranges in the runtime bytecode that hold immutable values.
700+
async function loadImmutableRefs(hreInst: typeof hre, artifact: any): Promise<ImmRange[]> {
701+
const fqName = `${artifact.sourceName}:${artifact.contractName}`
702+
const buildInfo = await hreInst.artifacts.getBuildInfo(fqName)
703+
const out = buildInfo?.output?.contracts?.[artifact.sourceName]?.[artifact.contractName] as any
704+
const refs = out?.evm?.deployedBytecode?.immutableReferences as Record<string, ImmRange[]> | undefined
705+
if (!refs) return []
706+
return Object.values(refs).flat()
707+
}
708+
709+
// Replaces the bytes at each immutable range with zeros so two bytecodes that
710+
// only differ in their patched immutable values compare equal.
711+
function maskImmutables(hexCode: string, ranges: ImmRange[]): string {
712+
if (ranges.length === 0) return hexCode
713+
const hex = hexCode.startsWith('0x') ? hexCode.slice(2) : hexCode
714+
const buf = Buffer.from(hex, 'hex')
715+
for (const { start, length } of ranges) {
716+
if (start + length > buf.length) continue
717+
buf.fill(0, start, start + length)
718+
}
719+
return '0x' + buf.toString('hex')
720+
}
721+
722+
// Reads the live values that solc patched into each immutable slot. For an
723+
// `address` immutable solc reserves a 32-byte slot with the address right-
724+
// aligned; we extract the low 20 bytes as a checksummed address.
725+
function readImmutableValues(hexCode: string, ranges: ImmRange[]): string[] {
726+
const hex = hexCode.startsWith('0x') ? hexCode.slice(2) : hexCode
727+
const out: string[] = []
728+
for (const { start, length } of ranges) {
729+
if (length !== 32) continue
730+
const slot = hex.slice(start * 2, (start + length) * 2)
731+
if (slot.length !== 64) continue
732+
if (!/^0{24}/.test(slot)) continue // not address-shaped
733+
try {
734+
out.push(ethers.getAddress('0x' + slot.slice(24)))
735+
} catch {
736+
// not a valid address; skip
737+
}
738+
}
739+
return out
740+
}
741+
664742
function firstDivergence(a: string, b: string): number | string {
665743
const ah = a.startsWith('0x') ? a.slice(2) : a
666744
const bh = b.startsWith('0x') ? b.slice(2) : b

0 commit comments

Comments
 (0)