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
147 changes: 147 additions & 0 deletions nest/src/controllers/verify/verify.controller.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
import { Test } from '@nestjs/testing';
import type { Response } from 'express';
import { CompilerService } from '../../services/compiler/compiler.service';
import { ExecService } from '../../services/exec/exec.service';
import { GithubService } from '../../services/github/github.service';
import { IpfsService } from '../../services/ipfs/ipfs.service';
import { TempService } from '../../services/temp/temp.service';
import { VerifyController } from './verify.controller';

describe('VerifyController snapshot', () => {
const height = 165753012;
const block = '56xEo2LorUFVNbkFhCncFSWNiobdp1kzm14nZ47b5JVW';
const hash = '5KaX9FM9NtjpfahksL8TMWQk3LF7k8Sv88Qem4tGrVDW';
const metadata = {
block_hash: block,
block_height: height,
result: { build_info: { source_code_snapshot: 'snapshot' } },
};
const rpc = { callFunction: jest.fn(), viewCode: jest.fn() };
const verifier = { getContract: jest.fn(), setContract: jest.fn() };
const compiler = { verifyContract: jest.fn() };
const ipfs = { addFolder: jest.fn() };
const response = { status: jest.fn().mockReturnThis(), json: jest.fn() };
const verify = (blockId?: number) =>
controller.verifyRust(
{ accountId: 'test.near', networkId: 'mainnet', blockId },
response as unknown as Response,
);
let controller: VerifyController;

beforeEach(async () => {
jest.clearAllMocks();
verifier.getContract.mockResolvedValue(null);
rpc.callFunction.mockResolvedValue(metadata);
rpc.viewCode.mockResolvedValue({
block_hash: block,
block_height: height,
hash,
});
compiler.verifyContract.mockResolvedValue({
stdout: [
'The code obtained from the contract account ID and the code calculated from the repository are the same.',
'Contract code hash: ' + hash,
],
});
ipfs.addFolder.mockResolvedValue('cid');
const module = await Test.createTestingModule({
controllers: [VerifyController],
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: TempService,
useValue: { createFolder: () => 'tmp', deleteFolder: jest.fn() },
},
{ provide: IpfsService, useValue: ipfs },
{ provide: 'MainnetRpcService', useValue: rpc },
{ provide: 'MainnetVerifierService', useValue: verifier },
{ provide: 'TestnetRpcService', useValue: {} },
{ provide: 'TestnetVerifierService', useValue: {} },
],
}).compile();
controller = module.get(VerifyController);
});

// blockId 0 keeps its historical meaning: the latest final block
it.each([undefined, 0, height])(
'pins every read after metadata (request block: %s)',
async (requested) => {
await verify(requested);
expect(rpc.callFunction).toHaveBeenCalledWith(
'test.near',
'contract_source_metadata',
requested,
);
expect(rpc.viewCode).toHaveBeenCalledWith('test.near', block);
expect(compiler.verifyContract).toHaveBeenCalledWith(
'test.near',
'mainnet',
block,
);
expect(verifier.setContract).toHaveBeenCalledWith(
'test.near',
'cid',
hash,
height,
'rust',
);
expect(response.status).toHaveBeenCalledWith(200);
},
);

it('does not sign or pin if the reported build hash differs from deployed code', async () => {
rpc.viewCode.mockResolvedValueOnce({
block_hash: block,
block_height: height,
hash: 'other',
});
await verify();
expect(response.status).toHaveBeenCalledWith(400);
expect(ipfs.addFolder).not.toHaveBeenCalled();
expect(verifier.setContract).not.toHaveBeenCalled();
});

it('keeps the existing response for an already verified hash', async () => {
verifier.getContract.mockResolvedValueOnce({
block_height: height,
code_hash: hash,
});
await verify();
expect(response.status).toHaveBeenCalledWith(400);
expect(response.json).toHaveBeenCalledWith({
message: "Code hash didn't change",
});
expect(ipfs.addFolder).not.toHaveBeenCalled();
expect(verifier.setContract).not.toHaveBeenCalled();
});

it('rejects inconsistent RPC snapshots before building', async () => {
rpc.viewCode.mockResolvedValueOnce({
block_hash: 'other',
block_height: height + 1,
hash,
});
await verify();
expect(response.status).toHaveBeenCalledWith(500);
expect(compiler.verifyContract).not.toHaveBeenCalled();
expect(verifier.setContract).not.toHaveBeenCalled();
});

it('rejects metadata from a block other than the requested one', async () => {
await verify(height - 1);
expect(response.status).toHaveBeenCalledWith(500);
expect(rpc.viewCode).not.toHaveBeenCalled();
expect(compiler.verifyContract).not.toHaveBeenCalled();
expect(verifier.setContract).not.toHaveBeenCalled();
});
});
45 changes: 41 additions & 4 deletions nest/src/controllers/verify/verify.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,10 @@ export class VerifyController {
// Pre-verification checks: Get contract metadata and validate repository accessibility
let contractMetadata: ContractMetadataDto = null;
let buildInfo: BuildInfo = null;
// Every read after the metadata lookup is pinned to the block it came from.
let blockHash: string;
let blockHeight: number;
let deployedHash: string;

try {
// Get contract metadata to check if source is accessible
Expand All @@ -112,6 +116,32 @@ export class VerifyController {

buildInfo = contractMetadata.build_info;

blockHash = contractMetadataResponse.block_hash;
blockHeight = contractMetadataResponse.block_height;
// blockId 0 has always meant the latest final block (callFunction treats it as unset)
const requestedHeight = blockId || undefined;
if (
typeof blockHash !== 'string' ||
!blockHash ||
!Number.isSafeInteger(blockHeight) ||
blockHeight < 0 ||
(requestedHeight !== undefined && blockHeight !== requestedHeight)
) {
throw new Error('Invalid block in metadata response');
}

const code = await rpcService.viewCode(accountId, blockHash);
if (
code.block_hash !== blockHash ||
code.block_height !== blockHeight ||
!('hash' in code) ||
typeof code.hash !== 'string' ||
!code.hash
) {
throw new Error('Invalid code response for verification block');
}
deployedHash = code.hash;

// Extract the repository URL and pinned commit SHA
const { repoUrl, sha } = this.githubService.parseSourceCodeSnapshot(
buildInfo.source_code_snapshot,
Expand Down Expand Up @@ -174,6 +204,7 @@ export class VerifyController {
const { stdout } = await this.compilerService.verifyContract(
accountId,
networkId,
blockHash,
);

// Parse verification output
Expand Down Expand Up @@ -206,6 +237,16 @@ export class VerifyController {
});
}

// The rebuilt hash must be the code deployed at the verification block
if (checksum !== deployedHash) {
this.logger.warn(
`Verification failed for ${accountId}: built ${checksum}, deployed ${deployedHash} at block ${blockHeight}`,
);
return res
.status(400)
.json({ message: 'Contract verification failed' });
}

// Check if the code hash is the same as the one in the verifier contract
if (contractData && contractData.code_hash === checksum) {
this.logger.log(
Expand All @@ -218,10 +259,6 @@ export class VerifyController {
`New verification for ${accountId}: old=${contractData?.code_hash || 'none'}, new=${checksum}`,
);

// Get the actual block height from the contract code query
const codeResponse = await rpcService.viewCode(accountId, blockId);
const blockHeight = (codeResponse as any).block_height;

// Contract metadata and buildInfo already fetched in pre-verification checks

// Extract the repository URL and pinned commit SHA
Expand Down
45 changes: 45 additions & 0 deletions nest/src/modules/near/services/rpc.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { RpcService } from './rpc.service';

describe('RpcService block selection', () => {
const blockHash = '56xEo2LorUFVNbkFhCncFSWNiobdp1kzm14nZ47b5JVW';
let service: RpcService;
let query: jest.Mock;

beforeEach(() => {
service = new RpcService({ nodeUrl: 'http://127.0.0.1:1' } as any);
query = jest.fn().mockResolvedValue({
result: [...Buffer.from('{}')],
block_hash: blockHash,
block_height: 1,
});
(service as any).provider = { query };
});

it.each([undefined, 0])(
'reads metadata from the final block when blockId is %s',
async (blockId) => {
await service.callFunction(
'test.near',
'contract_source_metadata',
blockId,
);
expect(query.mock.calls[0][0]).toMatchObject({ finality: 'final' });
expect(query.mock.calls[0][0]).not.toHaveProperty('block_id');
},
);

it('reads metadata from the requested block height', async () => {
await service.callFunction('test.near', 'contract_source_metadata', 42);
expect(query.mock.calls[0][0]).toMatchObject({ block_id: 42 });
expect(query.mock.calls[0][0]).not.toHaveProperty('finality');
});

it('reads deployed code only at the given block hash', async () => {
await service.viewCode('test.near', blockHash);
expect(query.mock.calls[0][0]).toEqual({
request_type: 'view_code',
account_id: 'test.near',
block_id: blockHash,
});
});
});
9 changes: 2 additions & 7 deletions nest/src/modules/near/services/rpc.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,20 +40,15 @@ export class RpcService {

async viewCode(
accountId: string,
blockId?: number,
blockHash: string,
): Promise<QueryResponseKind> {
try {
const queryParams: any = {
request_type: 'view_code',
account_id: accountId,
block_id: blockHash,
};

if (blockId) {
queryParams.block_id = blockId;
} else {
queryParams.finality = 'final';
}

const response = await this.provider.query(queryParams);

this.logger.log(`Code viewed for account ID: ${accountId}`);
Expand Down
18 changes: 14 additions & 4 deletions nest/src/services/compiler/compiler.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { ExecService } from '../exec/exec.service';
import { CompilerService } from './compiler.service';

describe('CompilerService', () => {
const blockHash = '56xEo2LorUFVNbkFhCncFSWNiobdp1kzm14nZ47b5JVW';
let compilerService: CompilerService;
let execService: ExecService;

Expand All @@ -29,7 +30,11 @@ describe('CompilerService', () => {
.spyOn(execService, 'executeFile')
.mockResolvedValue({ stderr: [], stdout: mockOutput });

const result = await compilerService.verifyContract('test.near', 'mainnet');
const result = await compilerService.verifyContract(
'test.near',
'mainnet',
blockHash,
);
expect(result.stdout).toEqual(mockOutput);
expect(execService.executeFile).toHaveBeenCalledWith('near', [
'contract',
Expand All @@ -38,7 +43,8 @@ describe('CompilerService', () => {
'test.near',
'network-config',
'mainnet',
'now',
'at-block-hash',
blockHash,
]);
});

Expand All @@ -47,13 +53,17 @@ describe('CompilerService', () => {
jest.spyOn(execService, 'executeFile').mockRejectedValue(error);

await expect(
compilerService.verifyContract('test.near', 'mainnet'),
compilerService.verifyContract('test.near', 'mainnet', blockHash),
).rejects.toThrow(error);
});

it('should reject unsafe account IDs before executing', async () => {
await expect(
compilerService.verifyContract('test.near; touch /tmp/pwned', 'mainnet'),
compilerService.verifyContract(
'test.near; touch /tmp/pwned',
'mainnet',
blockHash,
),
).rejects.toThrow('Invalid NEAR account ID');
expect(execService.executeFile).not.toHaveBeenCalled();
});
Expand Down
4 changes: 3 additions & 1 deletion nest/src/services/compiler/compiler.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export class CompilerService {
async verifyContract(
accountId: string,
networkId: string,
blockHash: string,
): Promise<{ stdout: string[] }> {
if (!isValidNearAccountId(accountId)) {
throw new BadRequestException('Invalid NEAR account ID');
Expand All @@ -37,7 +38,8 @@ export class CompilerService {
accountId,
'network-config',
networkId,
'now',
'at-block-hash',
blockHash,
]);
this.logger.log(`Contract verification completed`);
return { stdout };
Expand Down
Loading