aboutsummaryrefslogtreecommitdiffstats
path: root/src/ts/0x.js.ts
blob: acbdd01e2bc6020a74302e8af71dc0968b9ae920 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import * as BigNumber from 'bignumber.js';
import * as ethUtil from 'ethereumjs-util';
import {assert} from './utils/assert';

/**
 * Elliptic Curve signature
 */
export interface ECSignature {
    v: number;
    r: string;
    s: string;
}

export class ZeroEx {
    /**
     * Verifies that the elliptic curve signature `signature` was generated
     * by signing `data` with the private key corresponding to the `signer` address.
     */
    public static isValidSignature(data: string, signature: ECSignature, signer: ETHAddressHex): boolean {
        assert.isString('data', data);
        assert.isObject('signature', signature);
        assert.isETHAddressHex('signer', signer);

        const dataBuff = ethUtil.toBuffer(data);
        const msgHashBuff = ethUtil.hashPersonalMessage(dataBuff);
        try {
            const pubKey = ethUtil.ecrecover(msgHashBuff,
                signature.v,
                ethUtil.toBuffer(signature.r),
                ethUtil.toBuffer(signature.s));
            const retrievedAddress = ethUtil.bufferToHex(ethUtil.pubToAddress(pubKey));
            return retrievedAddress === signer;
        } catch (err) {
            return false;
        }
    }
}