Skip to content

Commit

Permalink
util: check that hex to byte conversion is valid in hexToBytes (#3185)
Browse files Browse the repository at this point in the history
* util: check that hex to byte conversion is valid in hexToBytes

* util: add test case for invalid hex

* util: add test case for invalid bytes (fails)

* util: add regex

* util: clarify error

---------

Co-authored-by: acolytec3 <[email protected]>
Co-authored-by: Jochem Brouwer <[email protected]>
  • Loading branch information
3 people authored Dec 12, 2023
1 parent de70612 commit 9698584
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 7 deletions.
14 changes: 7 additions & 7 deletions packages/util/src/bytes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,8 +87,8 @@ export const hexToBytes = (hex: string): Uint8Array => {
throw new Error(`hex argument type ${typeof hex} must be of type string`)
}

if (!hex.startsWith('0x')) {
throw new Error(`prefixed hex input should start with 0x, got ${hex.substring(0, 2)}`)
if (!/^0x[0-9a-fA-F]*$/.test(hex)) {
throw new Error(`Input must be a 0x-prefixed hexadecimal string, got ${hex}`)
}

hex = hex.slice(2)
Expand All @@ -97,11 +97,11 @@ export const hexToBytes = (hex: string): Uint8Array => {
hex = padToEven(hex)
}

const byteLen = hex.length / 2
const bytes = new Uint8Array(byteLen)
for (let i = 0; i < byteLen; i++) {
const byte = parseInt(hex.slice(i * 2, (i + 1) * 2), 16)
bytes[i] = byte
const byteLen = hex.length
const bytes = new Uint8Array(byteLen / 2)
for (let i = 0; i < byteLen; i += 2) {
const byte = parseInt(hex.slice(i, i + 2), 16)
bytes[i / 2] = byte
}
return bytes
}
Expand Down
10 changes: 10 additions & 0 deletions packages/util/test/bytes.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -420,6 +420,16 @@ describe('hexToBytes', () => {
hexToBytes('aabbcc112233')
})
})

it('should throw on invalid hex', () => {
assert.throws(() => {
hexToBytes('0xinvalidhexstring')
})
assert.throws(() => {
hexToBytes('0xfz')
})
})

it('should convert prefixed hex-strings', () => {
const converted = hexToBytes('0x1')
assert.deepEqual(converted, new Uint8Array([1]))
Expand Down

0 comments on commit 9698584

Please sign in to comment.