Skip to content

Commit

Permalink
Make padWithZeroes implementation less offensive
Browse files Browse the repository at this point in the history
  • Loading branch information
rekmarks committed Aug 15, 2021
1 parent a8f7907 commit 4e0f659
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 8 deletions.
15 changes: 12 additions & 3 deletions src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1454,13 +1454,22 @@ describe('padWithZeroes', function () {
it('pads a string shorter than the target length with zeroes', function () {
const input = 'abc';
expect(sigUtil.padWithZeroes(input, 4)).toStrictEqual(`0${input}`);
})
});

it('returns a string longer than or equal to the target length without modifying it', function () {
const input = 'abc';
expect(sigUtil.padWithZeroes(input, 3)).toStrictEqual(input);
})
})
});

it('throws an error if passed an invalid hex string', function () {
const inputs = ['0xabc', 'xyz', '-'];
for (const input of inputs) {
expect(() => sigUtil.padWithZeroes(input, 3)).toThrow(
new Error(`Expected an unprefixed hex string. Received: ${input}`),
);
}
});
});

it('personalSign and recover', function () {
const address = '0x29c76e6ad8f28bb1004902578fb108c507be341b';
Expand Down
30 changes: 25 additions & 5 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -686,12 +686,32 @@ function getPublicKeyFor<T extends MessageTypes>(
return recoverPublicKey(msgHash, msgParams.sig);
}

export function padWithZeroes(number: string, length: number): string {
let myString = `${number}`;
while (myString.length < length) {
myString = `0${myString}`;
/**
* Pads the front of the given hex string with zeroes until it reaches the
* target length. If the input string is already longer than or equal to the
* target length, it is returned unmodified.
*
* If the input string is "0x"-prefixed or not a hex string, an error will be
* thrown.
*
* @param hexString The hexadecimal string to pad with zeroes.
* @param targetLength The target length of the hexadecimal string.
* @returns The input string front-padded with zeroes, or the original string
* if it was already greater than or equal to to the target length.
*/
export function padWithZeroes(hexString: string, targetLength: number): string {
if (!/^[a-f0-9]+$/iu.test(hexString)) {
throw new Error(
`Expected an unprefixed hex string. Received: ${hexString}`,
);
}

if (hexString.length < targetLength) {
return `${new Array(targetLength - hexString.length)
.fill(0)
.join()}${hexString}`;
}
return myString;
return hexString;
}

// converts hex strings to the Uint8Array format used by nacl
Expand Down

0 comments on commit 4e0f659

Please sign in to comment.