Skip to content
Merged
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: 3 additions & 2 deletions nest/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,9 @@ RUN mkdir -p $RUSTUP_HOME $CARGO_HOME \
# Add Rust to the PATH environment variable for all subsequent commands
ENV PATH="/usr/local/cargo/bin:$PATH"

# Install near-cli-rs for contract verification
RUN cargo install near-cli-rs --locked
# Install near-cli-rs for contract verification. Pinned: the verify controller
# parses this CLI's output and relies on its at-block-hash argument.
RUN cargo install near-cli-rs --version 0.31.1 --locked

# Set environment variable for near-cli-rs to run in non-interactive mode
ENV NEAR_CI=1
Expand Down
112 changes: 95 additions & 17 deletions nest/src/controllers/verify/verify.controller.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,12 @@ describe('VerifyController snapshot', () => {
const verifier = { getContract: jest.fn(), setContract: jest.fn() };
const compiler = { verifyContract: jest.fn() };
const ipfs = { addFolder: jest.fn() };
const github = {
parseSourceCodeSnapshot: () => ({ repoUrl: 'repo', sha: 'sha' }),
clone: jest.fn(),
checkout: jest.fn(),
getRepoPath: () => 'path',
};
const response = { status: jest.fn().mockReturnThis(), json: jest.fn() };
const verify = (blockId?: number) =>
controller.verifyRust(
Expand Down Expand Up @@ -49,15 +55,7 @@ describe('VerifyController snapshot', () => {
providers: [
{ provide: CompilerService, useValue: compiler },
{ provide: ExecService, useValue: {} },
{
provide: GithubService,
useValue: {
parseSourceCodeSnapshot: () => ({ repoUrl: 'repo', sha: 'sha' }),
clone: jest.fn(),
checkout: jest.fn(),
getRepoPath: () => 'path',
},
},
{ provide: GithubService, useValue: github },
{
provide: TempService,
useValue: { createFolder: () => 'tmp', deleteFolder: jest.fn() },
Expand Down Expand Up @@ -111,18 +109,98 @@ describe('VerifyController snapshot', () => {
expect(verifier.setContract).not.toHaveBeenCalled();
});

it('keeps the existing response for an already verified hash', async () => {
const expectNothingBuiltOrWritten = () => {
expect(github.clone).not.toHaveBeenCalled();
expect(compiler.verifyContract).not.toHaveBeenCalled();
expect(ipfs.addFolder).not.toHaveBeenCalled();
expect(verifier.setContract).not.toHaveBeenCalled();
};

// An unchanged hash needs no height check: nothing would be written
it.each([height, height + 1])(
'returns the existing response for an already verified hash before building (record height: %s)',
async (recordHeight) => {
verifier.getContract.mockResolvedValueOnce({
block_height: recordHeight,
code_hash: hash,
});
await verify(height);
expect(response.status).toHaveBeenCalledWith(400);
expect(response.json).toHaveBeenCalledWith({
message: "Code hash didn't change",
});
expectNothingBuiltOrWritten();
},
);

// getContract returns block_height as a number; its parsing is tested there
it('rejects a block older than the existing record', async () => {
verifier.getContract.mockResolvedValueOnce({
block_height: height,
code_hash: hash,
block_height: height + 1,
code_hash: 'old',
});
await verify();
expect(response.status).toHaveBeenCalledWith(400);
await verify(height);
expect(response.status).toHaveBeenCalledWith(409);
expect(response.json).toHaveBeenCalledWith({
message: "Code hash didn't change",
message: `Block ${height} is older than the verified record for test.near at block ${height + 1}. Verify at block ${height + 1} or later.`,
});
expectNothingBuiltOrWritten();
});

it.each([height, height - 1, 0])(
'verifies a block at or after the existing record (record height: %p)',
async (recordHeight) => {
verifier.getContract.mockResolvedValueOnce({
block_height: recordHeight,
code_hash: 'old',
});
await verify(height);
expect(compiler.verifyContract).toHaveBeenCalledWith(
'test.near',
'mainnet',
block,
);
expect(verifier.setContract).toHaveBeenCalledWith(
'test.near',
'cid',
hash,
height,
'rust',
);
expect(response.status).toHaveBeenCalledWith(200);
},
);

it('returns 503 without building when the registry cannot be read', async () => {
verifier.getContract.mockRejectedValueOnce(new Error('RPC timeout'));
await verify(height);
expect(response.status).toHaveBeenCalledWith(503);
expect(response.json).toHaveBeenCalledWith({
message:
'Could not read the verifier registry for test.near. Please retry later.',
});
expect(rpc.callFunction).not.toHaveBeenCalled();
expect(rpc.viewCode).not.toHaveBeenCalled();
expectNothingBuiltOrWritten();
});

it('verifies when the registry has no record', async () => {
verifier.getContract.mockResolvedValueOnce(null);
await verify(height);
expect(compiler.verifyContract).toHaveBeenCalled();
expect(ipfs.addFolder).toHaveBeenCalled();
expect(verifier.setContract).toHaveBeenCalledWith(
'test.near',
'cid',
hash,
height,
'rust',
);
expect(response.status).toHaveBeenCalledWith(200);
expect(response.json).toHaveBeenCalledWith({
message: 'Contract verified successfully',
checksum: hash,
});
expect(ipfs.addFolder).not.toHaveBeenCalled();
expect(verifier.setContract).not.toHaveBeenCalled();
});

it('rejects inconsistent RPC snapshots before building', async () => {
Expand Down
40 changes: 36 additions & 4 deletions nest/src/controllers/verify/verify.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,11 +83,21 @@ export class VerifyController {
throw new HttpException('Invalid network ID', 400);
}

let contractData: ContractData = null;
// The existing record decides whether this request may replace it, so an
// unreadable registry or record stops the request; only a null answer
// means no record. getContract checks code_hash and block_height.
// It is read at the latest final block, not the verification block,
// because the guards below compare against the record as it is now.
let contractData: ContractData | null;
try {
contractData = await verifierService.getContract(accountId);
} catch {
// Contract not found in verifier, continue
} catch (error) {
this.logger.error(
`Registry read failed for ${accountId}: ${error.message}`,
);
return res.status(503).json({
message: `Could not read the verifier registry for ${accountId}. Please retry later.`,
});
}

// Pre-verification checks: Get contract metadata and validate repository accessibility
Expand Down Expand Up @@ -142,6 +152,28 @@ export class VerifyController {
}
deployedHash = code.hash;

if (contractData) {
// The record already holds the deployed code: nothing to build or write
if (contractData.code_hash === deployedHash) {
this.logger.log(
`Code hash unchanged for ${accountId}: ${deployedHash} (already verified)`,
);
return res.status(400).json({ message: "Code hash didn't change" });
}

// set_contract replaces the record without comparing heights, so an
// older block must not get that far
const recordHeight = contractData.block_height;
if (blockHeight < recordHeight) {
this.logger.warn(
`Rejected stale block for ${accountId}: block ${blockHeight} is older than the record at block ${recordHeight}`,
);
return res.status(409).json({
message: `Block ${blockHeight} is older than the verified record for ${accountId} at block ${recordHeight}. Verify at block ${recordHeight} or later.`,
});
}
}

// Extract the repository URL and pinned commit SHA
const { repoUrl, sha } = this.githubService.parseSourceCodeSnapshot(
buildInfo.source_code_snapshot,
Expand Down Expand Up @@ -247,7 +279,7 @@ export class VerifyController {
.json({ message: 'Contract verification failed' });
}

// Check if the code hash is the same as the one in the verifier contract
// Backstop for the pre-build check: never rewrite an unchanged hash
if (contractData && contractData.code_hash === checksum) {
this.logger.log(
`Code hash unchanged for ${accountId}: ${checksum} (already verified)`,
Expand Down
160 changes: 160 additions & 0 deletions nest/src/modules/near/services/verifier.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
import { HttpException } from '@nestjs/common';
import { KeyPair } from '@near-js/crypto';
import { VerifierService } from './verifier.service';

describe('VerifierService.getContract', () => {
const record = {
cid: 'cid',
lang: 'rust',
code_hash: '5KaX9FM9NtjpfahksL8TMWQk3LF7k8Sv88Qem4tGrVDW',
block_height: 165753012,
votes: [],
comments: [],
};
const reply = (result: unknown) => ({
result,
logs: [],
block_hash: '56xEo2LorUFVNbkFhCncFSWNiobdp1kzm14nZ47b5JVW',
block_height: 165753100,
});
// A well-formed call_function reply: the JSON answer as an array of bytes
const answer = (json: string) => reply([...Buffer.from(json)]);
// A record in raw JSON, so fields can hold values JSON.stringify can't write
const recordJson = (fields: Record<string, string>) =>
`{${Object.entries(fields)
.map(([key, value]) => `"${key}":${value}`)
.join(',')}}`;
let service: VerifierService;
let query: jest.Mock;

const expectUnreadable = async () => {
const error = await service.getContract('test.near').catch((e) => e);
expect(error).toBeInstanceOf(HttpException);
expect(error.getStatus()).toBe(503);
};

beforeEach(() => {
service = new VerifierService({
accountId: 'registry.near',
nodeUrl: 'http://127.0.0.1:1',
privateKey: KeyPair.fromRandom('ed25519').toString(),
} as any);
query = jest.fn();
(service as any).provider = { query };
});

it('reads the record from the registry at the final block', async () => {
query.mockResolvedValueOnce(answer(JSON.stringify(record)));
await expect(service.getContract('test.near')).resolves.toEqual(record);
expect(query).toHaveBeenCalledWith({
request_type: 'call_function',
account_id: 'registry.near',
method_name: 'get_contract',
args_base64: Buffer.from('{"account_id":"test.near"}').toString('base64'),
finality: 'final',
});
});

it('returns null only for a genuinely absent record', async () => {
query.mockResolvedValueOnce(answer('null'));
await expect(service.getContract('test.near')).resolves.toBeNull();
});

it('throws a 503 when the registry RPC fails', async () => {
query.mockRejectedValueOnce(new Error('fetch failed'));
await expectUnreadable();
});

it('throws a 503 when the RPC reply is missing', async () => {
query.mockResolvedValueOnce(undefined);
await expectUnreadable();
});

// Buffer.from also accepts strings, so a text "null" must not decode to
// an absent record
it.each([
'null',
JSON.stringify(record),
undefined,
null,
42,
{},
{ 0: 110, length: 1 },
[256],
[-1],
[1.5],
['n'],
[null],
])(
'throws a 503 when the RPC result is not an array of bytes (%p)',
async (result) => {
query.mockResolvedValueOnce(reply(result));
await expectUnreadable();
},
);

it.each(['', 'not json', '{"code_hash":', '42', '"record"', 'true', '[]'])(
'throws a 503 when the registry answer is not a record or null (%p)',
async (json) => {
query.mockResolvedValueOnce(answer(json));
await expectUnreadable();
},
);

it.each([undefined, 'null', '42', '""', '["hash"]', '{}'])(
'throws a 503 when the record code_hash is not a non-empty string (%p)',
async (codeHash) => {
const fields: Record<string, string> = { block_height: '165753012' };
if (codeHash !== undefined) fields.code_hash = codeHash;
query.mockResolvedValueOnce(answer(recordJson(fields)));
await expectUnreadable();
},
);

it.each([
['165753012', 165753012],
['"165753012"', 165753012],
['0', 0],
['"0"', 0],
])(
'returns block_height %s as the number %p',
async (blockHeight, expected) => {
query.mockResolvedValueOnce(
answer(recordJson({ code_hash: '"hash"', block_height: blockHeight })),
);
await expect(service.getContract('test.near')).resolves.toEqual({
code_hash: 'hash',
block_height: expected,
});
},
);

it.each([
undefined,
'null',
'-1',
'1.5',
'1e400',
'9007199254740992',
'9007199254740993',
'""',
'" 1"',
'"-1"',
'"1.5"',
'"1e3"',
'"0x10"',
'"01"',
'"9007199254740993"',
'true',
'[1]',
'{}',
])(
'throws a 503 when the record block_height is malformed (%p)',
async (blockHeight) => {
const fields: Record<string, string> = { code_hash: '"hash"' };
if (blockHeight !== undefined) fields.block_height = blockHeight;
query.mockResolvedValueOnce(answer(recordJson(fields)));
await expectUnreadable();
},
);
});
Loading
Loading