UNPKG

2.46 kBPlain TextView Raw
1/**
2 * This file contains a compatability layer for some deprecated types and helper methods
3 *
4 * @prettier
5 */
6import * as utxolib from '@bitgo/utxo-lib';
7import * as bip32 from 'bip32';
8import { sanitizeLegacyPath } from '@bitgo/sdk-api';
9
10import * as bitcoinUtil from './bitcoin';
11
12interface ECPairCompat extends utxolib.ECPairInterface {
13 getPublicKeyBuffer(): Buffer;
14}
15
16function createECPairCompat(ecPair: utxolib.ECPairInterface): ECPairCompat {
17 return Object.assign(ecPair, {
18 getPublicKeyBuffer(): Buffer {
19 return ecPair.publicKey;
20 },
21 });
22}
23
24export function makeRandomKey(): ECPairCompat {
25 return createECPairCompat(bitcoinUtil.makeRandomKey());
26}
27
28/**
29 * Implementation of legacy "HDNode" class as used by certain components
30 */
31export class HDNode {
32 constructor(private bip32: bip32.BIP32Interface) {}
33
34 get publicKey(): Buffer {
35 return this.bip32.publicKey;
36 }
37
38 get privateKey(): Buffer | undefined {
39 return this.bip32.privateKey;
40 }
41
42 public static fromSeedBuffer(buf: Buffer): HDNode {
43 return new HDNode(bip32.fromSeed(buf));
44 }
45
46 public static fromBase58(str: string): HDNode {
47 return new HDNode(bip32.fromBase58(str));
48 }
49
50 public isNeutered(): boolean {
51 return this.bip32.isNeutered();
52 }
53
54 public neutered(): HDNode {
55 return new HDNode(this.bip32.neutered());
56 }
57
58 public toBase58(): string {
59 return this.bip32.toBase58();
60 }
61
62 public derivePath(p: string): HDNode {
63 return new HDNode(this.bip32.derivePath(sanitizeLegacyPath(p)));
64 }
65}
66
67export interface Derivable {
68 deriveKey(path: string): ECPairCompat;
69 derive(path: string): HDNode;
70}
71
72export function hdPath(hdNode: HDNode): Derivable {
73 return {
74 derive(path: string): HDNode {
75 return hdNode.derivePath(path);
76 },
77
78 deriveKey(path: string): ECPairCompat {
79 const node = hdNode.derivePath(path);
80 if (node.privateKey) {
81 return createECPairCompat(utxolib.ECPair.fromPrivateKey(node.privateKey));
82 } else {
83 return createECPairCompat(utxolib.ECPair.fromPublicKey(node.publicKey));
84 }
85 },
86 };
87}
88
89export const networks = utxolib.networks;
90
91export const address = {
92 fromBase58Check(addr: string): { hash: Buffer; version: number } {
93 return utxolib.address.fromBase58Check(addr, utxolib.networks.bitcoin);
94 },
95
96 toBase58Check(hash: Buffer, version: number): string {
97 return utxolib.address.toBase58Check(hash, version, utxolib.networks.bitcoin);
98 },
99};