Skip to content

Commit

Permalink
Merge pull request #3316 from ethereum/issue/3041
Browse files Browse the repository at this point in the history
Ensure '0x' prefix exists (web3-eth-accounts)
  • Loading branch information
nivida authored Jan 21, 2020
2 parents 332e638 + 1df8eba commit 7386be2
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 0 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -133,3 +133,7 @@ Released with 1.0.0-beta.37 code base.
### Added

- ENS module extended with the possibility to add a custom registry (#3301)

### Changed

- Ensure '0x' prefix is existing for Accounts.sign and Accounts.privateKeyToAccount (#3041)
8 changes: 8 additions & 0 deletions packages/web3-eth-accounts/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,10 @@ Accounts.prototype.create = function create(entropy) {
};

Accounts.prototype.privateKeyToAccount = function privateKeyToAccount(privateKey) {
if (!privateKey.startsWith('0x')) {
throw new Error('Required prefix "0x" is missing.');
}

return this._addAccountFunctions(Account.fromPrivate(privateKey));
};

Expand Down Expand Up @@ -294,6 +298,10 @@ Accounts.prototype.hashMessage = function hashMessage(data) {
};

Accounts.prototype.sign = function sign(data, privateKey) {
if (!privateKey.startsWith('0x')) {
throw new Error('Required prefix "0x" is missing for the given private key.');
}

var hash = this.hashMessage(data);
var signature = Account.sign(hash, privateKey);
var vrs = Account.decodeSignature(signature);
Expand Down
18 changes: 18 additions & 0 deletions test/eth.accounts.sign.js
Original file line number Diff line number Diff line change
Expand Up @@ -113,4 +113,22 @@ describe("eth", function () {
});
});
});

it('should throw an error if a PK got passed to Accounts.sign without a "0x" prefix', function () {
try {
new Accounts().sign('DATA', 'be6383dad004f233317e46ddb46ad31b16064d14447a95cc1d8c8d4bc61c3728');
assert.fail();
} catch(err) {
assert(err.message.includes('Required prefix "0x" is missing for the given private key.'));
}
});

it('should throw an error if a PK got passed to Accounts.privateKeyToAccount without a "0x" prefix', function () {
try {
new Accounts().privateKeyToAccount('be6383dad004f233317e46ddb46ad31b16064d14447a95cc1d8c8d4bc61c3728');
assert.fail();
} catch(err) {
assert(err.message.includes('Required prefix "0x" is missing.'));
}
});
});

0 comments on commit 7386be2

Please sign in to comment.