From: Chris Duncan Date: Thu, 4 Dec 2025 13:33:26 +0000 (-0800) Subject: Simplify hex cast to bytes. X-Git-Url: https://git.codecow.com/?a=commitdiff_plain;h=7099b8076fd043fa694881deb5a82a4b118b1b10;p=libnemo.git Simplify hex cast to bytes. --- diff --git a/src/lib/crypto/secp256k1.ts b/src/lib/crypto/secp256k1.ts index 7dbff17..f6ea29d 100644 --- a/src/lib/crypto/secp256k1.ts +++ b/src/lib/crypto/secp256k1.ts @@ -155,20 +155,10 @@ export class Secp256k1 { } static hexToBytes (hex: string): Bytes { - const e = 'hex invalid' - if (typeof hex !== 'string') return this.err(e) - const hl = hex.length - const al = hl / 2 - if (hl % 2) return this.err(e) - const array = new Uint8Array(al) - for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) { - // treat each char as ASCII - const n1 = this._char(hex.charCodeAt(hi)) // parse first char, multiply it by 16 - const n2 = this._char(hex.charCodeAt(hi + 1)) // parse second char - if (n1 === undefined || n2 === undefined) return this.err(e) - array[ai] = n1 * 16 + n2 // example: 'A9' => 10*16 + 9 - } - return array + if (!/[0-9A-Fa-f]+/.test(hex ?? '')) return this.err('hex invalid') + if (hex.length % 2) hex = `0${hex}` + const intArray = hex.match(/.{2}/g)?.map(v => parseInt(v, 16)) + return new Uint8Array(intArray ?? []) } // prettier-ignore