Skip to content
This repository has been archived by the owner on Oct 7, 2024. It is now read-only.

Commit

Permalink
signMessage: add explicit input validation handling
Browse files Browse the repository at this point in the history
The library previously rejected non-hex-string data but relied on an
underlying library to throw the error.

This makes the validation explicit, and changes the type of the `data`
parameter of `signMessage` from `string` to `Hex` to reflect that.
  • Loading branch information
legobeat committed Sep 25, 2023
1 parent 60f7d5b commit 3782743
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 5 deletions.
6 changes: 3 additions & 3 deletions src/HDKeyring.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -605,7 +605,7 @@ describe('hd-keyring', () => {
const localMessage = 'hello there!';
const msgHashHex = bufferToHex(
Buffer.from(keccak256(Buffer.from(localMessage))),
);
) as Hex;
await keyring.addAccounts(9);
const addresses = await keyring.getAccounts();
const signatures = await Promise.all(
Expand Down Expand Up @@ -634,8 +634,8 @@ describe('hd-keyring', () => {
numberOfAccounts: 1,
});

await expect(keyring.signMessage(firstAcct, '')).rejects.toThrow(
'Cannot convert 0x to a BigInt',
await expect(keyring.signMessage(firstAcct, '' as Hex)).rejects.toThrow(
'Invalid input: data is not a hex string',
);
});

Expand Down
8 changes: 6 additions & 2 deletions src/HDKeyring.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@ import {
TypedDataV1,
TypedMessage,
} from '@metamask/eth-sig-util';
import { Hex, Keyring, Eip1024EncryptedData } from '@metamask/utils';
import type { Hex, Keyring, Eip1024EncryptedData } from '@metamask/utils';
import { isStrictHexString } from '@metamask/utils';
import { TxData, TypedTransaction } from '@ethereumjs/tx';
import { HDKeyringErrors } from './errors';

Expand Down Expand Up @@ -261,9 +262,12 @@ export class HDKeyring implements Keyring<SerializedHdKeyringState> {
// For eth_sign, we need to sign arbitrary data:
async signMessage(
address: Hex,
data: string,
data: Hex,
opts: KeyringOpt = {},
): Promise<string> {
if (!isStrictHexString(data)) {
throw new Error('Invalid input: data is not a hex string');
}
const message: string = stripHexPrefix(data);
const privKey: Uint8Array = this.#getPrivateKeyFor(address, opts);
const msgSig: ECDSASignature = ecsign(
Expand Down

0 comments on commit 3782743

Please sign in to comment.