@bitpay-labs/bitcore-client 11.5.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +131 -0
- package/bin/multi-sig/wallet-derive-address +149 -0
- package/bin/wallet +31 -0
- package/bin/wallet-balance +62 -0
- package/bin/wallet-balance-all +77 -0
- package/bin/wallet-broadcast +35 -0
- package/bin/wallet-bump-tx +65 -0
- package/bin/wallet-check +62 -0
- package/bin/wallet-create +46 -0
- package/bin/wallet-decrypt +31 -0
- package/bin/wallet-delete +21 -0
- package/bin/wallet-derive +70 -0
- package/bin/wallet-flags +84 -0
- package/bin/wallet-import +80 -0
- package/bin/wallet-list +31 -0
- package/bin/wallet-paypro +175 -0
- package/bin/wallet-register +29 -0
- package/bin/wallet-send +146 -0
- package/bin/wallet-sign +64 -0
- package/bin/wallet-sign-message +55 -0
- package/bin/wallet-storage +79 -0
- package/bin/wallet-token +73 -0
- package/bin/wallet-token-rm +33 -0
- package/bin/wallet-tx +106 -0
- package/bin/wallet-tx-list +92 -0
- package/bin/wallet-utxos +28 -0
- package/package.json +71 -0
- package/src/client.ts +271 -0
- package/src/encryption.ts +139 -0
- package/src/index.ts +21 -0
- package/src/storage/level.ts +171 -0
- package/src/storage/mongo.ts +187 -0
- package/src/storage/textFile.ts +250 -0
- package/src/storage.ts +192 -0
- package/src/stream-util.ts +80 -0
- package/src/types/index.d.ts +2 -0
- package/src/types/storage.d.ts +1 -0
- package/src/types/wallet.d.ts +36 -0
- package/src/utils.ts +35 -0
- package/src/wallet.ts +983 -0
- package/test/unit/wallet.test.ts +552 -0
- package/ts_build/src/client.d.ts +77 -0
- package/ts_build/src/client.d.ts.map +1 -0
- package/ts_build/src/client.js +280 -0
- package/ts_build/src/client.js.map +1 -0
- package/ts_build/src/encryption.d.ts +27 -0
- package/ts_build/src/encryption.d.ts.map +1 -0
- package/ts_build/src/encryption.js +130 -0
- package/ts_build/src/encryption.js.map +1 -0
- package/ts_build/src/index.d.ts +11 -0
- package/ts_build/src/index.d.ts.map +1 -0
- package/ts_build/src/index.js +55 -0
- package/ts_build/src/index.js.map +1 -0
- package/ts_build/src/storage/level.d.ts +48 -0
- package/ts_build/src/storage/level.d.ts.map +1 -0
- package/ts_build/src/storage/level.js +194 -0
- package/ts_build/src/storage/level.js.map +1 -0
- package/ts_build/src/storage/mongo.d.ts +62 -0
- package/ts_build/src/storage/mongo.d.ts.map +1 -0
- package/ts_build/src/storage/mongo.js +173 -0
- package/ts_build/src/storage/mongo.js.map +1 -0
- package/ts_build/src/storage/textFile.d.ts +53 -0
- package/ts_build/src/storage/textFile.d.ts.map +1 -0
- package/ts_build/src/storage/textFile.js +268 -0
- package/ts_build/src/storage/textFile.js.map +1 -0
- package/ts_build/src/storage.d.ts +63 -0
- package/ts_build/src/storage.d.ts.map +1 -0
- package/ts_build/src/storage.js +172 -0
- package/ts_build/src/storage.js.map +1 -0
- package/ts_build/src/stream-util.d.ts +15 -0
- package/ts_build/src/stream-util.d.ts.map +1 -0
- package/ts_build/src/stream-util.js +81 -0
- package/ts_build/src/stream-util.js.map +1 -0
- package/ts_build/src/utils.d.ts +8 -0
- package/ts_build/src/utils.d.ts.map +1 -0
- package/ts_build/src/utils.js +37 -0
- package/ts_build/src/utils.js.map +1 -0
- package/ts_build/src/wallet.d.ts +229 -0
- package/ts_build/src/wallet.d.ts.map +1 -0
- package/ts_build/src/wallet.js +806 -0
- package/ts_build/src/wallet.js.map +1 -0
- package/ts_build/test/unit/wallet.test.d.ts +2 -0
- package/ts_build/test/unit/wallet.test.d.ts.map +1 -0
- package/ts_build/test/unit/wallet.test.js +533 -0
- package/ts_build/test/unit/wallet.test.js.map +1 -0
- package/tsconfig.json +40 -0
- package/tsconfig.prod.json +6 -0
package/src/client.ts
ADDED
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
import { URL } from 'url';
|
|
2
|
+
import { BitcoreLib } from '@bitpay-labs/crypto-wallet-core';
|
|
3
|
+
import requestStream from 'request';
|
|
4
|
+
import request from 'request-promise-native';
|
|
5
|
+
import * as secp256k1 from 'secp256k1';
|
|
6
|
+
import { utils } from './utils';
|
|
7
|
+
|
|
8
|
+
const usingBrowser = (global as any).window;
|
|
9
|
+
const URLClass = usingBrowser ? usingBrowser.URL : URL;
|
|
10
|
+
export class Client {
|
|
11
|
+
apiUrl: string;
|
|
12
|
+
authKey: any;
|
|
13
|
+
|
|
14
|
+
constructor(params: {
|
|
15
|
+
apiUrl: string;
|
|
16
|
+
authKey: BitcoreLib.PrivateKey;
|
|
17
|
+
}) {
|
|
18
|
+
this.apiUrl = params.apiUrl;
|
|
19
|
+
this.authKey = params.authKey;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
async _request(params: request.OptionsWithUrl) {
|
|
23
|
+
try {
|
|
24
|
+
return await request(params);
|
|
25
|
+
} catch (err) {
|
|
26
|
+
if (err.statusCode) {
|
|
27
|
+
throw new Error(`${err.statusCode} - ${params.method}: ${params.url} - "${JSON.stringify(err.error)}"`);
|
|
28
|
+
} else if (err.error instanceof Error) {
|
|
29
|
+
throw err.error;
|
|
30
|
+
}
|
|
31
|
+
throw err;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
_buildQueryString( params: any) {
|
|
36
|
+
const query = [];
|
|
37
|
+
for (const [key, value] of Object.entries(params)) {
|
|
38
|
+
value && query.push(`${key}=${value}`);
|
|
39
|
+
}
|
|
40
|
+
return query.length ? `?${query.join('&')}` : '';
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
getMessage(params: { method: string; url: string; payload?: any }) {
|
|
44
|
+
const { method, url, payload = {} } = params;
|
|
45
|
+
const parsedUrl = new URLClass(url);
|
|
46
|
+
return [method, parsedUrl.pathname + parsedUrl.search, JSON.stringify(payload)].join('|');
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
sign(params: { method: string; url: string; payload?: any }) {
|
|
50
|
+
const message = this.getMessage(params);
|
|
51
|
+
const privateKey = this.authKey.toBuffer();
|
|
52
|
+
const messageHash = BitcoreLib.crypto.Hash.sha256sha256(Buffer.from(message));
|
|
53
|
+
return secp256k1.sign(messageHash, privateKey).signature.toString('hex');
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
async register(params: { payload: { baseUrl?: string } & any }) {
|
|
57
|
+
const { payload } = params;
|
|
58
|
+
// allow you to overload the client's baseUrl
|
|
59
|
+
const { baseUrl = this.apiUrl } = payload;
|
|
60
|
+
const url = `${baseUrl}/wallet`;
|
|
61
|
+
const signature = this.sign({ method: 'POST', url, payload });
|
|
62
|
+
return this._request({
|
|
63
|
+
method: 'POST',
|
|
64
|
+
url,
|
|
65
|
+
headers: { 'x-signature': signature },
|
|
66
|
+
body: payload,
|
|
67
|
+
json: true
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
async getToken(contractAddress) {
|
|
72
|
+
const url = `${this.apiUrl}/token/${contractAddress}`;
|
|
73
|
+
return this._request({ method: 'GET', url, json: true });
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
async getSolanaTokens(address) {
|
|
77
|
+
const url = `${this.apiUrl}/ata/${address}`;
|
|
78
|
+
return this._request({ method: 'GET', url, json: true });
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async getBalance(params: { payload?: any; pubKey: string; time?: string; address?: string; hex?: boolean }) {
|
|
82
|
+
const { payload, pubKey, time, address, hex } = params;
|
|
83
|
+
let url = `${this.apiUrl}/wallet/${pubKey}/balance`;
|
|
84
|
+
if (time) {
|
|
85
|
+
url += `/${time}`;
|
|
86
|
+
}
|
|
87
|
+
const query = [];
|
|
88
|
+
if (payload?.tokenContractAddress) {
|
|
89
|
+
query.push(`tokenAddress=${payload.tokenContractAddress}`);
|
|
90
|
+
}
|
|
91
|
+
if (address) {
|
|
92
|
+
query.push(`address=${address}`);
|
|
93
|
+
}
|
|
94
|
+
if (hex) {
|
|
95
|
+
query.push('hex=true');
|
|
96
|
+
}
|
|
97
|
+
url += query.length ? `?${query.join('&')}` : '';
|
|
98
|
+
const signature = this.sign({ method: 'GET', url });
|
|
99
|
+
return this._request({
|
|
100
|
+
method: 'GET',
|
|
101
|
+
url,
|
|
102
|
+
headers: { 'x-signature': signature },
|
|
103
|
+
json: true
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
async getTransaction(params: { txid: string; populated?: boolean }) {
|
|
108
|
+
const { txid, populated } = params;
|
|
109
|
+
const url = `${this.apiUrl}/tx/${txid}${populated ? '/populated' : ''}`;
|
|
110
|
+
return this._request({ method: 'GET', url, json: true });
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
async getNonce(params) {
|
|
114
|
+
const { address } = params;
|
|
115
|
+
const url = `${this.apiUrl}/address/${address}/txs/count`;
|
|
116
|
+
return this._request({ method: 'GET', url, json: true });
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
getAddressTxos = async function(params) {
|
|
120
|
+
const { unspent, address } = params;
|
|
121
|
+
const args = unspent ? `?unspent=${unspent}` : '';
|
|
122
|
+
const url = `${this.apiUrl}/address/${address}${args}`;
|
|
123
|
+
return this._request({ method: 'GET', url, json: true });
|
|
124
|
+
};
|
|
125
|
+
|
|
126
|
+
getCoins(params: { payload?: any; pubKey: string; includeSpent: boolean }) {
|
|
127
|
+
const { payload, pubKey, includeSpent } = params;
|
|
128
|
+
const url = `${this.apiUrl}/wallet/${pubKey}/utxos?includeSpent=${includeSpent}`;
|
|
129
|
+
const signature = this.sign({ method: 'GET', url, payload });
|
|
130
|
+
return requestStream.get(url, {
|
|
131
|
+
headers: { 'x-signature': signature },
|
|
132
|
+
body: payload,
|
|
133
|
+
json: true
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
listTransactions(params) {
|
|
138
|
+
const { pubKey, startBlock, startDate, endBlock, endDate, includeMempool, payload, tokenContractAddress, limit } = params;
|
|
139
|
+
let url = `${this.apiUrl}/wallet/${pubKey}/transactions`;
|
|
140
|
+
let query = '';
|
|
141
|
+
if (startBlock) {
|
|
142
|
+
query += `startBlock=${startBlock}&`;
|
|
143
|
+
}
|
|
144
|
+
if (endBlock) {
|
|
145
|
+
query += `endBlock=${endBlock}&`;
|
|
146
|
+
}
|
|
147
|
+
if (startDate) {
|
|
148
|
+
query += `startDate=${startDate}&`;
|
|
149
|
+
}
|
|
150
|
+
if (endDate) {
|
|
151
|
+
query += `endDate=${endDate}&`;
|
|
152
|
+
}
|
|
153
|
+
if (includeMempool) {
|
|
154
|
+
query += 'includeMempool=true&';
|
|
155
|
+
}
|
|
156
|
+
if (tokenContractAddress) {
|
|
157
|
+
query += `tokenAddress=${tokenContractAddress}&`;
|
|
158
|
+
}
|
|
159
|
+
if (limit) {
|
|
160
|
+
query += `limit=${limit}&`;
|
|
161
|
+
}
|
|
162
|
+
query = query.endsWith('&') ? query.slice(0, -1) : query;
|
|
163
|
+
if (query) {
|
|
164
|
+
url += '?' + query;
|
|
165
|
+
}
|
|
166
|
+
const signature = this.sign({ method: 'GET', url, payload });
|
|
167
|
+
return requestStream.get(url, {
|
|
168
|
+
headers: { 'x-signature': signature },
|
|
169
|
+
body: payload,
|
|
170
|
+
json: true
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
async getFee(params) {
|
|
175
|
+
const { target, txType } = params;
|
|
176
|
+
const url = `${this.apiUrl}/fee/${target}${this._buildQueryString({ txType })}`;
|
|
177
|
+
const result = await this._request({ method: 'GET', url, json: true });
|
|
178
|
+
if (result.errors?.length) {
|
|
179
|
+
throw new Error(result.errors[0]);
|
|
180
|
+
}
|
|
181
|
+
return result;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
async getPriorityFee(params) {
|
|
185
|
+
const { percentile } = params;
|
|
186
|
+
const url = `${this.apiUrl}/priorityFee/${percentile}`;
|
|
187
|
+
const result = await this._request({ method: 'GET', url, json: true });
|
|
188
|
+
if (result.errors?.length) {
|
|
189
|
+
throw new Error(result.errors[0]);
|
|
190
|
+
}
|
|
191
|
+
return result;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
async importAddresses(params: { pubKey: string; payload: Array<{ address: string }> }): Promise<void> {
|
|
195
|
+
const { payload, pubKey } = params;
|
|
196
|
+
const url = `${this.apiUrl}/wallet/${pubKey}`;
|
|
197
|
+
|
|
198
|
+
for (let i = 0; i < payload.length; i += 100) {
|
|
199
|
+
const body = payload.slice(i, i + 100);
|
|
200
|
+
console.log(`Importing addresses ${i + 1}-${i + body.length} of ${payload.length}`);
|
|
201
|
+
if (i >= 100) {
|
|
202
|
+
await utils.sleep(1000); // cooldown
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const signature = this.sign({ method: 'POST', url, payload: body });
|
|
206
|
+
|
|
207
|
+
await this._request({
|
|
208
|
+
method: 'POST',
|
|
209
|
+
url,
|
|
210
|
+
headers: { 'x-signature': signature },
|
|
211
|
+
body,
|
|
212
|
+
json: true
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
async broadcast(params) {
|
|
218
|
+
const { payload } = params;
|
|
219
|
+
const url = `${this.apiUrl}/tx/send`;
|
|
220
|
+
return this._request({ method: 'POST', url, body: payload, json: true });
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
async checkWallet(params) {
|
|
224
|
+
const { pubKey } = params;
|
|
225
|
+
const url = `${this.apiUrl}/wallet/${pubKey}/check`;
|
|
226
|
+
const signature = this.sign({ method: 'GET', url });
|
|
227
|
+
return this._request({
|
|
228
|
+
method: 'GET',
|
|
229
|
+
url,
|
|
230
|
+
headers: { 'x-signature': signature },
|
|
231
|
+
json: true
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
getAddresses(params: { pubKey: string }) {
|
|
236
|
+
const { pubKey } = params;
|
|
237
|
+
const url = `${this.apiUrl}/wallet/${pubKey}/addresses`;
|
|
238
|
+
const signature = this.sign({ method: 'GET', url });
|
|
239
|
+
return this._request({
|
|
240
|
+
method: 'GET',
|
|
241
|
+
url,
|
|
242
|
+
headers: { 'x-signature': signature },
|
|
243
|
+
json: true
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
getAccountFlags(params: { address: string }) {
|
|
248
|
+
const { address } = params;
|
|
249
|
+
const url = `${this.apiUrl}/address/${address}/flags`;
|
|
250
|
+
return this._request({ method: 'GET', url, json: true });
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
estimateGas(params: { to: string; from: string; data: string; value: string }) {
|
|
254
|
+
const { to, from, data, value } = params;
|
|
255
|
+
const body = { to, from, data, value };
|
|
256
|
+
const url = `${this.apiUrl}/gas`;
|
|
257
|
+
return this._request({ method: 'POST', url, json: true, body });
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
getL1Fee(params: { rawTx: string; safe?: boolean }) {
|
|
261
|
+
const { rawTx, safe } = params;
|
|
262
|
+
const body = { rawTx };
|
|
263
|
+
const url = `${this.apiUrl}/l1/fee${safe ? '?safe=true' : ''}`;
|
|
264
|
+
return this._request({ method: 'POST', url, json: true, body });
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
getBlockTip() {
|
|
268
|
+
const url = `${this.apiUrl}/block/tip`;
|
|
269
|
+
return this._request({ method: 'GET', url, json: true });
|
|
270
|
+
}
|
|
271
|
+
}
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import crypto from 'crypto';
|
|
2
|
+
import { BitcoreLib as bitcore } from '@bitpay-labs/crypto-wallet-core';
|
|
3
|
+
|
|
4
|
+
export function shaHash(data, algo = 'sha256') {
|
|
5
|
+
const hash = crypto
|
|
6
|
+
.createHash(algo)
|
|
7
|
+
.update(data, 'utf8')
|
|
8
|
+
.digest('hex')
|
|
9
|
+
.toUpperCase();
|
|
10
|
+
return hash;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
const SHA512 = data => shaHash(data, 'sha512');
|
|
14
|
+
const SHA256 = data => shaHash(data, 'sha256');
|
|
15
|
+
const algo = 'aes-256-cbc';
|
|
16
|
+
|
|
17
|
+
export function encryptEncryptionKey(encryptionKey, password) {
|
|
18
|
+
const password_hash = Buffer.from(SHA512(password));
|
|
19
|
+
const key = password_hash.subarray(0, 32);
|
|
20
|
+
const iv = password_hash.subarray(32, 48);
|
|
21
|
+
const cipher = crypto.createCipheriv(algo, key, iv);
|
|
22
|
+
const encData = cipher.update(encryptionKey, 'hex', 'hex') + cipher.final('hex');
|
|
23
|
+
return encData;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function decryptEncryptionKey(encEncryptionKey, password) {
|
|
27
|
+
const password_hash = Buffer.from(SHA512(password));
|
|
28
|
+
const key = password_hash.subarray(0, 32);
|
|
29
|
+
const iv = password_hash.subarray(32, 48);
|
|
30
|
+
const decipher = crypto.createDecipheriv(algo, key, iv);
|
|
31
|
+
const decrypted = decipher.update(encEncryptionKey, 'hex', 'hex' as any) + decipher.final('hex');
|
|
32
|
+
return decrypted;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function encryptPrivateKey(privKey, pubKey, encryptionKey) {
|
|
36
|
+
const key = Buffer.from(encryptionKey, 'hex');
|
|
37
|
+
const doubleHash = Buffer.from(SHA256(SHA256(pubKey)), 'hex');
|
|
38
|
+
const iv = doubleHash.subarray(0, 16);
|
|
39
|
+
const cipher = crypto.createCipheriv(algo, key, iv);
|
|
40
|
+
const encData = cipher.update(privKey, 'utf8', 'hex') + cipher.final('hex');
|
|
41
|
+
return encData;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function decryptPrivateKey(encPrivateKey: string, pubKey: string, encryptionKey: string) {
|
|
45
|
+
const key = Buffer.from(encryptionKey, 'hex');
|
|
46
|
+
const doubleHash = Buffer.from(SHA256(SHA256(pubKey)), 'hex');
|
|
47
|
+
const iv = doubleHash.subarray(0, 16);
|
|
48
|
+
const decipher = crypto.createDecipheriv(algo, key, iv);
|
|
49
|
+
const decrypted = decipher.update(encPrivateKey, 'hex', 'utf8') + decipher.final('utf8');
|
|
50
|
+
return decrypted;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function sha512KDF(passphrase: string, salt: Buffer, derivationOptions: { rounds?: number }): string {
|
|
54
|
+
const rounds = derivationOptions.rounds || 1;
|
|
55
|
+
// if salt was sent in as a string, we will have to assume the default encoding type
|
|
56
|
+
if (!Buffer.isBuffer(salt)) {
|
|
57
|
+
salt = Buffer.from(salt, 'hex');
|
|
58
|
+
}
|
|
59
|
+
let derivation: Buffer<ArrayBufferLike> = Buffer.concat([Buffer.from(''), Buffer.from(passphrase), salt]);
|
|
60
|
+
for (let i = 0; i < rounds; i++) {
|
|
61
|
+
derivation = crypto
|
|
62
|
+
.createHash('sha512')
|
|
63
|
+
.update(derivation)
|
|
64
|
+
.digest();
|
|
65
|
+
}
|
|
66
|
+
return derivation.toString('hex');
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function bitcoinCoreDecrypt(
|
|
70
|
+
jsonl: Array<{
|
|
71
|
+
cipherText?: string;
|
|
72
|
+
derivationMethod?: string;
|
|
73
|
+
rounds?: number;
|
|
74
|
+
salt?: Buffer;
|
|
75
|
+
pubKey?: string;
|
|
76
|
+
address?: string;
|
|
77
|
+
}>,
|
|
78
|
+
passphrase: string
|
|
79
|
+
) {
|
|
80
|
+
const derivationMethods = { SHA512: 0 };
|
|
81
|
+
let master = null;
|
|
82
|
+
const jsonlDecrypted = [];
|
|
83
|
+
for (const line of jsonl) {
|
|
84
|
+
const cipherText = line.cipherText;
|
|
85
|
+
if (line.derivationMethod) {
|
|
86
|
+
const salt = line.salt;
|
|
87
|
+
const derivationOptions = {
|
|
88
|
+
method: derivationMethods[line.derivationMethod],
|
|
89
|
+
rounds: line.rounds
|
|
90
|
+
};
|
|
91
|
+
// derive the key from passphrase
|
|
92
|
+
const key = sha512KDF(passphrase, salt, derivationOptions);
|
|
93
|
+
master = decrypt({ cipherText, key });
|
|
94
|
+
} else {
|
|
95
|
+
const privKey = decrypt({
|
|
96
|
+
key: master,
|
|
97
|
+
iv: bitcore.crypto.Hash.sha256sha256(Buffer.from(line.pubKey, 'hex')),
|
|
98
|
+
cipherText
|
|
99
|
+
});
|
|
100
|
+
const address = line.address.split(':');
|
|
101
|
+
const keyObj = {
|
|
102
|
+
privKey,
|
|
103
|
+
pubKey: line.pubKey,
|
|
104
|
+
address: address[address.length - 1]
|
|
105
|
+
};
|
|
106
|
+
jsonlDecrypted.push(keyObj);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
return { jsonlDecrypted, master };
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function decrypt(opts: { key?: string; iv?: Buffer | string; cipherText?: string }) {
|
|
113
|
+
const key = Buffer.from(opts.key, 'hex');
|
|
114
|
+
let secondHalf;
|
|
115
|
+
if (opts.iv) {
|
|
116
|
+
secondHalf = opts.iv.slice(0, 16);
|
|
117
|
+
} else {
|
|
118
|
+
secondHalf = key.subarray(32, 48); // AES256-cbc IV
|
|
119
|
+
}
|
|
120
|
+
const cipherText = Buffer.from(opts.cipherText, 'hex');
|
|
121
|
+
const firstHalf = key.subarray(0, 32); // AES256-cbc shared key
|
|
122
|
+
const AESDecipher = crypto.createDecipheriv(algo, firstHalf, secondHalf);
|
|
123
|
+
const plainText = Buffer.concat([AESDecipher.update(cipherText), AESDecipher.final()]).toString('hex');
|
|
124
|
+
|
|
125
|
+
return plainText;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export function generateEncryptionKey() {
|
|
129
|
+
return crypto.randomBytes(32);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export const Encryption = {
|
|
133
|
+
encryptEncryptionKey,
|
|
134
|
+
decryptEncryptionKey,
|
|
135
|
+
encryptPrivateKey,
|
|
136
|
+
decryptPrivateKey,
|
|
137
|
+
generateEncryptionKey,
|
|
138
|
+
bitcoinCoreDecrypt
|
|
139
|
+
};
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import 'source-map-support/register';
|
|
2
|
+
import * as CryptoWalletCore from '@bitpay-labs/crypto-wallet-core';
|
|
3
|
+
import { Client } from './client';
|
|
4
|
+
import { Encryption } from './encryption';
|
|
5
|
+
import { Storage } from './storage';
|
|
6
|
+
import { ParseApiStream, StreamUtil } from './stream-util';
|
|
7
|
+
import { Wallet } from './wallet';
|
|
8
|
+
|
|
9
|
+
export * from './wallet';
|
|
10
|
+
export {
|
|
11
|
+
Wallet,
|
|
12
|
+
Client,
|
|
13
|
+
Storage,
|
|
14
|
+
ParseApiStream,
|
|
15
|
+
Encryption,
|
|
16
|
+
StreamUtil,
|
|
17
|
+
CryptoWalletCore
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
// Types
|
|
21
|
+
export type * as Types from './types';
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
import * as fs from 'fs';
|
|
2
|
+
import * as os from 'os';
|
|
3
|
+
import { Transform } from 'stream';
|
|
4
|
+
import leveldn from 'leveldown';
|
|
5
|
+
import levelup, { LevelUp } from 'levelup';
|
|
6
|
+
|
|
7
|
+
const usingBrowser = 'window' in globalThis;
|
|
8
|
+
const StorageCache: { [path: string]: LevelUp } = {};
|
|
9
|
+
|
|
10
|
+
export class Level {
|
|
11
|
+
path: string;
|
|
12
|
+
db: LevelUp;
|
|
13
|
+
|
|
14
|
+
constructor(params: { path?: string; createIfMissing: boolean; errorIfExists: boolean }) {
|
|
15
|
+
const { path, createIfMissing, errorIfExists } = params;
|
|
16
|
+
let basePath;
|
|
17
|
+
if (!path) {
|
|
18
|
+
basePath = `${os.homedir()}/.bitcore`;
|
|
19
|
+
try {
|
|
20
|
+
if (!usingBrowser) {
|
|
21
|
+
fs.mkdirSync(basePath);
|
|
22
|
+
}
|
|
23
|
+
} catch (e) {
|
|
24
|
+
if (e.errno !== -17) {
|
|
25
|
+
console.error('Unable to create bitcore storage directory');
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
this.path = path || `${basePath}/bitcoreWallet`;
|
|
30
|
+
if (!createIfMissing && !usingBrowser) {
|
|
31
|
+
const walletExists =
|
|
32
|
+
fs.existsSync(this.path) && fs.existsSync(this.path + '/LOCK') && fs.existsSync(this.path + '/LOG');
|
|
33
|
+
if (!walletExists) {
|
|
34
|
+
throw new Error('Not a valid wallet path');
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
if (StorageCache[this.path]) {
|
|
38
|
+
this.db = StorageCache[this.path];
|
|
39
|
+
} else {
|
|
40
|
+
console.log('using wallets at', this.path);
|
|
41
|
+
this.db = StorageCache[this.path] = levelup(leveldn(this.path), {
|
|
42
|
+
createIfMissing,
|
|
43
|
+
errorIfExists
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
async loadWallet(params: { name: string }) {
|
|
49
|
+
const { name } = params;
|
|
50
|
+
return (await this.db.get(`wallet|${name}`)) as string;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
async deleteWallet(params: { name: string }) {
|
|
54
|
+
const { name } = params;
|
|
55
|
+
// await this.db.del(`wallet|${name}`);
|
|
56
|
+
const keysToDelete = await new Promise<string[]>((resolve, reject) => {
|
|
57
|
+
const walletKeys = [];
|
|
58
|
+
this.db.createKeyStream()
|
|
59
|
+
.on('data', (key: Buffer) => {
|
|
60
|
+
if (key.toString().startsWith(`wallet|${name}`)) {
|
|
61
|
+
walletKeys.push(key);
|
|
62
|
+
} else if (key.toString().startsWith(`key|${name}|`)) {
|
|
63
|
+
walletKeys.push(key);
|
|
64
|
+
}
|
|
65
|
+
})
|
|
66
|
+
.on('error', (err: Error) => {
|
|
67
|
+
reject(err);
|
|
68
|
+
})
|
|
69
|
+
.on('end', () => {
|
|
70
|
+
resolve(walletKeys);
|
|
71
|
+
});
|
|
72
|
+
});
|
|
73
|
+
let batch = this.db.batch();
|
|
74
|
+
for (const key of keysToDelete) {
|
|
75
|
+
batch = batch.del(key);
|
|
76
|
+
}
|
|
77
|
+
await batch.write();
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
async listWallets() {
|
|
81
|
+
return this.db.createReadStream().pipe(
|
|
82
|
+
new Transform({
|
|
83
|
+
objectMode: true,
|
|
84
|
+
write(data, enc, next) {
|
|
85
|
+
if (data.key.toString().startsWith('wallet')) {
|
|
86
|
+
const jsonData = JSON.parse(data.value.toString());
|
|
87
|
+
jsonData.storageType = 'Level';
|
|
88
|
+
this.push(JSON.stringify(jsonData));
|
|
89
|
+
}
|
|
90
|
+
next();
|
|
91
|
+
}
|
|
92
|
+
})
|
|
93
|
+
);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
async listKeys() {
|
|
97
|
+
return this.db.createReadStream().pipe(
|
|
98
|
+
new Transform({
|
|
99
|
+
objectMode: true,
|
|
100
|
+
write(data, enc, next) {
|
|
101
|
+
if (data.key.toString().startsWith('key')) {
|
|
102
|
+
this.push({
|
|
103
|
+
data: data.value.toString(),
|
|
104
|
+
key: data.key.toString(),
|
|
105
|
+
storageType: 'Level'
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
next();
|
|
109
|
+
}
|
|
110
|
+
})
|
|
111
|
+
);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
async saveWallet(params) {
|
|
115
|
+
const { wallet } = params;
|
|
116
|
+
delete wallet.storage;
|
|
117
|
+
return this.db.put(`wallet|${wallet.name}`, JSON.stringify(wallet));
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
async getKey(params: { address: string; name: string; keepAlive: boolean; open: boolean }) {
|
|
121
|
+
const { address, name } = params;
|
|
122
|
+
return (await this.db.get(`key|${name}|${address}`)) as string;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
async addKeys(params: { name: string; key: any; toStore: string; keepAlive: boolean; open: boolean }) {
|
|
126
|
+
const { name, key, toStore } = params;
|
|
127
|
+
await this.db.put(`key|${name}|${key.address}`, toStore);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
async getAddress(params: { name: string; address: string; keepAlive: boolean; open: boolean }) {
|
|
131
|
+
const { name, address, keepAlive, open } = params;
|
|
132
|
+
const data: string = (await this.getKey({ address, name, keepAlive, open })).toString();
|
|
133
|
+
if (!data) {
|
|
134
|
+
return null;
|
|
135
|
+
}
|
|
136
|
+
const { pubKey, path } = JSON.parse(data);
|
|
137
|
+
return { address, pubKey, path };
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
async getAddresses(params: { name: string; limit?: number; skip?: number }) {
|
|
141
|
+
const { name, limit, skip } = params;
|
|
142
|
+
const addresses = [];
|
|
143
|
+
let skipped = 0;
|
|
144
|
+
const stream = this.db.createReadStream();
|
|
145
|
+
return new Promise((resolve, reject) => {
|
|
146
|
+
stream
|
|
147
|
+
.on('data', function({ key, value }) {
|
|
148
|
+
if (key.toString().startsWith(`key|${name}|`)) {
|
|
149
|
+
if (skipped <= skip) {
|
|
150
|
+
skipped++;
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
if (limit && addresses.length >= limit) {
|
|
154
|
+
stream.destroy();
|
|
155
|
+
resolve(addresses);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
const address = key.toString().split('|')[2];
|
|
159
|
+
const valJSON = JSON.parse(value.toString());
|
|
160
|
+
addresses.push({ address, pubKey: valJSON.pubKey, path: valJSON.path });
|
|
161
|
+
}
|
|
162
|
+
})
|
|
163
|
+
.on('error', function(err) {
|
|
164
|
+
reject(err);
|
|
165
|
+
})
|
|
166
|
+
.on('end', function() {
|
|
167
|
+
resolve(addresses);
|
|
168
|
+
});
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
}
|