Skip to content

Commit

Permalink
Throw error for invalid circuit inputs
Browse files Browse the repository at this point in the history
  • Loading branch information
biscuitdey committed May 3, 2024
1 parent 0066bd7 commit 5764abd
Show file tree
Hide file tree
Showing 3 changed files with 137 additions and 124 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ import { ed25519 } from '@noble/curves/ed25519';
import * as circomlib from 'circomlibjs';
import * as crypto from 'crypto';
import 'dotenv/config';
import {
PublicKey,
PublicKeyType,
} from '../../../../identity/bpiSubjects/models/publicKey';

jest.setTimeout(20000);
describe('SnarkjsService', () => {
Expand All @@ -25,136 +29,135 @@ describe('SnarkjsService', () => {
});

//NOTE: Commenting out the workstep1 as it requires compiled artifacts to run. RUN THIS.
// beforeAll(async () => {
// const eddsa = await circomlib.buildEddsa();
// const privateKey = ed25519.utils.randomPrivateKey();
// const publicKeyPoints = eddsa.prv2pub(privateKey);
// const publicKey = [
// Buffer.from(publicKeyPoints[0]).toString('hex'),
// Buffer.from(publicKeyPoints[1]).toString('hex'),
// ].toString();
beforeAll(async () => {
const eddsa = await circomlib.buildEddsa();
const babyJub = await circomlib.buildBabyjub();
const privateKey = ed25519.utils.randomPrivateKey();
const publicKeyPoints = eddsa.prv2pub(privateKey);
const packedPublicKey = babyJub.packPoint(publicKeyPoints);
const eddsaPublicKey = Buffer.from(packedPublicKey).toString('hex');

// const payload = JSON.stringify({
// bpiId: 'f9d8e7c2-3a1b-4f6d-a5f3-f0f8f9f8f8f8',
// supplierInvoiceID: 'INV-12345',
// buyerInvoiceID: 'INV-67890',
// amount: 2000.0,
// issueDate: '2020-05-01',
// dueDate: '2020-06-01',
// status: 'NEW',
// items: [
// {
// id: 1,
// productID: 'ABC123',
// price: 10.0,
// amount: 50,
// },
// {
// id: 2,
// productID: 'DEF456',
// price: 20.0,
// amount: 25,
// },
// {
// id: 3,
// productID: 'ABC123',
// price: 10.0,
// amount: 50,
// },
// {
// id: 4,
// productID: 'ABC123',
// price: 10.0,
// amount: 50,
// },
// ],
// });
// const role = new BpiSubjectRole(
// '12',
// BpiSubjectRoleName.INTERNAL_BPI_SUBJECT,
// 'desc',
// );
// const ownerBpiSubject = new BpiSubject(
// '123',
// 'owner',
// 'ownerBpiSubject',
// publicKey,
// [role],
// );
// const fromBpiSubjectAccount = new BpiSubjectAccount(
// '123',
// ownerBpiSubject,
// ownerBpiSubject,
// 'authenticationPolicy',
// 'authorizationPolicy',
// 'verifiableCredential',
// 'recoveryKey',
// );
// const toBpiSubjectAccount = new BpiSubjectAccount(
// '123',
// ownerBpiSubject,
// ownerBpiSubject,
// 'authenticationPolicy',
// 'authorizationPolicy',
// 'verifiableCredential',
// 'recoveryKey',
// );
const payload = JSON.stringify({
bpiId: 'f9d8e7c2-3a1b-4f6d-a5f3-f0f8f9f8f8f8',
supplierInvoiceID: 'INV-12345',
buyerInvoiceID: 'INV-67890',
amount: 2000.0,
issueDate: '2020-05-01',
dueDate: '2020-06-01',
status: 'NEW',
items: [
{
id: 1,
productID: 'ABC123',
price: 10.0,
amount: 50,
},
{
id: 2,
productID: 'DEF456',
price: 20.0,
amount: 25,
},
{
id: 3,
productID: 'ABC123',
price: 10.0,
amount: 50,
},
{
id: 4,
productID: 'ABC123',
price: 10.0,
amount: 50,
},
],
});
const role = new BpiSubjectRole(
'12',
BpiSubjectRoleName.INTERNAL_BPI_SUBJECT,
'desc',
);
const ownerBpiSubject = new BpiSubject(
'123',
'owner',
'ownerBpiSubject',
[new PublicKey('321', PublicKeyType.EDDSA, eddsaPublicKey)],
[role],
);
const fromBpiSubjectAccount = new BpiSubjectAccount(
'123',
ownerBpiSubject,
ownerBpiSubject,
'authenticationPolicy',
'authorizationPolicy',
'verifiableCredential',
'recoveryKey',
);
const toBpiSubjectAccount = new BpiSubjectAccount(
'123',
ownerBpiSubject,
ownerBpiSubject,
'authenticationPolicy',
'authorizationPolicy',
'verifiableCredential',
'recoveryKey',
);

// const hashedPayload = crypto
// .createHash(`${process.env.MERKLE_TREE_HASH_ALGH}`)
// .update(JSON.stringify(payload))
// .digest();
const hashedPayload = crypto
.createHash(`${process.env.MERKLE_TREE_HASH_ALGH}`)
.update(JSON.stringify(payload))
.digest();

// const eddsaSignature = eddsa.signPedersen(privateKey, hashedPayload);
// const packedSignature = eddsa.packSignature(eddsaSignature);
// const signature = Buffer.from(packedSignature).toString('hex');
const eddsaSignature = eddsa.signPedersen(privateKey, hashedPayload);
const packedSignature = eddsa.packSignature(eddsaSignature);
const signature = Buffer.from(packedSignature).toString('hex');

// const tx: Transaction = new Transaction(
// '123',
// 12,
// '123',
// '123',
// fromBpiSubjectAccount,
// toBpiSubjectAccount,
// payload,
// signature,
// TransactionStatus.Initialized,
// );
const tx: Transaction = new Transaction(
'123',
12,
'123',
'123',
fromBpiSubjectAccount,
toBpiSubjectAccount,
payload,
signature,
TransactionStatus.Initialized,
);

// inputs = { tx };
// });
inputs = { tx };
});

// it('creates witness for workstep1', async () => {
// const circuitName = 'workstep1';
// const pathToCircuit =
// './zeroKnowledgeArtifacts/circuits/workstep1/workstep1_js/workstep1.wasm';
// const pathToProvingKey =
// './zeroKnowledgeArtifacts/circuits/workstep1/workstep1_final.zkey';
// const pathToVerificationKey =
// './zeroKnowledgeArtifacts/circuits/workstep1/workstep1_verification_key.json';
// const pathToWitnessCalculator =
// '../../../../../../zeroKnowledgeArtifacts/circuits/workstep1/workstep1_js/witness_calculator';
// const pathToWitnessFile =
// './zeroKnowledgeArtifacts/circuits/workstep1/witness.txt';
it('creates witness for workstep1', async () => {
const circuitName = 'workstep1';
const pathToCircuit =
'./zeroKnowledgeArtifacts/circuits/workstep1/workstep1_js/workstep1.wasm';
const pathToProvingKey =
'./zeroKnowledgeArtifacts/circuits/workstep1/workstep1_final.zkey';
const pathToVerificationKey =
'./zeroKnowledgeArtifacts/circuits/workstep1/workstep1_verification_key.json';
const pathToWitnessCalculator =
'../../../../../../zeroKnowledgeArtifacts/circuits/workstep1/workstep1_js/witness_calculator';
const pathToWitnessFile =
'./zeroKnowledgeArtifacts/circuits/workstep1/witness.txt';

// witness = await snarkjs.createWitness(
// inputs,
// circuitName,
// pathToCircuit,
// pathToProvingKey,
// pathToVerificationKey,
// pathToWitnessCalculator,
// pathToWitnessFile,
// );
// expect(typeof witness).toEqual('object');
// });
witness = await snarkjs.createWitness(
inputs,
circuitName,
pathToCircuit,
pathToProvingKey,
pathToVerificationKey,
pathToWitnessCalculator,
pathToWitnessFile,
);
expect(typeof witness).toEqual('object');
});

// it('verifies witness for workstep1', async () => {
// const isVerified = await snarkjs.verifyProofUsingWitness(witness);
// expect(isVerified).toBe(true);
// });
it('verifies witness for workstep1', async () => {
const isVerified = await snarkjs.verifyProofUsingWitness(witness);
expect(isVerified).toBe(true);
});

// afterAll(() => {
// globalThis.curve_bn128.terminate();
// });
afterAll(() => {
globalThis.curve_bn128.terminate();
});
});
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Injectable } from '@nestjs/common';
import { Injectable, BadRequestException } from '@nestjs/common';
import { Witness } from '../../../models/witness';
import { Proof } from '../../../models/proof';
import { ICircuitService } from '../circuitService.interface';
Expand All @@ -12,6 +12,14 @@ import * as fs from 'fs';
export class SnarkjsCircuitService implements ICircuitService {
public witness: Witness;

public async throwIfCreateWitnessInputInvalid(
publicInputs: string[],
): Promise<void> {
if (publicInputs[0] === '0') {
throw new BadRequestException('Invalid inputs');
}
}

public async createWitness(
inputs: {
tx: Transaction;
Expand Down Expand Up @@ -82,6 +90,8 @@ export class SnarkjsCircuitService implements ICircuitService {
pathToWitnessFile,
);

await this.throwIfCreateWitnessInputInvalid(publicInputs);

const newProof = {
value: proof,
protocol: proof.protocol,
Expand Down
Binary file not shown.

0 comments on commit 5764abd

Please sign in to comment.