Created
February 16, 2018 02:59
-
-
Save dominiek/d618d14a62f5f4318103e5e5176ed318 to your computer and use it in GitHub Desktop.
metamask_ethereum_signing.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For eth_sign, we need to sign arbitrary data: | |
signMessage (withAccount, data) { | |
const wallet = this._getWalletForAccount(withAccount) | |
const message = ethUtil.stripHexPrefix(data) | |
var privKey = wallet.getPrivateKey() | |
var msgSig = ethUtil.ecsign(new Buffer(message, 'hex'), privKey) | |
var rawMsgSig = ethUtil.bufferToHex(sigUtil.concatSig(msgSig.v, msgSig.r, msgSig.s)) | |
return Promise.resolve(rawMsgSig) | |
} | |
personalSign: function (privateKey, msgParams) { | |
var message = ethUtil.toBuffer(msgParams.data) | |
var msgHash = ethUtil.hashPersonalMessage(message) | |
var sig = ethUtil.ecsign(msgHash, privateKey) | |
var serialized = ethUtil.bufferToHex(this.concatSig(sig.v, sig.r, sig.s)) | |
return serialized | |
}, | |
/** | |
* Returns the keccak-256 hash of `message`, prefixed with the header used by the `eth_sign` RPC call. | |
* The output of this function can be fed into `ecsign` to produce the same signature as the `eth_sign` | |
* call for a given `message`, or fed to `ecrecover` along with a signature to recover the public key | |
* used to produce the signature. | |
* @param message | |
* @returns {Buffer} hash | |
*/ | |
exports.hashPersonalMessage = function (message) { | |
const prefix = exports.toBuffer('\u0019Ethereum Signed Message:\n' + message.length.toString()) | |
return exports.sha3(Buffer.concat([prefix, message])) | |
} | |
/** | |
* ECDSA sign | |
* @param {Buffer} msgHash | |
* @param {Buffer} privateKey | |
* @return {Object} | |
*/ | |
exports.ecsign = function (msgHash, privateKey) { | |
const sig = secp256k1.sign(msgHash, privateKey) | |
const ret = {} | |
ret.r = sig.signature.slice(0, 32) | |
ret.s = sig.signature.slice(32, 64) | |
ret.v = sig.recovery + 27 | |
return ret | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment