diff --git a/CHANGELOG.md b/CHANGELOG.md index 5626e4430fb..239cf0a4bfc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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) diff --git a/packages/web3-eth-accounts/src/index.js b/packages/web3-eth-accounts/src/index.js index 41400cef16b..3b34a9f8b73 100644 --- a/packages/web3-eth-accounts/src/index.js +++ b/packages/web3-eth-accounts/src/index.js @@ -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)); }; @@ -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); diff --git a/test/eth.accounts.sign.js b/test/eth.accounts.sign.js index a7b58645a73..14403670455 100644 --- a/test/eth.accounts.sign.js +++ b/test/eth.accounts.sign.js @@ -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.')); + } + }); });