Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

util: check that hex to byte conversion is valid in hexToBytes #3185

Merged
merged 6 commits into from
Dec 12, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I like this approach better. Hopefully doesn't turn out to be a performance hit.

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
Loading