Skip to content

Commit 6b01b50

Browse files
authored
fix: fromWifString error message ordering for invalid lengths (#51)
1 parent 2a1076d commit 6b01b50

2 files changed

Lines changed: 25 additions & 2 deletions

File tree

tests/wif.test.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import * as lib from '@exodus/bytes/wif.js'
2+
import { toBase58checkSync } from '@exodus/bytes/base58check.js'
23
import { randomValues } from '@exodus/crypto/randomBytes'
34
import { test } from 'node:test'
45
import assert from 'node:assert/strict'
@@ -73,3 +74,26 @@ test('sizes roundtrip, random data', async (t) => {
7374
}
7475
}
7576
})
77+
78+
test('invalid length throws before version check', async (t) => {
79+
// Regression test: length validation before version check
80+
// Old: threw "Invalid network version" for invalid length with wrong expectedVersion
81+
// New: throws "Invalid WIF length" regardless of expectedVersion
82+
83+
const invalidLengths = [0, 1, 4, 10, 32, 35, 50]
84+
85+
for (const len of invalidLengths) {
86+
const arr = new Uint8Array(len).fill(128)
87+
arr[0] = 42
88+
const encoded = toBase58checkSync(arr)
89+
const wrongVersion = 99
90+
91+
await t.assert.rejects(async () => lib.fromWifString(encoded, wrongVersion), {
92+
message: 'Invalid WIF length',
93+
})
94+
95+
t.assert.throws(() => lib.fromWifStringSync(encoded, wrongVersion), {
96+
message: 'Invalid WIF length',
97+
})
98+
}
99+
})

wif.js

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { assertUint8 } from './assert.js'
66

77
function from(arr, expectedVersion) {
88
assertUint8(arr)
9+
if (arr.length !== 33 && arr.length !== 34) throw new Error('Invalid WIF length')
910
const version = arr[0]
1011
if (expectedVersion !== undefined && version !== expectedVersion) {
1112
throw new Error('Invalid network version')
@@ -14,15 +15,13 @@ function from(arr, expectedVersion) {
1415
// Makes a copy, regardless of input being a Buffer or a Uint8Array (unlike .slice)
1516
const privateKey = Uint8Array.from(arr.subarray(1, 33))
1617
if (arr.length === 33) return { version, privateKey, compressed: false }
17-
if (arr.length !== 34) throw new Error('Invalid WIF length')
1818
if (arr[33] !== 1) throw new Error('Invalid compression flag')
1919
return { version, privateKey, compressed: true }
2020
}
2121

2222
function to({ version: v, privateKey, compressed }) {
2323
if (!Number.isSafeInteger(v) || v < 0 || v > 0xff) throw new Error('Missing or invalid version')
2424
assertUint8(privateKey, { length: 32, name: 'privateKey' })
25-
if (privateKey.length !== 32) throw new TypeError('Invalid privateKey length')
2625
const out = new Uint8Array(compressed ? 34 : 33)
2726
out[0] = v
2827
out.set(privateKey, 1)

0 commit comments

Comments
 (0)