From 7b6378283c03d85d095500c92585095346c92fa8 Mon Sep 17 00:00:00 2001 From: Chris Duncan Date: Sat, 2 Aug 2025 22:40:12 -0700 Subject: [PATCH] Convert index to bytes with buffers instead of string manipulation. --- src/lib/blake2b-ckd.ts | 13 ++++++------- src/lib/blake2b.ts | 8 ++++---- 2 files changed, 10 insertions(+), 11 deletions(-) diff --git a/src/lib/blake2b-ckd.ts b/src/lib/blake2b-ckd.ts index b347a5e..7f75f07 100644 --- a/src/lib/blake2b-ckd.ts +++ b/src/lib/blake2b-ckd.ts @@ -2,7 +2,6 @@ //! SPDX-License-Identifier: GPL-3.0-or-later import { Blake2b } from '#src/lib/blake2b.js' -import { hex } from '#src/lib/convert.js' /** * Derives account private keys from a wallet seed using the BLAKE2b hashing @@ -14,15 +13,15 @@ import { hex } from '#src/lib/convert.js' * https://docs.nano.org/integration-guides/the-basics/ * * @param {ArrayBuffer} seed - 32-byte secret seed of the wallet -* @param {number} index - Account to derive +* @param {number} index - 4-byte index of account to derive * @returns {ArrayBuffer} Private key for the account */ export class Blake2bCkd { static ckd (seed: ArrayBuffer, index: number): ArrayBuffer { - return new Blake2b(32) - .update(new Uint8Array(seed)) - .update(hex.toBytes(index.toString(16).padStart(8, '0'))) - .digest() - .buffer + const b = new ArrayBuffer(4) + new DataView(b).setUint32(0, index, false) + const s = new Uint8Array(seed) + const i = new Uint8Array(b) + return new Blake2b(32).update(s).update(i).digest().buffer } } diff --git a/src/lib/blake2b.ts b/src/lib/blake2b.ts index 47c1297..319e73b 100644 --- a/src/lib/blake2b.ts +++ b/src/lib/blake2b.ts @@ -256,12 +256,12 @@ export class Blake2b { } } - update (input: Uint8Array): Blake2b { + update (input: Uint8Array): Blake2b { if (input instanceof ArrayBuffer) { input = new Uint8Array(input) } if (!(input instanceof Uint8Array)) { - throw new TypeError(`input must be Uint8Array or Buffer`) + throw new TypeError('Input must be Uint8Array or Buffer') } this.#blake2bUpdate(input) return this @@ -272,8 +272,8 @@ export class Blake2b { digest (out: 'binary' | Uint8Array): Uint8Array digest (out?: 'binary' | 'hex' | Uint8Array): string | Uint8Array { const buf = (!out || out === 'binary' || out === 'hex') ? new Uint8Array(this.#outlen) : out - if (!(buf instanceof Uint8Array)) throw new TypeError(`out must be "binary", "hex", Uint8Array, or Buffer`) - if (buf.length < this.#outlen) throw new RangeError(`out must have at least outlen bytes of space`) + if (!(buf instanceof Uint8Array)) throw new TypeError('out must be "binary", "hex", Uint8Array, or Buffer') + if (buf.length < this.#outlen) throw new RangeError('out must have at least outlen bytes of space') this.#blake2bFinal(buf) return (out === 'hex') ? Blake2b.#toHex(buf) -- 2.47.3