]> zoso.dev Git - libnemo.git/commitdiff
Use new WASM blake hashing module. Eliminate an import within worker file by performi...
authorChris Duncan <chris@zoso.dev>
Sun, 17 Nov 2024 07:24:38 +0000 (23:24 -0800)
committerChris Duncan <chris@zoso.dev>
Sun, 17 Nov 2024 07:24:38 +0000 (23:24 -0800)
src/lib/ckd.ts

index 8e40b9db7f78d2485ed7ce814358b6f2009a4fb2..78cb8cc17272c3de0f067618c0508ec0bafb920c 100644 (file)
@@ -1,15 +1,16 @@
 // SPDX-FileCopyrightText: 2024 Chris Duncan <chris@zoso.dev>
 // SPDX-License-Identifier: GPL-3.0-or-later
 
-import blake2b from 'blake2b'
+import blake2b from 'blake2b-wasm'
 import { nanoCKD } from './bip32-key-derivation.js'
-import { dec, hex } from './convert.js'
 
-if (globalThis.Worker == null) {
+let addEventListener = globalThis.addEventListener
+let postMessage = globalThis.postMessage
+if (addEventListener == null || postMessage == null) {
        const { isMainThread, parentPort } = await import('node:worker_threads')
-       if (!isMainThread) {
-               globalThis.addEventListener ??= Object.getPrototypeOf(parentPort).on.bind(parentPort)
-               globalThis.postMessage ??= Object.getPrototypeOf(parentPort).postMessage.bind(parentPort)
+       if (!isMainThread && parentPort) {
+               addEventListener = Object.getPrototypeOf(parentPort).addListener.bind(parentPort)
+               postMessage = Object.getPrototypeOf(parentPort).postMessage.bind(parentPort)
        }
 }
 
@@ -31,7 +32,7 @@ addEventListener('message', (message) => {
                        break
                }
        }
-}, { once: true })
+})
 
 /**
 * Derives BIP-44 Nano account private keys.
@@ -50,7 +51,10 @@ async function ckdBip44 (seed: string, index: number): Promise<string> {
 * @returns {Promise<Account>}
 */
 async function ckdBlake2b (seed: string, index: number): Promise<string> {
-       const input = `${seed}${dec.toHex(index, 8)}`
-       const hash = blake2b(32).update(hex.toBytes(input)).digest('hex')
+       const indexHex = index.toString(16).padStart(8, '0').toUpperCase()
+       const inputHex = `${seed}${indexHex}`.padStart(72, '0')
+       const inputArray = (inputHex.match(/.{1,2}/g) ?? []).map(h => parseInt(h, 16))
+       const inputBytes = Uint8Array.from(inputArray)
+       const hash = blake2b().update(inputBytes).digest('hex')
        return hash
 }