2017-08-07 20:25:23 -07:00
|
|
|
import EthTx from 'ethereumjs-tx';
|
2017-10-30 12:10:25 -07:00
|
|
|
import {
|
|
|
|
addHexPrefix,
|
|
|
|
ecsign,
|
|
|
|
ecrecover,
|
|
|
|
sha3,
|
|
|
|
hashPersonalMessage,
|
|
|
|
toBuffer,
|
|
|
|
pubToAddress
|
|
|
|
} from 'ethereumjs-util';
|
2017-09-24 19:06:28 -07:00
|
|
|
import { RawTransaction } from 'libs/transaction';
|
2017-08-07 20:25:23 -07:00
|
|
|
import { isValidRawTx } from 'libs/validators';
|
2017-10-30 12:10:25 -07:00
|
|
|
import { stripHexPrefixAndLower } from 'libs/values';
|
2017-08-07 20:25:23 -07:00
|
|
|
|
2017-08-11 14:54:10 -07:00
|
|
|
export function signRawTxWithPrivKey(
|
|
|
|
privKey: Buffer,
|
|
|
|
rawTx: RawTransaction
|
|
|
|
): string {
|
2017-08-07 20:25:23 -07:00
|
|
|
if (!isValidRawTx(rawTx)) {
|
|
|
|
throw new Error('Invalid raw transaction');
|
|
|
|
}
|
|
|
|
|
2017-09-24 19:06:28 -07:00
|
|
|
const eTx = new EthTx(rawTx);
|
2017-08-07 20:25:23 -07:00
|
|
|
eTx.sign(privKey);
|
|
|
|
return '0x' + eTx.serialize().toString('hex');
|
|
|
|
}
|
|
|
|
|
2017-10-30 12:10:25 -07:00
|
|
|
// adapted from:
|
|
|
|
// https://github.com/kvhnuke/etherwallet/blob/2a5bc0db1c65906b14d8c33ce9101788c70d3774/app/scripts/controllers/signMsgCtrl.js#L95
|
|
|
|
export function signMessageWithPrivKeyV2(privKey: Buffer, msg: string): string {
|
|
|
|
const hash = hashPersonalMessage(toBuffer(msg));
|
2017-09-24 19:06:28 -07:00
|
|
|
const signed = ecsign(hash, privKey);
|
|
|
|
const combined = Buffer.concat([
|
2017-08-07 20:25:23 -07:00
|
|
|
Buffer.from(signed.r),
|
|
|
|
Buffer.from(signed.s),
|
|
|
|
Buffer.from([signed.v])
|
|
|
|
]);
|
2017-09-24 19:06:28 -07:00
|
|
|
const combinedHex = combined.toString('hex');
|
2017-08-07 20:25:23 -07:00
|
|
|
|
2017-10-30 12:10:25 -07:00
|
|
|
return addHexPrefix(combinedHex);
|
|
|
|
}
|
|
|
|
|
|
|
|
export interface ISignedMessage {
|
|
|
|
address: string;
|
|
|
|
message: string;
|
|
|
|
signature: string;
|
|
|
|
version: string;
|
|
|
|
}
|
|
|
|
|
|
|
|
// adapted from:
|
|
|
|
// https://github.com/kvhnuke/etherwallet/blob/2a5bc0db1c65906b14d8c33ce9101788c70d3774/app/scripts/controllers/signMsgCtrl.js#L118
|
|
|
|
export function verifySignedMessage({
|
|
|
|
address,
|
|
|
|
message,
|
|
|
|
signature,
|
|
|
|
version
|
|
|
|
}: ISignedMessage) {
|
|
|
|
const sig = new Buffer(stripHexPrefixAndLower(signature), 'hex');
|
|
|
|
if (sig.length !== 65) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
//TODO: explain what's going on here
|
|
|
|
sig[64] = sig[64] === 0 || sig[64] === 1 ? sig[64] + 27 : sig[64];
|
|
|
|
const hash =
|
|
|
|
version === '2' ? hashPersonalMessage(toBuffer(message)) : sha3(message);
|
|
|
|
const pubKey = ecrecover(hash, sig[64], sig.slice(0, 32), sig.slice(32, 64));
|
|
|
|
|
|
|
|
return (
|
|
|
|
stripHexPrefixAndLower(address) === pubToAddress(pubKey).toString('hex')
|
|
|
|
);
|
2017-08-07 20:25:23 -07:00
|
|
|
}
|