1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 | import * as assert from 'assert';
|
16 | import * as bip32 from 'bip32';
|
17 | import * as secp256k1 from 'secp256k1';
|
18 | import * as utxolib from '@bitgo/utxo-lib';
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 | export function getSharedSecret(
|
27 | privateKey: bip32.BIP32Interface | utxolib.ECPair.ECPairInterface | Buffer,
|
28 | publicKey: bip32.BIP32Interface | Buffer
|
29 | ): Buffer {
|
30 | function isBIP32Interface(k: any): k is bip32.BIP32Interface {
|
31 | return k.constructor.name === 'BIP32';
|
32 | }
|
33 | function isECPairInterface(k: any): k is utxolib.ECPair.ECPairInterface {
|
34 | return k.constructor.name === 'ECPair';
|
35 | }
|
36 | if (isBIP32Interface(privateKey)) {
|
37 | if (!privateKey.privateKey) {
|
38 | throw new Error(`privateNode must be private key`);
|
39 | }
|
40 | privateKey = privateKey.privateKey;
|
41 | } else if (isECPairInterface(privateKey)) {
|
42 | if (privateKey.privateKey === undefined || !Buffer.isBuffer(privateKey.privateKey)) {
|
43 | throw new Error(`unexpected ECPair`);
|
44 | }
|
45 | privateKey = privateKey.privateKey;
|
46 | }
|
47 |
|
48 | if (!Buffer.isBuffer(publicKey)) {
|
49 | publicKey = publicKey.publicKey;
|
50 | }
|
51 |
|
52 | if (!Buffer.isBuffer(privateKey) || !Buffer.isBuffer(publicKey)) {
|
53 | throw new Error(`invalid state`);
|
54 | }
|
55 |
|
56 | assert.strictEqual(privateKey.length, 32);
|
57 | assert.strictEqual(publicKey.length, 33);
|
58 |
|
59 |
|
60 |
|
61 | const buffer = Buffer.from(secp256k1.publicKeyTweakMul(publicKey, privateKey))
|
62 |
|
63 | .slice(1);
|
64 | assert.strictEqual(buffer.length, 32);
|
65 | return buffer;
|
66 | }
|