From 44929fb2c90363014689b7d13d83ce5f423d7367 Mon Sep 17 00:00:00 2001 From: Andre Staltz Date: Wed, 18 Oct 2023 13:05:00 +0300 Subject: [PATCH] new API getMinRequiredDepth --- lib/index.js | 33 +++++++++++++++++++++++++-------- test/index.test.js | 5 +++-- 2 files changed, 28 insertions(+), 10 deletions(-) diff --git a/lib/index.js b/lib/index.js index a84a389..c38da27 100644 --- a/lib/index.js +++ b/lib/index.js @@ -335,23 +335,40 @@ function initRecord(peer, config) { /** * @param {string} tangleID + * @returns {number} */ - function getFieldRootsOfTangle(tangleID) { + function getMinRequiredDepth(tangleID) { assertDBExists(peer) - // prettier-ignore - if (!accountID) throw new Error('Cannot getFieldRootsByTangle() before loading') const rootMsg = peer.db.get(tangleID) if (!rootMsg) throw new Error(`Cannot find tangle root "${tangleID}"`) - // prettier-ignore - if (!MsgV3.isMoot(rootMsg, accountID)) throw new Error(`"${tangleID}" is not a moot`) + if (!MsgV3.isMoot(rootMsg)) throw new Error(`"${tangleID}" is not a moot`) const domain = rootMsg.metadata.domain // prettier-ignore if (!domain.startsWith(PREFIX)) throw new Error(`"${tangleID}" is not a record moot`) - const subdomain = toSubdomain(domain) - return getFieldRoots(subdomain) + // Discover field roots + const fieldRoots = new Set() + const tangle = peer.db.getTangle(tangleID) + const msgIDs = tangle.topoSort() + for (const msgID of msgIDs) { + const msg = peer.db.get(msgID) + if (!msg?.data) continue + for (const supersededMsgID of msg.data.supersedes) { + fieldRoots.delete(supersededMsgID) + } + fieldRoots.add(msgID) + } + + // Get minimum depth of all field roots + let minDepth = Infinity + for (const msgID of fieldRoots) { + const depth = tangle.getDepth(msgID) + if (depth < minDepth) minDepth = depth + } + + return minDepth } /** @@ -437,7 +454,7 @@ function initRecord(peer, config) { update, read, getFieldRoots, - getFieldRootsOfTangle, + getMinRequiredDepth, squeeze, _squeezePotential, diff --git a/test/index.test.js b/test/index.test.js index d81ae31..ad53eaf 100644 --- a/test/index.test.js +++ b/test/index.test.js @@ -116,6 +116,8 @@ test('Record receives old branched update', async (t) => { const moot = MsgV3.createMoot(aliceID, 'record_v1__profile', aliceKeypair) const mootID = MsgV3.getMsgID(moot) + assert.equal(peer.record.getMinRequiredDepth(mootID), 7, 'getMinRequiredDepth') + const tangle = new MsgV3.Tangle(mootID) tangle.add(mootID, moot) await p(peer.db.add)(moot, mootID) @@ -143,8 +145,7 @@ test('Record receives old branched update', async (t) => { 'fieldRoots' ) - const altFieldRoots7 = peer.record.getFieldRootsOfTangle(mootID) - assert.deepEqual(altFieldRoots7, fieldRoots7, 'getFieldRootsOfTangle') + assert.equal(peer.record.getMinRequiredDepth(mootID), 1, 'getMinRequiredDepth') assert.equal(peer.record._squeezePotential('profile'), 6, 'squeezePotential=6') })