UNPKG

@ceramicnetwork/core

Version:

Typescript implementation of the Ceramic protocol

90 lines 3.39 kB
import { AnchorStatus, EventType, StreamUtils } from '@ceramicnetwork/common'; import { filter, firstValueFrom } from 'rxjs'; export class Utils { static async getCommitData(dispatcher, cid, streamId, timestamp) { const commit = await dispatcher.retrieveCommit(cid, streamId); if (!commit) throw new Error(`No commit found for CID ${cid.toString()}`); const commitData = { cid, type: EventType.DATA, commit, timestamp }; if (StreamUtils.isSignedCommit(commit)) { const linkedCommit = await dispatcher.retrieveCommit(commit.link, streamId); if (!linkedCommit) throw new Error(`No commit found for CID ${commit.link.toString()}`); commitData.commit = linkedCommit; commitData.envelope = commit; commitData.capability = await this.extractCapability(commit, dispatcher); } else if (StreamUtils.isAnchorCommit(commit)) { commitData.type = EventType.TIME; commitData.proof = await dispatcher.retrieveFromIPFS(commit.proof); } if (!commitData.commit.prev) commitData.type = EventType.INIT; return commitData; } static async extractCapability(commit, dispatcher) { if (!commit.signatures || commit.signatures.length === 0) return; const capCID = StreamUtils.getCacaoCidFromCommit(commit); if (!capCID) return; try { const cacao = await dispatcher.retrieveFromIPFS(capCID); return cacao; } catch (error) { throw new Error(`Error while loading capability from IPFS with CID ${capCID.toString()}: ${error}`); } } static async anchorUpdate(ceramic, stream) { if ('anchor' in ceramic.anchorService) { const anchorService = ceramic.anchorService; const tillAnchored = firstValueFrom(stream.pipe(filter((state) => [AnchorStatus.ANCHORED, AnchorStatus.FAILED].includes(state.anchorStatus)))); await anchorService.anchor(); await tillAnchored; } else { return Promise.reject('Not InMemoryAnchorService'); } } } export class TrieNode { constructor(key = '') { this.key = key; this.children = {}; } } export class PathTrie { constructor() { this.root = new TrieNode(); } add(path) { const nextNodeAdd = (node, key) => { if (!node.children[key]) node.children[key] = new TrieNode(key); return node.children[key]; }; if (path.startsWith('/')) path = path.substring(1); path.split('/').reduce(nextNodeAdd, this.root); } } export const promiseTimeout = (promise, ms, timeoutErrorMsg) => { const timeout = new Promise((resolve, reject) => { setTimeout(() => reject(new Error(timeoutErrorMsg)), ms); }); return Promise.race([timeout, promise]); }; export const abortSignalToPromise = (abortSignal) => { return new Promise((resolve) => { if (abortSignal.aborted) { return resolve(); } const done = () => { abortSignal.removeEventListener('abort', done); resolve(); }; abortSignal.addEventListener('abort', done); }); }; //# sourceMappingURL=utils.js.map