Files
advx/src/services/BlockchainService.ts
T
2025-04-10 23:07:21 -03:00

74 lines
2.0 KiB
TypeScript

import OpenTimestamps from 'opentimestamps-javascript'; // Atualizar import
import { createHash } from 'crypto';
import * as fs from 'fs/promises';
import * as path from 'path';
export class BlockchainService {
private readonly storageDir: string;
constructor() {
this.storageDir = path.join(process.cwd(), 'storage', 'timestamps');
this.ensureStorageDir();
}
private async ensureStorageDir() {
try {
await fs.mkdir(this.storageDir, { recursive: true });
} catch (error) {
console.error('Erro ao criar diretório de timestamps:', error);
}
}
async createTimestamp(buffer: Buffer) {
try {
// 1. Criar hash do arquivo
const fileHash = createHash('sha256').update(buffer).digest();
// 2. Criar timestamp
const timestamp = await OpenTimestamps.stamp(fileHash);
// 3. Salvar arquivo .ots
const otsPath = path.join(this.storageDir, `${fileHash.toString('hex')}.ots`);
await fs.writeFile(otsPath, Buffer.from(timestamp));
return {
hash: fileHash.toString('hex'),
timestamp,
otsPath
};
} catch (error) {
console.error('Erro ao criar timestamp:', error);
throw new Error('Falha ao criar timestamp na blockchain');
}
}
async verifyTimestamp(hash: string, timestamp: Buffer) {
try {
// Usar a API correta do OpenTimestamps
const result = await OpenTimestamps.verify(
Buffer.from(timestamp),
Buffer.from(hash, 'hex')
);
if (!result) {
return {
verified: false,
message: 'Timestamp ainda não confirmado na blockchain'
};
}
return {
verified: true,
timestamp: new Date(result * 1000),
message: 'Timestamp verificado na blockchain do Bitcoin'
};
} catch (error) {
console.error('Erro ao verificar timestamp:', error);
return {
verified: false,
message: 'Erro ao verificar timestamp'
};
}
}
}