2023-09-22 17:57:16 +02:00

89 lines
2.5 KiB
TypeScript

import BaseService from "@Services/BaseService";
import { Service } from "typedi";
import { BackendVariables } from "@Common/config/variables/Variables";
import AnchoringProofService from "@Services/common/AnchoringProofService/AnchoringProofService";
import EAnchoringStatus from "le-coffre-resources/dist/Notary/EAnchoringStatus";
@Service()
export default class SecureService extends BaseService {
constructor(protected variables: BackendVariables, protected anchoringProofService: AnchoringProofService) {
super();
}
/**
* @description : anchor a sequence of hashes
* @throws {Error} If secure job cannot be created
*/
public async anchor(hash_sources: string[]) {
const url = new URL(this.variables.SECURE_API_BASE_URL.concat("/flows/v2/anchor"));
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
apiKey: this.variables.SECURE_API_KEY,
},
body: JSON.stringify({
hash_sources,
callback_url: "",
callback_config: {},
}),
});
return await response.json();
}
/**
* @description : verify if a sequence of hashes is anchored
* @throws {Error} If secure job cannot be found
*/
public async verify(hash_sources: string[]) {
const params = new URLSearchParams();
hash_sources.forEach((hash) => {
params.append("hash_sources", hash);
});
const url = new URL(this.variables.SECURE_API_BASE_URL.concat("/flows/v2/verify?").concat(params.toString()));
const response = await fetch(url, {
method: "GET",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
apiKey: this.variables.SECURE_API_KEY,
},
});
return await response.json();
}
/**
* @description : Download the anchoring proof document
* @throws {Error} If transaction is not verified on chain
*/
public async download(hash_sources: string[]) {
const anchor = await this.verify(hash_sources);
if (anchor.transactions.length === 0) {
throw new Error("No anchor found");
}
const transaction = anchor.transactions[0];
if (transaction.status !== EAnchoringStatus.VERIFIED_ON_CHAIN) {
throw new Error(`Transaction not verified on chain: ${transaction.status}`);
}
return this.anchoringProofService.generate({
rootHash: anchor.root_hash,
txLink: transaction.tx_link,
anchoringTime: new Date(transaction.anchoring_timestamp).toLocaleString("fr-FR", {
timeZone: "Europe/Paris",
timeZoneName: "short",
}),
});
}
}