From dd3dc6997b41c0ec700d5eaadc80f37395ab748b Mon Sep 17 00:00:00 2001 From: Trinidadec Date: Sat, 28 Oct 2023 00:18:59 +0300 Subject: [PATCH] Push Digest (#26) * push digest * part end * minor renaming * mask partial end result --- index.mjs | 6 +++--- tree.mjs | 25 ++++++++++++++++++++----- 2 files changed, 23 insertions(+), 8 deletions(-) diff --git a/index.mjs b/index.mjs index e8ffcc4..58c2f6d 100644 --- a/index.mjs +++ b/index.mjs @@ -5,9 +5,9 @@ const { toAddress } = base32 /** @type {(hash: string) => string} */ const getPath = hash => `${hash.substring(0, 2)}/${hash.substring(2, 4)}/${hash.substring(4)}` -/** @type {(root: string) => Buffer} */ -const getBuffer = root => { - const data = fs.readFileSync(`cdt0/${root}`) +/** @type {(path: string) => Buffer} */ +const getBuffer = path => { + const data = fs.readFileSync(`cdt0/${path}`) const tailLength = data[0] console.log(`tail length = ${tailLength}`) if (tailLength === 32) { diff --git a/tree.mjs b/tree.mjs index 9c47f4b..2478e71 100644 --- a/tree.mjs +++ b/tree.mjs @@ -13,9 +13,11 @@ const { compress } = sha224 const mask244 = ((1n << 224n) - 1n) /** @type {(state: State) => (nu8: number) => void} */ -const push = state => nu8 => { +const push = state => nu8 => pushDigest(state)(byteToDigest(nu8)) + +/** @type {(state: State) => (bu256: bigint) => void} */ +const pushDigest = state => last0 => { let i = 0 - let last0 = byteToDigest(nu8) while (true) { let subTree = state[i] if (subTree === undefined) { @@ -32,15 +34,28 @@ const push = state => nu8 => { } /** @type {(state: State) => bigint} */ -const end = state => { +const end = state => compress(internalEnd(state)) & mask244 + +/** @type {(state: State) => bigint | null} */ +const partialEnd = state => { + let digest256 = internalEnd(state) + if (digest256 >> 224n === 0xffff_ffffn) { + return null + } + return digest256 & mask244 +} + +/** @type {(state: State) => bigint} */ +const internalEnd = state => { let last0 = 0n for (let subTree of state) { last0 = endSubTree(subTree)(last0) } - return compress(last0) & mask244 + return last0 } export default { push, - end + end, + partialEnd } \ No newline at end of file