1 | import * as utxolib from '@bitgo/utxo-lib';
|
2 | import * as _ from 'lodash';
|
3 | import * as bitcoinMessage from 'bitcoinjs-message';
|
4 | import * as bip32 from 'bip32';
|
5 |
|
6 |
|
7 |
|
8 |
|
9 | export function signMessage(
|
10 | message: string,
|
11 | privateKey: bip32.BIP32Interface | Buffer,
|
12 | network: { messagePrefix: string },
|
13 | ): Buffer {
|
14 | if (!Buffer.isBuffer(privateKey)) {
|
15 | privateKey = privateKey.privateKey as Buffer;
|
16 | if (!privateKey) {
|
17 | throw new Error(`must provide privateKey`);
|
18 | }
|
19 | }
|
20 | if (!_.isObject(network) || !_.isString(network.messagePrefix)) {
|
21 | throw new Error(`invalid argument 'network'`);
|
22 | }
|
23 | const compressed = true;
|
24 | return bitcoinMessage.sign(message, privateKey, compressed, network.messagePrefix);
|
25 | }
|
26 |
|
27 |
|
28 |
|
29 |
|
30 |
|
31 | export function verifyMessage(
|
32 | message: string,
|
33 | publicKey: bip32.BIP32Interface | Buffer,
|
34 | signature: Buffer,
|
35 | network: { messagePrefix: string },
|
36 | ): boolean {
|
37 | if (!Buffer.isBuffer(publicKey)) {
|
38 | publicKey = publicKey.publicKey;
|
39 | }
|
40 | if (!_.isObject(network) || !_.isString(network.messagePrefix)) {
|
41 | throw new Error(`invalid argument 'network'`);
|
42 | }
|
43 |
|
44 | const address = utxolib.address.toBase58Check(utxolib.crypto.hash160(publicKey), utxolib.networks.bitcoin.pubKeyHash, utxolib.networks.bitcoin);
|
45 | return bitcoinMessage.verify(message, address, signature, network.messagePrefix);
|
46 | }
|