-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
103 lines (85 loc) · 2.22 KB
/
index.js
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
92
93
94
95
96
97
98
99
100
101
102
103
const EdDSA = require('elliptic').eddsa;
const base64url = require('base64url');
const ec = new EdDSA('ed25519');
const crc16 = require('crc16');
const initMnemonic = require('./mnemonicLib');
class Mnemonic {
constructor({ lazyLoad = false } = {}) {
if (!lazyLoad) {
this._initLib();
}
this.lib = () => {
this._initLib();
return this.mnemonicLib;
};
}
_initLib() {
if (typeof this.mnemonicLib === 'undefined') {
this.mnemonicLib = initMnemonic();
}
}
createMnemonic(mnemonicPassword = '') {
return new Promise((resolve, reject) => {
this.lib().create(mnemonicPassword, (res, err) => {
if (err == null) {
resolve(res);
} else {
reject(err);
}
});
});
}
getKeypairFromMnemonic(mnemonic, mnemonicPassword = '') {
let promise;
if (mnemonicPassword === '') {
promise = this.isBasicSeed(mnemonic);
} else {
promise = this.isPasswordSeed(mnemonic);
}
return promise.then((res) => {
if (!res) {
throw new Error('invalid mnemonic');
}
return new Promise((resolve, reject) => {
this.lib().getPrivateKey(mnemonic, mnemonicPassword, (res, err) => {
if (err == null) {
resolve(ec.keyFromSecret(res));
} else {
reject(err);
}
});
});
});
}
isBasicSeed(mnemonic) {
return new Promise((resolve, reject) => {
this.lib().isBasicSeed(mnemonic, (res, err) => {
if (err == null) {
resolve(res);
} else {
reject(err);
}
});
});
}
isPasswordSeed(mnemonic) {
return new Promise((resolve, reject) => {
this.lib().isPasswordSeed(mnemonic, (res, err) => {
if (err == null) {
resolve(res);
} else {
reject(err);
}
});
});
}
getPublicKeyInTonFormat(publicKey) {
const payload = Buffer.alloc(34);
payload.fill(0x3E, 0, 1);
payload.fill(0xE6, 1, 2);
payload.fill(Buffer.from(publicKey, 'hex'), 2);
const crc = crc16(payload);
return base64url(Buffer.concat([payload, Buffer.from(crc.toString(16).padStart(4, '0'), 'hex')]));
}
}
module.exports = Mnemonic;