1 |
|
2 | import { randomBytes, randomFillSync } from 'crypto'
|
3 | import { ECPair, address as baddress, crypto as bcrypto } from 'bitcoinjs-lib'
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 | export function getEntropy(arg: Buffer | number): Buffer {
|
12 | if (!arg) {
|
13 | arg = 32
|
14 | }
|
15 | if (typeof arg === 'number') {
|
16 | return randomBytes(arg)
|
17 | } else {
|
18 | return randomFillSync(arg)
|
19 | }
|
20 | }
|
21 |
|
22 |
|
23 |
|
24 |
|
25 | export function makeECPrivateKey() {
|
26 | const keyPair = ECPair.makeRandom({ rng: getEntropy })
|
27 | return keyPair.privateKey.toString('hex')
|
28 | }
|
29 |
|
30 |
|
31 |
|
32 |
|
33 | export function publicKeyToAddress(publicKey: string) {
|
34 | const publicKeyBuffer = Buffer.from(publicKey, 'hex')
|
35 | const publicKeyHash160 = bcrypto.hash160(publicKeyBuffer)
|
36 | const address = baddress.toBase58Check(publicKeyHash160, 0x00)
|
37 | return address
|
38 | }
|
39 |
|
40 |
|
41 |
|
42 |
|
43 | export function getPublicKeyFromPrivate(privateKey: string) {
|
44 | const keyPair = ECPair.fromPrivateKey(Buffer.from(privateKey, 'hex'))
|
45 | return keyPair.publicKey.toString('hex')
|
46 | }
|