From 91e38a9d93256dcda79f91440d74300f22b773b6 Mon Sep 17 00:00:00 2001 From: Chris Duncan Date: Fri, 8 Nov 2024 10:48:00 -0800 Subject: [PATCH] Revert promisification of serialize functions in BIP-32 ckd algorithm. Add type guards to serialization functions and log actual value instead of binary representation on errors. Simplify byte array construction and return now that convert methods accept padding values. --- src/lib/bip32-key-derivation.ts | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/src/lib/bip32-key-derivation.ts b/src/lib/bip32-key-derivation.ts index a622b99..3bff28a 100644 --- a/src/lib/bip32-key-derivation.ts +++ b/src/lib/bip32-key-derivation.ts @@ -39,33 +39,33 @@ async function slip10 (curve: string, S: string): Promise { async function CKDpriv ({ privateKey, chainCode }: ExtendedKey, index: number): Promise { const key = hex.toBytes(chainCode) - const data = hex.toBytes(`00${bytes.toHex(await ser256(privateKey))}${bytes.toHex(await ser32(index))}`) + const data = hex.toBytes(`00${bytes.toHex(ser256(privateKey))}${bytes.toHex(ser32(index))}`) const I = await hmac(key, data) const IL = I.slice(0, I.length / 2) const IR = I.slice(I.length / 2) return ({ privateKey: IL, chainCode: IR }) } -async function ser32 (integer: number): Promise { - const bits = integer.toString(2) +function ser32 (integer: number): Uint8Array { + if (typeof integer !== 'number') { + throw new TypeError(`Expected a number, received ${typeof integer}`) + } + const bits = dec.toBin(integer) if (bits.length > 32) { - throw new RangeError(`Expected 32-bit integer, received ${bits.length} bits: ${bits}`) + throw new RangeError(`Expected 32-bit integer, received ${bits.length}-bit value: ${integer}`) } - const bytes = dec.toBytes(integer) - const result = new Uint8Array(4) - result.set(bytes, 4 - bytes.length) - return result + return dec.toBytes(integer, 4) } -async function ser256 (integer: string): Promise { +function ser256 (integer: string): Uint8Array { + if (typeof integer !== 'string') { + throw new TypeError(`Expected string, received ${typeof integer}`) + } const bits = hex.toBin(integer) if (bits.length > 256) { - throw new RangeError(`Expected 256-bit integer, received ${bits.length} bits: ${bits}`) + throw new RangeError(`Expected 256-bit integer, received ${bits.length}-bit value: ${integer}`) } - const bytes = hex.toBytes(integer) - const result = new Uint8Array(32) - result.set(bytes, 32 - bytes.length) - return result + return hex.toBytes(integer, 32) } async function hmac (key: Uint8Array, data: Uint8Array): Promise { -- 2.34.1