-
Notifications
You must be signed in to change notification settings - Fork 22
/
SeedKey.ts
91 lines (79 loc) 路 1.94 KB
/
SeedKey.ts
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
// Adapted from https://github.com/terra-money/terra-js/blob/master/src/utils/keyUtils.ts
import * as bip32 from 'bip32';
import * as bip39 from 'bip39';
import { RawKey } from './RawKey';
export const DEFAULT_COINTYPE = 330;
export interface SeedKeyOptions {
/**
* Buffer containing the seed.
*/
seed: Buffer;
/**
* BIP44 account number.
*/
account?: number;
/**
* BIP44 index number
*/
index?: number;
/**
* Coin type. Default is LUNA, 330.
*/
coinType?: number;
}
const DEFAULT_OPTIONS = {
account: 0,
index: 0,
coinType: DEFAULT_COINTYPE,
};
/**
* Implements a BIP39 mnemonic wallet with standard key derivation from a word list. Note
* that this implementation exposes the private key in memory, so it is not advised to use
* for applications requiring high security.
*/
export class SeedKey extends RawKey {
/**
* Buffer containing the seed.
*/
public seed: Buffer;
/**
* Creates a new signing key from a seed.
*
* ### Providing a seed
*
* ```ts
* import { SeedKey } from 'terra.js';
*
* const sk = new SeedKey({ seed: '...' });
* console.log(mk.accAddress);
* ```
*
* ### Generating a seed from a mnemonic
*
* ```ts
* const seed = SeedKey.seedFromMnemonic('...);
* console.log(seed);
* ```
*
* @param options
*/
constructor(options: SeedKeyOptions) {
const { account, index, coinType } = {
...DEFAULT_OPTIONS,
...options,
};
const { seed } = options;
const masterKey = bip32.fromSeed(seed);
const derivationPath = `m/44'/${coinType}'/${account}'/0/${index}`;
const hd = masterKey.derivePath(derivationPath);
const privateKey = hd.privateKey;
if (!privateKey) {
throw new Error('Failed to derive key pair');
}
super(privateKey, coinType === 60);
this.seed = seed;
}
public static seedFromMnemonic(mnemonic: string): Buffer {
return bip39.mnemonicToSeedSync(mnemonic);
}
}