From 6bef419b302a760ceb0010d3e42b65fca9148641 Mon Sep 17 00:00:00 2001 From: Lucas Leblow Date: Fri, 16 Aug 2024 16:00:57 -0600 Subject: [PATCH] crdx: Improve performance of decryptGraph --- packages/crdx/src/graph/decrypt.ts | 38 ++++++++++++++---------------- 1 file changed, 18 insertions(+), 20 deletions(-) diff --git a/packages/crdx/src/graph/decrypt.ts b/packages/crdx/src/graph/decrypt.ts index bb4e26c4..c90df9a2 100644 --- a/packages/crdx/src/graph/decrypt.ts +++ b/packages/crdx/src/graph/decrypt.ts @@ -51,34 +51,32 @@ export const decryptGraph: DecryptFn = ({ keys: KeysetWithSecrets | KeysetWithSecrets[] | Keyring }): Graph => { const { encryptedLinks, root, childMap = {} } = encryptedGraph - const links = encryptedGraph.links ?? {} + const toVisit = [root] + const visited: Set = new Set() + const decryptedLinks: Record> = {} + + while (toVisit.length > 0) { + const current = toVisit.pop() as Hash + + if (visited.has(current)) { + continue + } - /** Recursively decrypts a link and its children. */ - const decrypt = ( - hash: Hash, - prevLinks: Record> = {} - ): Record> => { - // decrypt this link - const encryptedLink = encryptedLinks[hash] + const encryptedLink = encryptedLinks[current] const decryptedLink = - links[hash] ?? // if it's already decrypted, don't bother decrypting it again + links[current] ?? // if it's already decrypted, don't bother decrypting it again decryptLink(encryptedLink, keys) - let newLinks = { - [hash]: decryptedLink, - } - // decrypt its children - const children = childMap[hash] ?? [] - for (const hash of children) { - newLinks = { ...newLinks, ...decrypt(hash, newLinks) } - } + decryptedLinks[current] = decryptedLink - return { ...prevLinks, ...newLinks } + const children = childMap[current] ?? [] + for (const child of children) { + toVisit.push(child) + } + visited.add(current) } - const decryptedLinks = decrypt(root) - return { ...encryptedGraph, links: decryptedLinks,