2017-08-07 20:25:23 -07:00
|
|
|
import EthTx from 'ethereumjs-tx';
|
2017-09-24 19:06:28 -07:00
|
|
|
import { ecsign, sha3 } from 'ethereumjs-util';
|
|
|
|
import { RawTransaction } from 'libs/transaction';
|
2017-08-07 20:25:23 -07:00
|
|
|
import { isValidRawTx } from 'libs/validators';
|
|
|
|
|
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');
|
|
|
|
}
|
|
|
|
|
|
|
|
export function signMessageWithPrivKey(
|
|
|
|
privKey: Buffer,
|
|
|
|
msg: string,
|
|
|
|
address: string,
|
|
|
|
date: string
|
|
|
|
): string {
|
2017-09-24 19:06:28 -07:00
|
|
|
const spacer = msg.length > 0 && date.length > 0 ? ' ' : '';
|
|
|
|
const fullMessage = msg + spacer + date;
|
|
|
|
const hash = sha3(fullMessage);
|
|
|
|
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
|
|
|
|
|
|
|
return JSON.stringify({
|
2017-09-24 19:06:28 -07:00
|
|
|
address,
|
2017-08-07 20:25:23 -07:00
|
|
|
msg: fullMessage,
|
|
|
|
sig: '0x' + combinedHex
|
|
|
|
});
|
|
|
|
}
|