From 4e0f659f244a1cb95cfee113204059c4eb14f56d Mon Sep 17 00:00:00 2001 From: Erik Marks Date: Sun, 15 Aug 2021 12:47:21 -0700 Subject: [PATCH] Make padWithZeroes implementation less offensive --- src/index.test.ts | 15 ++++++++++++--- src/index.ts | 30 +++++++++++++++++++++++++----- 2 files changed, 37 insertions(+), 8 deletions(-) diff --git a/src/index.test.ts b/src/index.test.ts index 23e17d06..9c225ed8 100644 --- a/src/index.test.ts +++ b/src/index.test.ts @@ -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'; diff --git a/src/index.ts b/src/index.ts index 7e2cd0f0..536fd0fe 100644 --- a/src/index.ts +++ b/src/index.ts @@ -686,12 +686,32 @@ function getPublicKeyFor( 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