]> git.codecow.com Git - libnemo.git/commitdiff
Simplify hex cast to bytes.
authorChris Duncan <chris@zoso.dev>
Thu, 4 Dec 2025 13:33:26 +0000 (05:33 -0800)
committerChris Duncan <chris@zoso.dev>
Thu, 4 Dec 2025 13:33:26 +0000 (05:33 -0800)
src/lib/crypto/secp256k1.ts

index 7dbff1783506d72953cbc40ce38c2d02478787b3..f6ea29d6de52b0f077cddc494c8a2439ae945f7e 100644 (file)
@@ -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