ethereumjs / ethereumjs-wallet

Utilities for handling Ethereum keys
MIT License
986 stars 295 forks source link

fromPrivateKey issue #85

Open brightsider opened 5 years ago

brightsider commented 5 years ago

I can import wallet with privateKey + 1 random character. How to fix it?

let key = privateKey
if (key.startsWith('0x')) {
    key = key.substring(2)
}
let buf = Buffer.from(key, 'hex')
let result = ethereumjs.fromPrivateKey(buf)
let publicKey = '0x' + result.getAddress().toString('hex')
if (publicKey.toLowerCase() === address.toLowerCase()) {
    return privateKey
}
michaelsbradleyjr commented 5 years ago

This is owing to the behavior of Node's built in Buffer.from. In a Node REPL:

> Buffer.from('ff', 'hex')
<Buffer ff>
> Buffer.from('fF' + 'f', 'hex')
<Buffer ff>
> Buffer.from('ff' + 'Z', 'hex')
<Buffer ff>
> Buffer.from('ffpff', 'hex')
<Buffer ff>
> Buffer.from('Rffff', 'hex')
<Buffer >
> Buffer.from('frf', 'hex')
<Buffer >

That is, the function trims off the trailing character so that the input is the longest possible even number of hex characters. Note that Buffer.from also normalizes to lower case and the trimmed character/s may not even be valid hex. If the first two characters are not valid hex then you get an empty buffer, i.e. the same as Buffer.from('', 'hex').

There's nothing I see that ethereumjs-wallet can do to help in this situation since it's trimmed before fromPrivateKey is invoked.