vc-notarization
Version:
Notarize verifiable credentials on DLT for provability and order
56 lines (55 loc) • 2.62 kB
JavaScript
import { MAX_INDEXATION_KEY_LENGTH, retrieveData, sendData, SingleNodeClient } from "@iota/iota.js";
import { Converter } from "@iota/util.js";
import { DLT } from '../enums.js';
const client = new SingleNodeClient(process.env.IOTA_NODE_URL || "https://chrysalis-nodes.iota.org");
/**
* Converts the index string into bytes and trims it if necessary
* @param index
* @returns
*/
function getIndexBytes(index) {
const indexBytes = Converter.utf8ToBytes(index);
if (indexBytes.length > MAX_INDEXATION_KEY_LENGTH)
return indexBytes.subarray(0, MAX_INDEXATION_KEY_LENGTH);
return indexBytes;
}
export class Iota {
dlt = DLT.IOTA;
explorerURL = process.env.IOTA_EXPLORER_URL || "https://explorer.iota.org/mainnet/message/";
async notarizeHash(hash, index) {
const indexBytes = getIndexBytes(index || hash);
const sendResult = await sendData(client, indexBytes, Converter.utf8ToBytes(hash));
return {
dlt: this.dlt,
transactionId: sendResult.messageId,
explorerURL: this.explorerURL + sendResult.messageId
};
}
async getNotarizedTimestamp(hash, index, proof) {
const indexBytes = getIndexBytes(index || hash);
const messages = await client.messagesFind(indexBytes);
if (messages && messages.messageIds.length > 0) {
const firstOccurance = await retrieveData(client, messages.messageIds[0]);
if (!firstOccurance || !firstOccurance.data)
throw new Error('Could not retrieve any message data from the tangle!');
if (Converter.bytesToUtf8(firstOccurance.data) !== hash)
throw new Error('Notarized hash does not match the given hash!');
const firstOccuranceMeta = await client.messageMetadata(messages.messageIds[0]);
if (!firstOccuranceMeta)
throw new Error('Could not retrieve any message meta data from the tangle!');
if (!firstOccuranceMeta.isSolid)
throw new Error('Notarization message is not solid!');
if (!firstOccuranceMeta.referencedByMilestoneIndex)
throw new Error('Notarization message was not referenced by a milestone!');
const milestone = await client.milestone(firstOccuranceMeta.referencedByMilestoneIndex);
return new Date(milestone.timestamp * 1000);
}
throw new Error('Could not retrieve any message from the tangle!');
}
async getStatus() {
return {
node: await client.info(),
health: await client.health(),
};
}
}