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 3 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
3 changes: 3 additions & 0 deletions packages/util/src/bytes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,9 @@ export const hexToBytes = (hex: string): Uint8Array => {
const bytes = new Uint8Array(byteLen)
for (let i = 0; i < byteLen; i++) {
const byte = parseInt(hex.slice(i * 2, (i + 1) * 2), 16)
if (Number.isNaN(byte)) {
throw 'Invalid hex'
}
bytes[i] = byte
}
return bytes
Expand Down
7 changes: 7 additions & 0 deletions packages/util/test/bytes.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -420,6 +420,13 @@ describe('hexToBytes', () => {
hexToBytes('aabbcc112233')
})
})

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

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