hospital-log/backend/api/src/modules/proof/proof.service.ts

64 lines
1.8 KiB
TypeScript
Raw Normal View History

2025-11-13 07:06:16 +00:00
import {
Injectable,
InternalServerErrorException,
NotFoundException,
} from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { RekammedisService } from '../rekammedis/rekammedis.service';
2025-11-13 07:06:16 +00:00
import { groth16, wtns } from 'snarkjs';
import path from 'path';
@Injectable()
export class ProofService {
constructor(
private prismaService: PrismaService,
private rekamMedisService: RekammedisService,
) {}
2025-11-13 07:06:16 +00:00
buildDir = path.join(__dirname, '../../../', 'dist');
publicDir = path.join(__dirname, '../../../../', '/api/public');
wasmPath = path.join(this.publicDir, 'circuit.wasm');
zkeyPath = path.join(this.publicDir, 'circuit_final.zkey');
vkeyPath = path.join(this.publicDir, 'verification_key.json');
witnessPath = path.join(this.buildDir, 'witness.wtns');
async calculateWitness(age: number) {
const inputs = {
age: age,
threshold: 18,
};
await wtns.calculate(inputs, this.wasmPath, this.witnessPath);
}
async generateProof() {
const { proof, publicSignals } = await groth16.prove(
this.zkeyPath,
this.witnessPath,
);
return { proof, publicSignals };
}
async getProof(id_visit: any) {
const age = await this.rekamMedisService.getAgeByIdVisit(id_visit);
if (!age) {
throw new NotFoundException('ID Visit tidak ditemukan');
}
try {
await this.calculateWitness(age);
} catch (error) {
console.log('Error during witness calculation:', error);
throw new InternalServerErrorException(
"Can't generate proof from input based on constraint. Please check the input data and try again.",
);
}
const { proof, publicSignals } = await this.generateProof();
return {
proof: proof,
publicSignals: publicSignals,
};
}
}