Skip to content

Commit 5df9819

Browse files
authored
fix: isHash accepting odd-length hex strings (#5042)
1 parent 11a1a86 commit 5df9819

3 files changed

Lines changed: 25 additions & 4 deletions

File tree

.changeset/is-hash-odd-length.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'viem': patch
3+
---
4+
5+
Fixed `isHash` returning `true` for odd-length hex strings. `size` rounds odd-length hex up to the next whole byte, so a 63-character hex string reported a size of 32 and passed the check. `isHash` now validates the length directly.

src/utils/hash/isHash.test.ts

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { expect, test } from 'vitest'
22

33
import { isHash } from './isHash.js'
44

5-
test('checks if address is valid', () => {
5+
test('checks if hash is valid', () => {
66
expect(isHash('0xa5cc3c03994db5b0d9a5eEdD10Cabab0813678ac')).toBeFalsy()
77
expect(isHash('0xa0cf798816d4b9b9866b5330eea46a18382f251e')).toBeFalsy()
88
expect(isHash('0xa5cc3c03994db5b0d9a5eEdD10Cabab0813678az')).toBeFalsy()
@@ -13,4 +13,21 @@ test('checks if address is valid', () => {
1313
'0x60fdd29ff912ce880cd3edaf9f932dc61d3dae823ea77e0323f94adb9f6a72fe',
1414
),
1515
).toBeTruthy()
16+
expect(
17+
isHash(
18+
'0x60FDD29FF912CE880CD3EDAF9F932DC61D3DAE823EA77E0323F94ADB9F6A72FE',
19+
),
20+
).toBeTruthy()
21+
})
22+
23+
test('checks length is exactly 32 bytes', () => {
24+
expect(isHash('')).toBeFalsy()
25+
expect(isHash('0x')).toBeFalsy()
26+
// 31.5 bytes: `size` rounds odd-length hex up to 32, so this used to pass.
27+
expect(isHash(`0x${'a'.repeat(63)}`)).toBeFalsy()
28+
expect(isHash(`0x${'a'.repeat(64)}`)).toBeTruthy()
29+
expect(isHash(`0x${'a'.repeat(65)}`)).toBeFalsy()
30+
expect(isHash(`0x${'a'.repeat(66)}`)).toBeFalsy()
31+
// 66 chars, but not hex.
32+
expect(isHash(`0x${'z'.repeat(64)}`)).toBeFalsy()
1633
})

src/utils/hash/isHash.ts

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,9 @@
11
import type { ErrorType } from '../../errors/utils.js'
22
import type { Hex } from '../../types/misc.js'
33
import { type IsHexErrorType, isHex } from '../data/isHex.js'
4-
import { type SizeErrorType, size } from '../data/size.js'
54

6-
export type IsHashErrorType = IsHexErrorType | SizeErrorType | ErrorType
5+
export type IsHashErrorType = IsHexErrorType | ErrorType
76

87
export function isHash(hash: string): hash is Hex {
9-
return isHex(hash) && size(hash) === 32
8+
return isHex(hash) && hash.length === 66
109
}

0 commit comments

Comments
 (0)