@cronstamp/clientlib
Version:
Client library for cronstamp, a blockchain-based document timestamping and verification service.
63 lines • 2.58 kB
JavaScript
import { hashString, isValidHash, VersionToHashAlgorithm } from './util/hash.js';
import { blockchainNames, blockchains } from './blockchains/blockchains.js';
import { ErrorTypes, ProcessError } from './lifecycle/manager.js';
export async function getCertificateFromFile(certificateFile) {
let certificateString = await certificateFile.text();
return getCertificateFromString(certificateString);
}
export async function getCertificateFromString(certificateString) {
return JSON.parse(certificateString);
}
export class CertificateHelper {
cert;
constructor(cert) {
this.cert = cert;
}
async calculateSaltedHash() {
let flattenedBlockchains = this.cert.meta.blockchains.sort().join(',');
let hashMetaContent = `${this.cert.meta.version}${flattenedBlockchains}${this.cert.meta.salt}`;
let hashContent = this.cert.document_hash + hashMetaContent;
return await hashString(hashContent, VersionToHashAlgorithm[this.cert.meta.version]);
}
/**
* Check, if the blockchains array contains invalid or extra fields
*/
static isValidBlockchainList(blockchains) {
return blockchains ? blockchains.every((b) => blockchainNames.includes(b)) : false;
}
/**
* Check if the certificate has all necessary data
*/
hasData() {
return (this.cert?.blockchains !== undefined &&
this.cert.meta.version > 0 &&
this.cert.meta.blockchains !== undefined &&
this.cert.document_hash !== undefined &&
this.cert.meta.salt !== undefined &&
isValidHash(this.cert.document_hash, VersionToHashAlgorithm[this.cert.meta.version]));
}
//TODO: Use the abstract class for this
getCertificateUnixTime() {
let lastTimestamp = -1;
for (const [name, data] of Object.entries(this.cert.blockchains)) {
let blockchain = blockchains[name];
if (data?.block_timestamp) {
let timestamp = blockchain.getTransactionUnixTimestamp(data.block_timestamp);
if (lastTimestamp < timestamp) {
lastTimestamp = timestamp;
}
}
}
if (lastTimestamp == -1) {
throw new ProcessError('Unable to determine blockchain timestamp!', ErrorTypes.DOCUMENT_ALTERED);
}
return lastTimestamp;
}
getCertificateDate() {
return new Date(this.getCertificateUnixTime());
}
getJSON() {
return JSON.stringify(this.cert);
}
}
//# sourceMappingURL=certificate.js.map