@bitpay-labs/bitcore-client 11.11.4 → 11.11.6
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/package.json +14 -9
- package/ts_build/src/wallet.d.ts +3 -3
- package/.mocharc.json +0 -6
- package/LICENSE +0 -21
- package/mcr.config.js +0 -16
- package/src/client.ts +0 -275
- package/src/encryption.ts +0 -191
- package/src/index.ts +0 -21
- package/src/storage/level.ts +0 -171
- package/src/storage/mongo.ts +0 -191
- package/src/storage/textFile.ts +0 -327
- package/src/storage.ts +0 -271
- package/src/stream-util.ts +0 -80
- package/src/types/index.d.ts +0 -2
- package/src/types/storage.d.ts +0 -1
- package/src/types/wallet.d.ts +0 -36
- package/src/utils.ts +0 -35
- package/src/wallet.ts +0 -1221
- package/test/unit/data/ethMigrationTestWallet.fixture.ts +0 -68
- package/test/unit/wallet.arc.test.ts +0 -10
- package/test/unit/wallet.test.ts +0 -1177
- package/ts_build/test/unit/data/ethMigrationTestWallet.fixture.d.ts +0 -51
- package/ts_build/test/unit/data/ethMigrationTestWallet.fixture.d.ts.map +0 -1
- package/ts_build/test/unit/data/ethMigrationTestWallet.fixture.js +0 -68
- package/ts_build/test/unit/data/ethMigrationTestWallet.fixture.js.map +0 -1
- package/ts_build/test/unit/wallet.arc.test.d.ts +0 -2
- package/ts_build/test/unit/wallet.arc.test.d.ts.map +0 -1
- package/ts_build/test/unit/wallet.arc.test.js +0 -12
- package/ts_build/test/unit/wallet.arc.test.js.map +0 -1
- package/ts_build/test/unit/wallet.test.d.ts +0 -2
- package/ts_build/test/unit/wallet.test.d.ts.map +0 -1
- package/ts_build/test/unit/wallet.test.js +0 -1037
- package/ts_build/test/unit/wallet.test.js.map +0 -1
- package/tsconfig.json +0 -40
- package/tsconfig.prod.json +0 -6
package/src/wallet.ts
DELETED
|
@@ -1,1221 +0,0 @@
|
|
|
1
|
-
import { mkdir, writeFile } from 'fs/promises';
|
|
2
|
-
import 'source-map-support/register';
|
|
3
|
-
import os from 'os';
|
|
4
|
-
import path from 'path';
|
|
5
|
-
import Mnemonic from '@bitpay-labs/bitcore-mnemonic';
|
|
6
|
-
import {
|
|
7
|
-
BitcoreLib,
|
|
8
|
-
BitcoreLibCash,
|
|
9
|
-
BitcoreLibDoge,
|
|
10
|
-
BitcoreLibLtc,
|
|
11
|
-
Constants,
|
|
12
|
-
Deriver,
|
|
13
|
-
SolKit,
|
|
14
|
-
SolanaProgram,
|
|
15
|
-
Transactions,
|
|
16
|
-
Web3,
|
|
17
|
-
ethers,
|
|
18
|
-
xrpl
|
|
19
|
-
} from '@bitpay-labs/crypto-wallet-core';
|
|
20
|
-
import * as Bcrypt from 'bcrypt';
|
|
21
|
-
import { Client } from './client';
|
|
22
|
-
import { Encryption } from './encryption';
|
|
23
|
-
import { Storage } from './storage';
|
|
24
|
-
import { TextFile } from './storage/textFile';
|
|
25
|
-
import { ParseApiStream } from './stream-util';
|
|
26
|
-
import { StorageType } from './types/storage';
|
|
27
|
-
import { BumpTxFeeType, IWallet, KeyImport } from './types/wallet';
|
|
28
|
-
|
|
29
|
-
const { PrivateKey, HDPrivateKey } = BitcoreLib;
|
|
30
|
-
const chainLibs = {
|
|
31
|
-
BTC: BitcoreLib,
|
|
32
|
-
BCH: BitcoreLibCash,
|
|
33
|
-
DOGE: BitcoreLibDoge,
|
|
34
|
-
LTC: BitcoreLibLtc,
|
|
35
|
-
ETH: { Web3, ethers },
|
|
36
|
-
MATIC: { Web3, ethers },
|
|
37
|
-
ARB: { Web3, ethers },
|
|
38
|
-
BASE: { Web3, ethers },
|
|
39
|
-
OP: { Web3, ethers },
|
|
40
|
-
ARC: { Web3, ethers },
|
|
41
|
-
XRP: xrpl,
|
|
42
|
-
SOL: { SolKit, SolanaProgram }
|
|
43
|
-
};
|
|
44
|
-
const CURRENT_WALLET_VERSION = 2;
|
|
45
|
-
|
|
46
|
-
const baseUrls = {
|
|
47
|
-
BTC: 'https://api.bitcore.io/api',
|
|
48
|
-
BCH: 'https://api.bitcore.io/api',
|
|
49
|
-
DOGE: 'https://api.bitcore.io/api',
|
|
50
|
-
LTC: 'https://api.bitcore.io/api',
|
|
51
|
-
ETH: 'https://api-eth.bitcore.io/api',
|
|
52
|
-
MATIC: 'https://api-matic.bitcore.io/api',
|
|
53
|
-
ARB: 'https://api-eth.bitcore.io/api',
|
|
54
|
-
OP: 'https://api-eth.bitcore.io/api',
|
|
55
|
-
BASE: 'https://api-eth.bitcore.io/api',
|
|
56
|
-
ARC: 'https://api-eth.bitcore.io/api',
|
|
57
|
-
XRP: 'https://api-xrp.bitcore.io/api',
|
|
58
|
-
SOL: 'https://api-sol.bitcore.io/api'
|
|
59
|
-
};
|
|
60
|
-
|
|
61
|
-
export interface IWalletExt extends IWallet {
|
|
62
|
-
storage?: Storage;
|
|
63
|
-
version?: 0 | 2; // Wallet versioning used for backwards compatibility
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
export class Wallet {
|
|
67
|
-
masterKey?: any;
|
|
68
|
-
baseUrl: string;
|
|
69
|
-
chain: string;
|
|
70
|
-
network: string;
|
|
71
|
-
client: Client;
|
|
72
|
-
storage: Storage;
|
|
73
|
-
storageType: string;
|
|
74
|
-
unlocked?: { encryptionKey: Buffer; masterKey: { xprivkey: Buffer; privateKey: Buffer } };
|
|
75
|
-
password: string;
|
|
76
|
-
encryptionKey: string;
|
|
77
|
-
authPubKey: string;
|
|
78
|
-
pubKey?: string;
|
|
79
|
-
xPubKey: string;
|
|
80
|
-
name: string;
|
|
81
|
-
path: string;
|
|
82
|
-
addressIndex?: number;
|
|
83
|
-
authKey: string;
|
|
84
|
-
derivationPath: string;
|
|
85
|
-
tokens?: Array<any>;
|
|
86
|
-
lite: boolean;
|
|
87
|
-
addressType: string;
|
|
88
|
-
addressZero: string;
|
|
89
|
-
version?: number;
|
|
90
|
-
|
|
91
|
-
static XrpAccountFlags = xrpl.AccountSetTfFlags;
|
|
92
|
-
|
|
93
|
-
constructor(params: Wallet | IWalletExt) {
|
|
94
|
-
Object.assign(this, params);
|
|
95
|
-
if (!this.baseUrl) {
|
|
96
|
-
this.baseUrl = baseUrls[this.chain.toUpperCase()] || 'https://api.bitcore.io/api';
|
|
97
|
-
}
|
|
98
|
-
this.client = new Client({
|
|
99
|
-
apiUrl: this.getApiUrl(),
|
|
100
|
-
authKey: this.getAuthSigningKey()
|
|
101
|
-
});
|
|
102
|
-
this.addressIndex = this.addressIndex || 0;
|
|
103
|
-
this.addressType = AddressTypes[this.chain]?.[this.addressType] || 'pubkeyhash';
|
|
104
|
-
if (params.lite) {
|
|
105
|
-
delete this.masterKey;
|
|
106
|
-
delete this.pubKey;
|
|
107
|
-
this.lite = true;
|
|
108
|
-
}
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
getApiUrl() {
|
|
112
|
-
return `${this.baseUrl}/${this.chain}/${this.network}`;
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
getLib() {
|
|
116
|
-
return chainLibs[this.chain.toUpperCase()];
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
saveWallet() {
|
|
120
|
-
const walletInstance = Object.assign({}, this);
|
|
121
|
-
delete walletInstance.unlocked;
|
|
122
|
-
if (walletInstance.masterKey) {
|
|
123
|
-
walletInstance.lite = false;
|
|
124
|
-
}
|
|
125
|
-
return this.storage.saveWallet({ wallet: walletInstance });
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
toObject(lite: boolean = this.lite) {
|
|
129
|
-
return {
|
|
130
|
-
name: this.name,
|
|
131
|
-
chain: this.chain,
|
|
132
|
-
network: this.network,
|
|
133
|
-
path: this.path,
|
|
134
|
-
baseUrl: this.baseUrl,
|
|
135
|
-
encryptionKey: this.encryptionKey,
|
|
136
|
-
authKey: this.authKey,
|
|
137
|
-
authPubKey: this.authPubKey,
|
|
138
|
-
masterKey: lite ? undefined : this.masterKey,
|
|
139
|
-
password: Bcrypt.hashSync(this.password, 10),
|
|
140
|
-
xPubKey: this.xPubKey,
|
|
141
|
-
pubKey: lite ? undefined : this.pubKey,
|
|
142
|
-
tokens: this.tokens,
|
|
143
|
-
storageType: this.storageType,
|
|
144
|
-
lite,
|
|
145
|
-
addressType: this.addressType,
|
|
146
|
-
addressZero: this.addressZero,
|
|
147
|
-
version: this.version
|
|
148
|
-
};
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
static async deleteWallet(params: { name: string; path?: string; storage?: Storage; storageType?: StorageType }) {
|
|
152
|
-
const { name, path, storageType } = params;
|
|
153
|
-
let { storage } = params;
|
|
154
|
-
try {
|
|
155
|
-
storage = storage || new Storage({ errorIfExists: false, createIfMissing: false, path, storageType });
|
|
156
|
-
await storage.deleteWallet({ name });
|
|
157
|
-
} catch (e: any) {
|
|
158
|
-
// ignore error if default wallet path does not exist
|
|
159
|
-
if (!path && !e.message?.includes?.('Not a valid wallet path')) {
|
|
160
|
-
throw e;
|
|
161
|
-
}
|
|
162
|
-
}
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
static async create(params: Partial<IWalletExt>) {
|
|
166
|
-
const { network, name, phrase, xpriv, password, path, lite, baseUrl } = params;
|
|
167
|
-
let { chain, storageType, storage, addressType } = params;
|
|
168
|
-
if (phrase && xpriv) {
|
|
169
|
-
throw new Error('You can only provide either a phrase or a xpriv, not both');
|
|
170
|
-
}
|
|
171
|
-
if (!chain || !network || !name) {
|
|
172
|
-
throw new Error('Missing required parameter');
|
|
173
|
-
}
|
|
174
|
-
chain = chain.toUpperCase();
|
|
175
|
-
if (addressType && AddressTypes[chain] && !AddressTypes[chain]?.[addressType]) {
|
|
176
|
-
throw new Error(`Invalid --addressType for chain. Valid address types are: ${Object.keys(AddressTypes[chain]).join(' | ')}`);
|
|
177
|
-
}
|
|
178
|
-
addressType = AddressTypes[chain]?.[addressType] || 'pubkeyhash';
|
|
179
|
-
|
|
180
|
-
// Generate wallet private keys
|
|
181
|
-
let hdPrivKey;
|
|
182
|
-
let mnemonic;
|
|
183
|
-
if (xpriv) {
|
|
184
|
-
hdPrivKey = new HDPrivateKey(xpriv, network);
|
|
185
|
-
} else {
|
|
186
|
-
mnemonic = new Mnemonic(phrase);
|
|
187
|
-
const algo = Constants.ALGOS_BY_CHAIN[chain] || Constants.ALGOS_BY_CHAIN['default'];
|
|
188
|
-
const keyType = Constants.ALGO_TO_KEY_TYPE[algo];
|
|
189
|
-
hdPrivKey = mnemonic.toHDPrivateKey('', network).derive(Deriver.pathFor(chain, network), keyType);
|
|
190
|
-
}
|
|
191
|
-
const privKeyObj = hdPrivKey.toObjectWithBufferPrivateKey();
|
|
192
|
-
|
|
193
|
-
// Generate public keys
|
|
194
|
-
// bip44 compatible pubKey
|
|
195
|
-
const pubKey = hdPrivKey.publicKey.toString();
|
|
196
|
-
|
|
197
|
-
// Generate and encrypt the encryption key and private key
|
|
198
|
-
const walletEncryptionKey = Encryption.generateEncryptionKey();
|
|
199
|
-
const encryptionKey = Encryption.encryptEncryptionKey(walletEncryptionKey, password); // stored, password-wrapped
|
|
200
|
-
|
|
201
|
-
// Encrypt privKeyObj.privateKey & privKeyObj.xprivkey
|
|
202
|
-
const xprivBuffer = BitcoreLib.encoding.Base58Check.decode(privKeyObj.xprivkey);
|
|
203
|
-
privKeyObj.xprivkey = Encryption.encryptBuffer(xprivBuffer, pubKey, walletEncryptionKey).toString('hex');
|
|
204
|
-
privKeyObj.privateKey = Encryption.encryptBuffer(privKeyObj.privateKey, pubKey, walletEncryptionKey).toString('hex');
|
|
205
|
-
|
|
206
|
-
// Generate authentication keys
|
|
207
|
-
const authKey = new PrivateKey();
|
|
208
|
-
const authPubKey = authKey.toPublicKey().toString();
|
|
209
|
-
|
|
210
|
-
const masterKeyWithEncryptedPrivateKeys = JSON.stringify(privKeyObj);
|
|
211
|
-
|
|
212
|
-
storageType = storageType ? storageType : 'Level';
|
|
213
|
-
storage =
|
|
214
|
-
storage ||
|
|
215
|
-
new Storage({
|
|
216
|
-
path,
|
|
217
|
-
errorIfExists: false,
|
|
218
|
-
createIfMissing: true,
|
|
219
|
-
storageType
|
|
220
|
-
});
|
|
221
|
-
|
|
222
|
-
const alreadyExists = await this.loadWallet({ storage, name, storageType }).catch(() => {/** no op */});
|
|
223
|
-
if (alreadyExists) {
|
|
224
|
-
throw new Error('Wallet already exists');
|
|
225
|
-
}
|
|
226
|
-
|
|
227
|
-
const wallet = new Wallet({
|
|
228
|
-
name,
|
|
229
|
-
chain,
|
|
230
|
-
network,
|
|
231
|
-
path,
|
|
232
|
-
baseUrl,
|
|
233
|
-
encryptionKey,
|
|
234
|
-
authKey,
|
|
235
|
-
authPubKey,
|
|
236
|
-
masterKey: masterKeyWithEncryptedPrivateKeys,
|
|
237
|
-
password,
|
|
238
|
-
xPubKey: hdPrivKey.xpubkey,
|
|
239
|
-
pubKey,
|
|
240
|
-
tokens: [],
|
|
241
|
-
storage,
|
|
242
|
-
storageType,
|
|
243
|
-
lite,
|
|
244
|
-
addressType,
|
|
245
|
-
addressZero: null,
|
|
246
|
-
version: CURRENT_WALLET_VERSION,
|
|
247
|
-
} as IWalletExt);
|
|
248
|
-
|
|
249
|
-
// save wallet to storage and then bitcore-node
|
|
250
|
-
await storage.saveWallet({ wallet: wallet.toObject(lite) });
|
|
251
|
-
const loadedWallet = await this.loadWallet({
|
|
252
|
-
storage,
|
|
253
|
-
name,
|
|
254
|
-
storageType
|
|
255
|
-
});
|
|
256
|
-
|
|
257
|
-
if (!xpriv) {
|
|
258
|
-
process.stdout.write(Buffer.from(mnemonic.phrase));
|
|
259
|
-
process.stdout.write(os.EOL);
|
|
260
|
-
} else {
|
|
261
|
-
process.stdout.write(hdPrivKey.toBuffer());
|
|
262
|
-
process.stdout.write(os.EOL);
|
|
263
|
-
}
|
|
264
|
-
|
|
265
|
-
await loadedWallet.register().catch(e => {
|
|
266
|
-
console.debug(e);
|
|
267
|
-
console.error('Failed to register wallet with bitcore-node.');
|
|
268
|
-
});
|
|
269
|
-
|
|
270
|
-
return loadedWallet;
|
|
271
|
-
}
|
|
272
|
-
|
|
273
|
-
static async exists(params: { name: string; path?: string; storage?: Storage }) {
|
|
274
|
-
const { storage, name } = params;
|
|
275
|
-
let alreadyExists;
|
|
276
|
-
try {
|
|
277
|
-
alreadyExists = await Wallet.loadWallet({
|
|
278
|
-
storage,
|
|
279
|
-
name
|
|
280
|
-
});
|
|
281
|
-
} catch (err) {
|
|
282
|
-
console.log(err);
|
|
283
|
-
}
|
|
284
|
-
return alreadyExists != undefined && alreadyExists.length && alreadyExists.length != 0;
|
|
285
|
-
}
|
|
286
|
-
|
|
287
|
-
static async loadWallet(params: { name: string; path?: string; storage?: Storage; storageType?: StorageType }) {
|
|
288
|
-
const { name, path, storageType } = params;
|
|
289
|
-
let { storage } = params;
|
|
290
|
-
storage = storage || new Storage({ errorIfExists: false, createIfMissing: false, path, storageType });
|
|
291
|
-
const loadedWallet = await storage.loadWallet({ name });
|
|
292
|
-
|
|
293
|
-
if (!loadedWallet) {
|
|
294
|
-
throw new Error('No wallet could be found');
|
|
295
|
-
}
|
|
296
|
-
|
|
297
|
-
return new Wallet(Object.assign(loadedWallet, { storage }));
|
|
298
|
-
}
|
|
299
|
-
|
|
300
|
-
/**
|
|
301
|
-
* Does this wallet use UTXOs?
|
|
302
|
-
* @returns {Boolean}
|
|
303
|
-
*/
|
|
304
|
-
isUtxoChain() {
|
|
305
|
-
// the toUpperCase() should not be necessary, but it's here just in case.
|
|
306
|
-
return ['BTC', 'BCH', 'DOGE', 'LTC'].includes(this.chain?.toUpperCase() || 'BTC');
|
|
307
|
-
}
|
|
308
|
-
|
|
309
|
-
/**
|
|
310
|
-
* Is this wallet EVM compatible?
|
|
311
|
-
* @returns {Boolean}
|
|
312
|
-
*/
|
|
313
|
-
isEvmChain() {
|
|
314
|
-
return ['ETH', 'MATIC', 'ARB', 'OP', 'BASE', 'ARC'].includes(this.chain?.toUpperCase());
|
|
315
|
-
}
|
|
316
|
-
|
|
317
|
-
isSolanaChain() {
|
|
318
|
-
return ['SOL'].includes(this.chain?.toUpperCase());
|
|
319
|
-
}
|
|
320
|
-
|
|
321
|
-
lock() {
|
|
322
|
-
if (!this.unlocked) {
|
|
323
|
-
return this;
|
|
324
|
-
}
|
|
325
|
-
|
|
326
|
-
if (Buffer.isBuffer(this.unlocked.masterKey.xprivkey)) {
|
|
327
|
-
this.unlocked.masterKey.xprivkey.fill(0);
|
|
328
|
-
}
|
|
329
|
-
|
|
330
|
-
if (Buffer.isBuffer(this.unlocked.masterKey.privateKey)) {
|
|
331
|
-
this.unlocked.masterKey.privateKey.fill(0);
|
|
332
|
-
}
|
|
333
|
-
this.unlocked.masterKey = null;
|
|
334
|
-
|
|
335
|
-
if (Buffer.isBuffer(this.unlocked.encryptionKey)) {
|
|
336
|
-
this.unlocked.encryptionKey.fill(0);
|
|
337
|
-
}
|
|
338
|
-
this.unlocked.encryptionKey = null;
|
|
339
|
-
this.unlocked = null;
|
|
340
|
-
return this;
|
|
341
|
-
}
|
|
342
|
-
|
|
343
|
-
async unlock(password) {
|
|
344
|
-
const validPass = await Bcrypt.compare(password, this.password).catch(() => false);
|
|
345
|
-
if (!validPass) {
|
|
346
|
-
throw new Error('Incorrect Password');
|
|
347
|
-
}
|
|
348
|
-
const encryptionKey = Encryption.decryptEncryptionKey(this.encryptionKey, password, true);
|
|
349
|
-
if (this.version != CURRENT_WALLET_VERSION) {
|
|
350
|
-
await this.migrateWallet(encryptionKey);
|
|
351
|
-
}
|
|
352
|
-
let masterKey;
|
|
353
|
-
if (!this.lite) {
|
|
354
|
-
masterKey = JSON.parse(this.masterKey);
|
|
355
|
-
masterKey.xprivkey = Encryption.decryptToBuffer(masterKey.xprivkey, this.pubKey, encryptionKey);
|
|
356
|
-
masterKey.privateKey = Encryption.decryptToBuffer(masterKey.privateKey, this.pubKey, encryptionKey);
|
|
357
|
-
}
|
|
358
|
-
this.unlocked = {
|
|
359
|
-
encryptionKey,
|
|
360
|
-
masterKey
|
|
361
|
-
};
|
|
362
|
-
return this;
|
|
363
|
-
}
|
|
364
|
-
|
|
365
|
-
async migrateWallet(encryptionKey: Buffer): Promise<Wallet> {
|
|
366
|
-
const preMigrationVersion = this.version ?? 1;
|
|
367
|
-
/**
|
|
368
|
-
* 0: Checks
|
|
369
|
-
*/
|
|
370
|
-
if (preMigrationVersion == CURRENT_WALLET_VERSION) {
|
|
371
|
-
console.warn('Wallet migration unnecessarily called - wallet is current version');
|
|
372
|
-
return this;
|
|
373
|
-
}
|
|
374
|
-
|
|
375
|
-
if (preMigrationVersion > CURRENT_WALLET_VERSION) {
|
|
376
|
-
console.warn(`Wallet version ${preMigrationVersion} greater than expected current wallet version ${CURRENT_WALLET_VERSION}`);
|
|
377
|
-
return this;
|
|
378
|
-
}
|
|
379
|
-
|
|
380
|
-
console.log(`Migrating wallet from version ${preMigrationVersion} to version ${CURRENT_WALLET_VERSION}`);
|
|
381
|
-
|
|
382
|
-
/**
|
|
383
|
-
* 1: Wallet to .bak
|
|
384
|
-
*/
|
|
385
|
-
const rawWallet = await this.storage.loadWallet({ name: this.name, raw: true });
|
|
386
|
-
if (!rawWallet) {
|
|
387
|
-
throw new Error('Migration failed - wallet not found');
|
|
388
|
-
}
|
|
389
|
-
|
|
390
|
-
const backupDir = path.join(
|
|
391
|
-
os.homedir(),
|
|
392
|
-
'.bitcore',
|
|
393
|
-
'bitcoreWallet',
|
|
394
|
-
'backup'
|
|
395
|
-
);
|
|
396
|
-
await mkdir(backupDir, { recursive: true });
|
|
397
|
-
|
|
398
|
-
const walletFilePath = path.join(backupDir, `${this.name}.v${preMigrationVersion}.bak`);
|
|
399
|
-
|
|
400
|
-
await writeFile(walletFilePath, rawWallet, 'utf8')
|
|
401
|
-
.then(() => console.log(`Pre-migration wallet backup written to ${walletFilePath}`))
|
|
402
|
-
.catch(err => {
|
|
403
|
-
console.error('Wallet backup failed, aborting migration', err.message);
|
|
404
|
-
throw new Error('Migration failure: failed to write wallet backup file. Aborting.');
|
|
405
|
-
});
|
|
406
|
-
|
|
407
|
-
/**
|
|
408
|
-
* Retrieve stored keys for backup and for migration
|
|
409
|
-
*/
|
|
410
|
-
const addresses = await this.getAddresses();
|
|
411
|
-
const storedKeys = await this.storage.getStoredKeys({
|
|
412
|
-
addresses,
|
|
413
|
-
name: this.name,
|
|
414
|
-
});
|
|
415
|
-
|
|
416
|
-
// Back up keys (enc)
|
|
417
|
-
const backupKeysStr = JSON.stringify(storedKeys);
|
|
418
|
-
const keysFilePath = path.join(backupDir, `${this.name}_keys.v${preMigrationVersion}.bak`);
|
|
419
|
-
await writeFile(keysFilePath, backupKeysStr, 'utf8')
|
|
420
|
-
.then(() => console.log(`Pre-migration keys backup written to ${keysFilePath}`))
|
|
421
|
-
.catch(err => {
|
|
422
|
-
console.error('Keys backup failed, aborting migration', err.message);
|
|
423
|
-
throw new Error('Migration failure: failed to write keys backup file. Aborting.');
|
|
424
|
-
});
|
|
425
|
-
|
|
426
|
-
/**
|
|
427
|
-
* 2. Convert
|
|
428
|
-
*/
|
|
429
|
-
|
|
430
|
-
/**
|
|
431
|
-
* 2a. Convert masterKey and encryptionKey
|
|
432
|
-
*/
|
|
433
|
-
const masterKeyStr = Encryption.decryptPrivateKey(this.masterKey, this.pubKey, encryptionKey);
|
|
434
|
-
const masterKey = JSON.parse(masterKeyStr);
|
|
435
|
-
if (!(masterKey.xprivkey && masterKey.privateKey)) {
|
|
436
|
-
throw new Error('Migration failure: masterKey is not formatted as expected');
|
|
437
|
-
}
|
|
438
|
-
|
|
439
|
-
const xprivBuffer = BitcoreLib.encoding.Base58Check.decode(masterKey.xprivkey);
|
|
440
|
-
const enc_xprivkeyBuffer = Encryption.encryptBuffer(xprivBuffer, this.pubKey, encryptionKey);
|
|
441
|
-
xprivBuffer.fill(0);
|
|
442
|
-
|
|
443
|
-
masterKey.xprivkey = enc_xprivkeyBuffer.toString('hex');
|
|
444
|
-
enc_xprivkeyBuffer.fill(0);
|
|
445
|
-
|
|
446
|
-
const privateKeyBuffer = Buffer.from(masterKey.privateKey, 'hex');
|
|
447
|
-
const enc_privateKeyBuffer = Encryption.encryptBuffer(privateKeyBuffer, this.pubKey, encryptionKey);
|
|
448
|
-
privateKeyBuffer.fill(0);
|
|
449
|
-
|
|
450
|
-
masterKey.privateKey = enc_privateKeyBuffer.toString('hex');
|
|
451
|
-
enc_privateKeyBuffer.fill(0);
|
|
452
|
-
|
|
453
|
-
// String with encrypted hex-encoded xprivkey and privateKey strings
|
|
454
|
-
this.masterKey = JSON.stringify(masterKey);
|
|
455
|
-
|
|
456
|
-
/**
|
|
457
|
-
* 2b. Convert signing keys
|
|
458
|
-
*/
|
|
459
|
-
const newKeys = [];
|
|
460
|
-
for (const key of storedKeys) {
|
|
461
|
-
const { encKey, pubKey } = key;
|
|
462
|
-
const decryptedKey = Encryption.decryptPrivateKey(encKey, pubKey, encryptionKey);
|
|
463
|
-
const decryptedKeyJSON = JSON.parse(decryptedKey);
|
|
464
|
-
|
|
465
|
-
// Convert private key to buffer format (uniform across all chains)
|
|
466
|
-
const privKeyBuffer = Deriver.privateKeyToBuffer(this.chain, decryptedKeyJSON.privKey);
|
|
467
|
-
const encryptedPrivateKeyBuffer = Encryption.encryptBuffer(privKeyBuffer, pubKey, encryptionKey);
|
|
468
|
-
privKeyBuffer.fill(0); // Zero out the plaintext buffer
|
|
469
|
-
|
|
470
|
-
decryptedKeyJSON.privKey = encryptedPrivateKeyBuffer.toString('hex');
|
|
471
|
-
newKeys.push(decryptedKeyJSON);
|
|
472
|
-
}
|
|
473
|
-
|
|
474
|
-
/**
|
|
475
|
-
* 3. Overwrite
|
|
476
|
-
*/
|
|
477
|
-
// 3a. Overwrite keys
|
|
478
|
-
const overwriteKeys = this.storage.storageType instanceof TextFile
|
|
479
|
-
? this.storage.storageType.migrate({ version: preMigrationVersion, name: this.name, keys: newKeys })
|
|
480
|
-
: this.storage.addKeysSafe({ name: this.name, keys: newKeys });
|
|
481
|
-
await overwriteKeys.catch(err => {
|
|
482
|
-
console.error('Migration failure: updated keys not successfully stored', err);
|
|
483
|
-
throw new Error('Migration failure: keys not successfully stored. Use backups to restore prior wallet and keys.');
|
|
484
|
-
});
|
|
485
|
-
|
|
486
|
-
// 3b. Overwrite wallet
|
|
487
|
-
this.version = CURRENT_WALLET_VERSION;
|
|
488
|
-
const storedEncryptedPassword = this.password; // Wallet.toObject() rehashes password - save and replace
|
|
489
|
-
const walletObj = this.toObject(false);
|
|
490
|
-
walletObj.password = storedEncryptedPassword;
|
|
491
|
-
await this.storage.saveWallet({ wallet: walletObj })
|
|
492
|
-
.catch(err => {
|
|
493
|
-
console.error('Migration failure: wallet not successfully saved', err);
|
|
494
|
-
throw new Error('Migration failure: wallet not successfully saved. Use backups to restore prior wallet and keys');
|
|
495
|
-
});
|
|
496
|
-
|
|
497
|
-
console.log('Migration succeeded');
|
|
498
|
-
return this;
|
|
499
|
-
}
|
|
500
|
-
|
|
501
|
-
async register(params: { baseUrl?: string } = {}) {
|
|
502
|
-
const { baseUrl } = params;
|
|
503
|
-
if (baseUrl) {
|
|
504
|
-
// save the new url without chain and network
|
|
505
|
-
// then use the new url with chain and network below
|
|
506
|
-
this.baseUrl = baseUrl;
|
|
507
|
-
await this.saveWallet();
|
|
508
|
-
}
|
|
509
|
-
const payload = {
|
|
510
|
-
name: this.name,
|
|
511
|
-
pubKey: this.authPubKey,
|
|
512
|
-
path: this.derivationPath,
|
|
513
|
-
network: this.network,
|
|
514
|
-
chain: this.chain,
|
|
515
|
-
apiUrl: this.getApiUrl()
|
|
516
|
-
};
|
|
517
|
-
return this.client.register({ payload });
|
|
518
|
-
}
|
|
519
|
-
|
|
520
|
-
getAuthSigningKey() {
|
|
521
|
-
return new PrivateKey(this.authKey);
|
|
522
|
-
}
|
|
523
|
-
|
|
524
|
-
/**
|
|
525
|
-
* Get balance for the wallet
|
|
526
|
-
* @param params
|
|
527
|
-
* @param params.time Get balance at point in time
|
|
528
|
-
* @param params.token DEPRECATED: Token to get by ticker symbol. WARNING: there could be multiple tokens with the same symbol
|
|
529
|
-
* @param params.tokenName Token to get by tokenName (Recommended over `token`)
|
|
530
|
-
* @param params.address EVM Account address to get the balance for
|
|
531
|
-
* @param params.hex Return the balance in hex
|
|
532
|
-
* @returns
|
|
533
|
-
*/
|
|
534
|
-
getBalance(params: { time?: string; token?: string; tokenName?: string; address?: string; hex?: boolean } = {}) {
|
|
535
|
-
const { time, token, tokenName, address, hex } = params;
|
|
536
|
-
let payload;
|
|
537
|
-
if (token || tokenName) {
|
|
538
|
-
const tokenObj = this.getTokenObj({ token, tokenName });
|
|
539
|
-
payload = {
|
|
540
|
-
tokenContractAddress: tokenObj.address
|
|
541
|
-
};
|
|
542
|
-
}
|
|
543
|
-
return this.client.getBalance({ payload, pubKey: this.authPubKey, time, address, hex });
|
|
544
|
-
}
|
|
545
|
-
|
|
546
|
-
getNetworkFee(params: { target?: number; txType?: number } = {}) {
|
|
547
|
-
const target = params.target || 2;
|
|
548
|
-
const txType = params.txType;
|
|
549
|
-
return this.client.getFee({ target, txType });
|
|
550
|
-
}
|
|
551
|
-
|
|
552
|
-
getNetworkPriorityFee(params: { percentile?: number } = {}) {
|
|
553
|
-
const percentile = params.percentile;
|
|
554
|
-
return this.client.getPriorityFee({ percentile });
|
|
555
|
-
}
|
|
556
|
-
|
|
557
|
-
getUtxos(params: { includeSpent?: boolean } = {}) {
|
|
558
|
-
const { includeSpent = false } = params;
|
|
559
|
-
return this.client.getCoins({
|
|
560
|
-
pubKey: this.authPubKey,
|
|
561
|
-
includeSpent
|
|
562
|
-
});
|
|
563
|
-
}
|
|
564
|
-
|
|
565
|
-
getUtxosArray(params: { includeSpent?: boolean } = {}) {
|
|
566
|
-
return new Promise((resolve, reject) => {
|
|
567
|
-
const utxoArray = [];
|
|
568
|
-
const { includeSpent = false } = params;
|
|
569
|
-
const utxoRequest = this.client.getCoins({
|
|
570
|
-
pubKey: this.authPubKey,
|
|
571
|
-
includeSpent
|
|
572
|
-
});
|
|
573
|
-
utxoRequest
|
|
574
|
-
.pipe(new ParseApiStream())
|
|
575
|
-
.on('data', utxo => utxoArray.push(utxo))
|
|
576
|
-
.on('end', () => resolve(utxoArray))
|
|
577
|
-
.on('err', err => reject(err));
|
|
578
|
-
});
|
|
579
|
-
}
|
|
580
|
-
|
|
581
|
-
/**
|
|
582
|
-
* Backwards compatible method for getting the token object
|
|
583
|
-
*
|
|
584
|
-
* `token` and `tokenName` are separate parameters because there are legacy token objects
|
|
585
|
-
* without a `name` but modern implementations try to use the tokenName.
|
|
586
|
-
* e.g.:
|
|
587
|
-
* tokens = [
|
|
588
|
-
* { token: 'USDC', address: '0x123...', decimals: '6' } // USDC.e
|
|
589
|
-
* { token: 'USDC', address: '0xabc...', decimals: '6', name: 'USDCn_m' } // native USDC
|
|
590
|
-
* ]
|
|
591
|
-
* params1 = { token: 'USDC', tokenName: 'USDC_m' } => returns tokens[0]
|
|
592
|
-
* params2 = { token: 'USDC', tokenName: 'USDCn_m' } => returns tokens[1]
|
|
593
|
-
*
|
|
594
|
-
*
|
|
595
|
-
* @param tokenName The `name` field on the token object
|
|
596
|
-
* @param token The `symbol` field on the token object (deprecated)
|
|
597
|
-
*/
|
|
598
|
-
getTokenObj(params: { tokenName?: string; token?: string }) {
|
|
599
|
-
const { tokenName, token } = params || {};
|
|
600
|
-
if (!tokenName && !token) {
|
|
601
|
-
return null;
|
|
602
|
-
}
|
|
603
|
-
// If tokenName was given, find the token by name (e.g. USDC_m)
|
|
604
|
-
let tokenObj = tokenName && this.tokens.find(tok => tok.name === tokenName);
|
|
605
|
-
// If not found by name AND token was given, find the token by symbol (e.g. USDC)
|
|
606
|
-
tokenObj = tokenObj || (token && this.tokens.find(tok => tok.symbol === token && [token, undefined].includes(tok.name)));
|
|
607
|
-
if (!tokenObj) {
|
|
608
|
-
throw new Error(`${tokenName || token} not found on wallet ${this.name}`);
|
|
609
|
-
}
|
|
610
|
-
return tokenObj;
|
|
611
|
-
}
|
|
612
|
-
|
|
613
|
-
listTransactions(params) {
|
|
614
|
-
const { token, tokenName } = params;
|
|
615
|
-
if (token || tokenName) {
|
|
616
|
-
const tokenObj = this.getTokenObj({ token, tokenName });
|
|
617
|
-
params.tokenContractAddress = tokenObj.address;
|
|
618
|
-
}
|
|
619
|
-
return this.client.listTransactions({
|
|
620
|
-
...params,
|
|
621
|
-
pubKey: this.authPubKey
|
|
622
|
-
});
|
|
623
|
-
}
|
|
624
|
-
|
|
625
|
-
async getToken(contractAddress) {
|
|
626
|
-
if (this.isSolanaChain()) {
|
|
627
|
-
const addresses = await this.client.getSolanaTokens(this.addressZero);
|
|
628
|
-
return addresses.find(addr => addr.mintAddress === contractAddress);
|
|
629
|
-
}
|
|
630
|
-
return this.client.getToken(contractAddress);
|
|
631
|
-
}
|
|
632
|
-
|
|
633
|
-
async addToken(params) {
|
|
634
|
-
if (!this.tokens) {
|
|
635
|
-
this.tokens = [];
|
|
636
|
-
}
|
|
637
|
-
this.tokens.push({
|
|
638
|
-
symbol: params.symbol,
|
|
639
|
-
address: params.address,
|
|
640
|
-
decimals: params.decimals,
|
|
641
|
-
name: params.name,
|
|
642
|
-
ataAddress: params.ataAddress
|
|
643
|
-
});
|
|
644
|
-
await this.saveWallet();
|
|
645
|
-
}
|
|
646
|
-
|
|
647
|
-
async rmToken({ tokenName }) {
|
|
648
|
-
if (!this.tokens) {
|
|
649
|
-
return;
|
|
650
|
-
}
|
|
651
|
-
this.tokens = this.tokens.filter(tok =>
|
|
652
|
-
(tok.name && tok.name !== tokenName) ||
|
|
653
|
-
/* legacy object */ (!tok.name && tok.symbol !== tokenName)
|
|
654
|
-
);
|
|
655
|
-
await this.saveWallet();
|
|
656
|
-
}
|
|
657
|
-
|
|
658
|
-
async newTx(params: {
|
|
659
|
-
utxos?: any[];
|
|
660
|
-
recipients: { address: string; amount: number }[];
|
|
661
|
-
from?: string;
|
|
662
|
-
change?: string; // 'miner' to have any change go to the miner (i.e. no change).
|
|
663
|
-
invoiceID?: string;
|
|
664
|
-
memo?: string;
|
|
665
|
-
fee?: number;
|
|
666
|
-
feeRate?: number;
|
|
667
|
-
nonce?: number;
|
|
668
|
-
tag?: number;
|
|
669
|
-
data?: string;
|
|
670
|
-
token?: string; // deprecated. tokenName is better, but old token objects don't have the `name` field.
|
|
671
|
-
tokenName?: string;
|
|
672
|
-
gasLimit?: number;
|
|
673
|
-
gasPrice?: number;
|
|
674
|
-
contractAddress?: string;
|
|
675
|
-
chainId?: number;
|
|
676
|
-
replaceByFee?: boolean;
|
|
677
|
-
lockUntilBlock?: number;
|
|
678
|
-
lockUntilDate?: Date;
|
|
679
|
-
isSweep?: boolean;
|
|
680
|
-
type?: string;
|
|
681
|
-
flags?: number;
|
|
682
|
-
blockHash?: string;
|
|
683
|
-
blockHeight?: number;
|
|
684
|
-
}) {
|
|
685
|
-
let chain = this.chain;
|
|
686
|
-
let tokenContractAddress;
|
|
687
|
-
let decimals;
|
|
688
|
-
let fromAta;
|
|
689
|
-
if (params.token || params.tokenName) {
|
|
690
|
-
chain = this.isSolanaChain() ? this.chain + 'SPL' : this.chain + 'ERC20';
|
|
691
|
-
const tokenObj = this.getTokenObj(params);
|
|
692
|
-
tokenContractAddress = tokenObj.address;
|
|
693
|
-
decimals = tokenObj.decimals;
|
|
694
|
-
fromAta = tokenObj.ataAddress;
|
|
695
|
-
}
|
|
696
|
-
let change = params.change;
|
|
697
|
-
if (change === 'miner') {
|
|
698
|
-
change = undefined; // no change
|
|
699
|
-
} else if (!change) {
|
|
700
|
-
change = await this._getChangeAddress();
|
|
701
|
-
}
|
|
702
|
-
let blockHash = params.blockHash;
|
|
703
|
-
let blockHeight = params.blockHeight;
|
|
704
|
-
if (this.isSolanaChain() && (!blockHash || !blockHeight)) {
|
|
705
|
-
const tip = await this.client.getBlockTip();
|
|
706
|
-
blockHash = tip.hash;
|
|
707
|
-
blockHeight = tip.height;
|
|
708
|
-
}
|
|
709
|
-
const payload = {
|
|
710
|
-
network: this.network,
|
|
711
|
-
chain,
|
|
712
|
-
recipients: params.recipients,
|
|
713
|
-
from: params.from,
|
|
714
|
-
change,
|
|
715
|
-
invoiceID: params.invoiceID,
|
|
716
|
-
memo: params.memo,
|
|
717
|
-
fee: params.fee,
|
|
718
|
-
feeRate: params.feeRate,
|
|
719
|
-
utxos: params.utxos,
|
|
720
|
-
nonce: params.nonce,
|
|
721
|
-
tag: params.tag,
|
|
722
|
-
gasPrice: params.gasPrice || params.feeRate || params.fee,
|
|
723
|
-
gasLimit: params.gasLimit || 200000,
|
|
724
|
-
data: params.data,
|
|
725
|
-
tokenAddress: tokenContractAddress,
|
|
726
|
-
contractAddress: params.contractAddress,
|
|
727
|
-
chainId: params.chainId,
|
|
728
|
-
replaceByFee: params.replaceByFee,
|
|
729
|
-
lockUntilBlock: params.lockUntilBlock,
|
|
730
|
-
lockUntilDate: params.lockUntilDate,
|
|
731
|
-
isSweep: params.isSweep,
|
|
732
|
-
type: params.type,
|
|
733
|
-
flags: params.flags,
|
|
734
|
-
blockHash,
|
|
735
|
-
blockHeight,
|
|
736
|
-
decimals,
|
|
737
|
-
fromAta
|
|
738
|
-
};
|
|
739
|
-
return Transactions.create(payload);
|
|
740
|
-
}
|
|
741
|
-
|
|
742
|
-
async createAtaAccount(mintAddress) {
|
|
743
|
-
if (!this.isSolanaChain()) {
|
|
744
|
-
throw new Error('createAtaAccount is only supported for Solana wallets');
|
|
745
|
-
}
|
|
746
|
-
const owner = SolKit.address(this.addressZero);
|
|
747
|
-
if (!mintAddress) {
|
|
748
|
-
throw new Error('mintAddress is required to create an associated token account');
|
|
749
|
-
}
|
|
750
|
-
const [newAccount] = await SolanaProgram.Token.findAssociatedTokenPda({
|
|
751
|
-
owner,
|
|
752
|
-
tokenProgram: SolanaProgram.Token.TOKEN_PROGRAM_ADDRESS,
|
|
753
|
-
mint: SolKit.address(mintAddress),
|
|
754
|
-
});
|
|
755
|
-
const tip = await this.client.getBlockTip();
|
|
756
|
-
const blockHash = tip.hash;
|
|
757
|
-
const blockHeight = tip.height;
|
|
758
|
-
const privateKey = await this.derivePrivateKey(null, 0);
|
|
759
|
-
const privKeyBytes = SolKit.getBase58Encoder().encode(privateKey.privKey);
|
|
760
|
-
const keyPair = await SolKit.createKeyPairSignerFromPrivateKeyBytes(privKeyBytes);
|
|
761
|
-
const tx = Transactions.create({
|
|
762
|
-
network: this.network,
|
|
763
|
-
chain: this.chain,
|
|
764
|
-
category: 'createata',
|
|
765
|
-
fromKeyPair: keyPair,
|
|
766
|
-
from: this.addressZero,
|
|
767
|
-
ataAddress: newAccount,
|
|
768
|
-
blockHash,
|
|
769
|
-
blockHeight,
|
|
770
|
-
mint: mintAddress,
|
|
771
|
-
});
|
|
772
|
-
const sig = await this.signTx({ tx });
|
|
773
|
-
await this.broadcast({ tx: sig });
|
|
774
|
-
return sig;
|
|
775
|
-
}
|
|
776
|
-
|
|
777
|
-
async broadcast(params: { tx: string }) {
|
|
778
|
-
const { tx } = params;
|
|
779
|
-
const payload = {
|
|
780
|
-
network: this.network,
|
|
781
|
-
chain: this.chain,
|
|
782
|
-
rawTx: tx
|
|
783
|
-
};
|
|
784
|
-
return this.client.broadcast({ payload });
|
|
785
|
-
}
|
|
786
|
-
|
|
787
|
-
async getTransactionByTxid(params: { txid: string; populated?: boolean }) {
|
|
788
|
-
const { txid, populated } = params;
|
|
789
|
-
return this.client.getTransaction({ txid, populated });
|
|
790
|
-
}
|
|
791
|
-
|
|
792
|
-
async importKeys(params: { keys: KeyImport[]; rederiveAddys?: boolean }) {
|
|
793
|
-
const { rederiveAddys } = params;
|
|
794
|
-
let { keys } = params;
|
|
795
|
-
// Avoid mutating caller-owned references (we'll encrypt privKeys below)
|
|
796
|
-
keys = keys.map(k => ({ ...k }));
|
|
797
|
-
|
|
798
|
-
const keysToSave: KeyImport[] = [];
|
|
799
|
-
for (const key of keys) {
|
|
800
|
-
if (typeof key.privKey !== 'string') {
|
|
801
|
-
continue;
|
|
802
|
-
}
|
|
803
|
-
|
|
804
|
-
let privKeyBuffer: Buffer | undefined;
|
|
805
|
-
try {
|
|
806
|
-
privKeyBuffer = Deriver.privateKeyToBuffer(this.chain, key.privKey);
|
|
807
|
-
if (typeof key.pubKey !== 'string') {
|
|
808
|
-
key.pubKey = Deriver.getPublicKey(this.chain, this.network, privKeyBuffer);
|
|
809
|
-
}
|
|
810
|
-
if (!key.pubKey) {
|
|
811
|
-
throw new Error(`pubKey is undefined for ${this.name}. Keys not added to storage`);
|
|
812
|
-
}
|
|
813
|
-
|
|
814
|
-
if (rederiveAddys) {
|
|
815
|
-
key.address = Deriver.getAddress(this.chain, this.network, key.pubKey, this.addressType);
|
|
816
|
-
}
|
|
817
|
-
|
|
818
|
-
key.privKey = Encryption.encryptBuffer(privKeyBuffer, key.pubKey, this.unlocked.encryptionKey).toString('hex');
|
|
819
|
-
} finally {
|
|
820
|
-
if (Buffer.isBuffer(privKeyBuffer)) {
|
|
821
|
-
privKeyBuffer.fill(0);
|
|
822
|
-
}
|
|
823
|
-
}
|
|
824
|
-
keysToSave.push(key);
|
|
825
|
-
}
|
|
826
|
-
|
|
827
|
-
if (keysToSave.length) {
|
|
828
|
-
await this.storage.addKeysSafe({
|
|
829
|
-
keys: keysToSave,
|
|
830
|
-
name: this.name
|
|
831
|
-
});
|
|
832
|
-
}
|
|
833
|
-
const addedAddresses = keys.map(key => {
|
|
834
|
-
return { address: key.address };
|
|
835
|
-
});
|
|
836
|
-
return this.client.importAddresses({
|
|
837
|
-
pubKey: this.authPubKey,
|
|
838
|
-
payload: addedAddresses
|
|
839
|
-
});
|
|
840
|
-
}
|
|
841
|
-
|
|
842
|
-
async signTx(params) {
|
|
843
|
-
const { tx, keys, passphrase, signingKeys, changeAddressIdx } = params;
|
|
844
|
-
const utxos = params.utxos || [];
|
|
845
|
-
if (!utxos.length) {
|
|
846
|
-
await new Promise<void>((resolve, reject) => {
|
|
847
|
-
this.getUtxos()
|
|
848
|
-
.pipe(new ParseApiStream())
|
|
849
|
-
.on('data', utxo => utxos.push(utxo))
|
|
850
|
-
.on('end', () => resolve())
|
|
851
|
-
.on('err', err => reject(err));
|
|
852
|
-
});
|
|
853
|
-
}
|
|
854
|
-
let addresses = [];
|
|
855
|
-
let decryptedKeys;
|
|
856
|
-
let decryptPrivateKeys = true;
|
|
857
|
-
if (!signingKeys) {
|
|
858
|
-
if (!keys) {
|
|
859
|
-
for (const utxo of utxos) {
|
|
860
|
-
addresses.push(utxo.address);
|
|
861
|
-
}
|
|
862
|
-
addresses = addresses.length > 0 ? addresses : await this.getAddresses();
|
|
863
|
-
decryptedKeys = await this.storage.getStoredKeys({
|
|
864
|
-
addresses,
|
|
865
|
-
name: this.name,
|
|
866
|
-
});
|
|
867
|
-
} else {
|
|
868
|
-
addresses.push(keys[0]);
|
|
869
|
-
for (const element of utxos) {
|
|
870
|
-
const keyToDecrypt = keys.find(key => key.address === element.address);
|
|
871
|
-
addresses.push(keyToDecrypt);
|
|
872
|
-
}
|
|
873
|
-
const decryptedParams = Encryption.bitcoinCoreDecrypt(addresses, passphrase);
|
|
874
|
-
decryptedKeys = [...decryptedParams.jsonlDecrypted];
|
|
875
|
-
decryptPrivateKeys = false;
|
|
876
|
-
}
|
|
877
|
-
}
|
|
878
|
-
if (this.isUtxoChain()) {
|
|
879
|
-
// If changeAddressIdx == null, then save the change key at the current addressIndex (just in case)
|
|
880
|
-
const changeKey = await this.derivePrivateKey(true, changeAddressIdx == null ? this.addressIndex : changeAddressIdx);
|
|
881
|
-
await this.importKeys({ keys: [changeKey] });
|
|
882
|
-
}
|
|
883
|
-
|
|
884
|
-
// Shallow copy to avoid mutation if signingKeys are passed in
|
|
885
|
-
const keysForSigning = [...(signingKeys || decryptedKeys)];
|
|
886
|
-
|
|
887
|
-
if (decryptPrivateKeys) {
|
|
888
|
-
for (const key of keysForSigning) {
|
|
889
|
-
let privKeyBuf: Buffer | undefined;
|
|
890
|
-
try {
|
|
891
|
-
privKeyBuf = Encryption.decryptToBuffer(key.privKey, key.pubKey, this.unlocked.encryptionKey);
|
|
892
|
-
|
|
893
|
-
// Convert buffer to chain-specific native format (e.g., WIF for BTC, hex for ETH, base58 for SOL)
|
|
894
|
-
const nativePrivKey = Deriver.bufferToPrivateKey_TEMP(this.chain, this.network, privKeyBuf);
|
|
895
|
-
|
|
896
|
-
key.privKey = nativePrivKey;
|
|
897
|
-
} catch (e) {
|
|
898
|
-
console.error('Failed to decrypt/convert private key:', e);
|
|
899
|
-
continue;
|
|
900
|
-
} finally {
|
|
901
|
-
// Zero out the buffer immediately after use
|
|
902
|
-
if (Buffer.isBuffer(privKeyBuf)) {
|
|
903
|
-
privKeyBuf.fill(0);
|
|
904
|
-
}
|
|
905
|
-
}
|
|
906
|
-
}
|
|
907
|
-
}
|
|
908
|
-
|
|
909
|
-
const payload = {
|
|
910
|
-
chain: this.chain,
|
|
911
|
-
network: this.network,
|
|
912
|
-
tx,
|
|
913
|
-
keys: keysForSigning,
|
|
914
|
-
key: keysForSigning[0],
|
|
915
|
-
utxos
|
|
916
|
-
};
|
|
917
|
-
return Transactions.sign({ ...payload });
|
|
918
|
-
}
|
|
919
|
-
|
|
920
|
-
async checkWallet() {
|
|
921
|
-
return this.client.checkWallet({
|
|
922
|
-
pubKey: this.authPubKey
|
|
923
|
-
});
|
|
924
|
-
}
|
|
925
|
-
|
|
926
|
-
async syncAddresses(withChangeAddress = false) {
|
|
927
|
-
const addresses = new Array<string>();
|
|
928
|
-
if (this.addressIndex !== undefined) {
|
|
929
|
-
for (let i = 0; i < this.addressIndex; i++) {
|
|
930
|
-
addresses.push(this.deriveAddress(i, false));
|
|
931
|
-
if (withChangeAddress) {
|
|
932
|
-
addresses.push(this.deriveAddress(i, true));
|
|
933
|
-
}
|
|
934
|
-
}
|
|
935
|
-
}
|
|
936
|
-
return this.client.importAddresses({
|
|
937
|
-
pubKey: this.authPubKey,
|
|
938
|
-
payload: addresses.map(a => ({ address: a }))
|
|
939
|
-
});
|
|
940
|
-
}
|
|
941
|
-
|
|
942
|
-
async getAddresses() {
|
|
943
|
-
const walletAddresses = await this.client.getAddresses({
|
|
944
|
-
pubKey: this.authPubKey
|
|
945
|
-
});
|
|
946
|
-
return walletAddresses.map(walletAddress => walletAddress.address);
|
|
947
|
-
}
|
|
948
|
-
|
|
949
|
-
async getLocalAddress(address) {
|
|
950
|
-
return this.storage.getAddress({ name: this.name, address });
|
|
951
|
-
}
|
|
952
|
-
|
|
953
|
-
async getLocalAddresses(limit?: number, skip?: number) {
|
|
954
|
-
return this.storage.getAddresses({ name: this.name, limit, skip });
|
|
955
|
-
}
|
|
956
|
-
|
|
957
|
-
async checkAddressOnServer(address) {
|
|
958
|
-
const walletAddresses = await this.getAddresses();
|
|
959
|
-
return !!walletAddresses.find(a => a === address);
|
|
960
|
-
}
|
|
961
|
-
|
|
962
|
-
deriveAddress(addressIndex, isChange) {
|
|
963
|
-
if (addressIndex === 0 && this.addressZero) {
|
|
964
|
-
return this.addressZero;
|
|
965
|
-
}
|
|
966
|
-
const address = Deriver.deriveAddress(this.chain, this.network, this.xPubKey, addressIndex, isChange, this.addressType);
|
|
967
|
-
return address;
|
|
968
|
-
}
|
|
969
|
-
|
|
970
|
-
async solSignMessage(privateKey, message) {
|
|
971
|
-
const privKeyBytes = SolKit.getBase58Encoder().encode(privateKey);
|
|
972
|
-
const keypair = await SolKit.createKeyPairFromPrivateKeyBytes(privKeyBytes);
|
|
973
|
-
const encodedMessage = SolKit.getUtf8Encoder().encode(message);
|
|
974
|
-
const signedBytes = await SolKit.signBytes(keypair.privateKey, encodedMessage);
|
|
975
|
-
return SolKit.getBase58Decoder().decode(signedBytes);
|
|
976
|
-
}
|
|
977
|
-
|
|
978
|
-
async getBlockTip() {
|
|
979
|
-
return this.client.getBlockTip();
|
|
980
|
-
}
|
|
981
|
-
|
|
982
|
-
async derivePrivateKey(isChange, addressIndex = this.addressIndex) {
|
|
983
|
-
return Deriver.derivePrivateKey(
|
|
984
|
-
this.chain,
|
|
985
|
-
this.network,
|
|
986
|
-
this.unlocked.masterKey,
|
|
987
|
-
addressIndex || 0,
|
|
988
|
-
isChange,
|
|
989
|
-
this.addressType
|
|
990
|
-
);
|
|
991
|
-
}
|
|
992
|
-
|
|
993
|
-
async nextAddressPair(withChangeAddress?: boolean) {
|
|
994
|
-
return this.generateAddressPair(this.addressIndex, withChangeAddress);
|
|
995
|
-
}
|
|
996
|
-
|
|
997
|
-
async generateAddressPair(addressIndex: number, withChangeAddress?: boolean) {
|
|
998
|
-
if (this.lite) {
|
|
999
|
-
return this.nextAddressPairLite(withChangeAddress);
|
|
1000
|
-
}
|
|
1001
|
-
addressIndex = addressIndex || 0;
|
|
1002
|
-
const newPrivateKey = await this.derivePrivateKey(false, addressIndex);
|
|
1003
|
-
const keys = [newPrivateKey];
|
|
1004
|
-
if (withChangeAddress) {
|
|
1005
|
-
const newChangePrivateKey = await this.derivePrivateKey(true, addressIndex);
|
|
1006
|
-
keys.push(newChangePrivateKey);
|
|
1007
|
-
}
|
|
1008
|
-
if (addressIndex === this.addressIndex) {
|
|
1009
|
-
this.addressIndex++;
|
|
1010
|
-
}
|
|
1011
|
-
await this.importKeys({ keys });
|
|
1012
|
-
if (addressIndex === 0) {
|
|
1013
|
-
this.addressZero = newPrivateKey.address.toString();
|
|
1014
|
-
}
|
|
1015
|
-
await this.saveWallet();
|
|
1016
|
-
return keys.map(key => key.address.toString());
|
|
1017
|
-
}
|
|
1018
|
-
|
|
1019
|
-
async nextAddressPairLite(withChangeAddress?: boolean) {
|
|
1020
|
-
return this.generateAddressPairLite(this.addressIndex, withChangeAddress);
|
|
1021
|
-
}
|
|
1022
|
-
|
|
1023
|
-
async generateAddressPairLite(addressIndex: number, withChangeAddress?: boolean) {
|
|
1024
|
-
addressIndex = addressIndex || 0;
|
|
1025
|
-
const addresses = [];
|
|
1026
|
-
addresses.push(this.deriveAddress(this.addressIndex, false));
|
|
1027
|
-
if (withChangeAddress) {
|
|
1028
|
-
addresses.push(this.deriveAddress(this.addressIndex, true));
|
|
1029
|
-
}
|
|
1030
|
-
if (addressIndex === this.addressIndex) {
|
|
1031
|
-
this.addressIndex++;
|
|
1032
|
-
}
|
|
1033
|
-
await this.client.importAddresses({
|
|
1034
|
-
pubKey: this.authPubKey,
|
|
1035
|
-
payload: addresses
|
|
1036
|
-
});
|
|
1037
|
-
await this.saveWallet();
|
|
1038
|
-
return addresses;
|
|
1039
|
-
}
|
|
1040
|
-
|
|
1041
|
-
async getNonce(_addressIndex: number = 0, isChange?: boolean) {
|
|
1042
|
-
const address = this.deriveAddress(0, isChange);
|
|
1043
|
-
const count = await this.client.getNonce({ address });
|
|
1044
|
-
if (!count || typeof count.nonce !== 'number') {
|
|
1045
|
-
throw new Error('Unable to get nonce');
|
|
1046
|
-
}
|
|
1047
|
-
return count.nonce;
|
|
1048
|
-
}
|
|
1049
|
-
|
|
1050
|
-
private async _getChangeAddress() {
|
|
1051
|
-
if (!this.isUtxoChain()) {
|
|
1052
|
-
return;
|
|
1053
|
-
}
|
|
1054
|
-
const key = await this.derivePrivateKey(true, this.addressIndex);
|
|
1055
|
-
await this.importKeys({ keys: [key] });
|
|
1056
|
-
return key.address;
|
|
1057
|
-
}
|
|
1058
|
-
|
|
1059
|
-
async bumpTxFee({ txid, rawTx, changeIdx, feeRate, feeTarget, feePriority, noRbf, isSweep } = {} as BumpTxFeeType) {
|
|
1060
|
-
if (changeIdx == null && this.isUtxoChain()) {
|
|
1061
|
-
throw new Error('Must provide changeIdx for UTXO chains');
|
|
1062
|
-
}
|
|
1063
|
-
|
|
1064
|
-
const lib = this.getLib();
|
|
1065
|
-
let existingTx;
|
|
1066
|
-
if (rawTx) {
|
|
1067
|
-
if (lib.ethers) {
|
|
1068
|
-
existingTx = lib.ethers.Transaction.from(rawTx);
|
|
1069
|
-
} else {
|
|
1070
|
-
const tx = new lib.Transaction(rawTx);
|
|
1071
|
-
txid = tx.id;
|
|
1072
|
-
}
|
|
1073
|
-
}
|
|
1074
|
-
if (txid) {
|
|
1075
|
-
existingTx = await this.getTransactionByTxid({ txid, populated: this.isUtxoChain() });
|
|
1076
|
-
} else if (!existingTx) {
|
|
1077
|
-
throw new Error('Must provide either rawTx or txid');
|
|
1078
|
-
}
|
|
1079
|
-
|
|
1080
|
-
const params: any = {};
|
|
1081
|
-
|
|
1082
|
-
if (this.isUtxoChain()) {
|
|
1083
|
-
const { coins: { inputs, outputs }, locktime } = existingTx;
|
|
1084
|
-
|
|
1085
|
-
params.utxos = inputs;
|
|
1086
|
-
params.change = outputs.find(o => o.mintIndex == changeIdx).address;
|
|
1087
|
-
params.recipients = outputs.filter(o => o.mintIndex != changeIdx).map(o => ({ address: o.address, amount: o.value }));
|
|
1088
|
-
params.lockUntilBlock = locktime > 0 ? locktime : undefined;
|
|
1089
|
-
params.replaceByFee = !noRbf;
|
|
1090
|
-
params.isSweep = isSweep ?? outputs.length === 1;
|
|
1091
|
-
if (feeRate) {
|
|
1092
|
-
params.feeRate = feeRate;
|
|
1093
|
-
} else {
|
|
1094
|
-
const scale = 1e5; // convert from sat/kb to sat/byte
|
|
1095
|
-
params.feeRate = Math.ceil((await this.getNetworkFee({ target: feeTarget })).feerate * scale);
|
|
1096
|
-
console.log(`Bumping fee rate to ${params.feeRate} sats/byte`);
|
|
1097
|
-
}
|
|
1098
|
-
|
|
1099
|
-
// EVM chains
|
|
1100
|
-
} else {
|
|
1101
|
-
const { nonce, gasLimit, gasPrice, to, data, value, chainId, type } = existingTx;
|
|
1102
|
-
// converting gasLimit and value with toString avoids a bigNumber warning
|
|
1103
|
-
params.nonce = nonce;
|
|
1104
|
-
params.gasLimit = gasLimit?.toString();
|
|
1105
|
-
params.gasPrice = gasPrice;
|
|
1106
|
-
params.data = data;
|
|
1107
|
-
params.chainId = chainId;
|
|
1108
|
-
params.type = type;
|
|
1109
|
-
params.recipients = [{ address: to, amount: value.toString() }];
|
|
1110
|
-
|
|
1111
|
-
// TODO fix type2 support
|
|
1112
|
-
// eslint-disable-next-line no-constant-condition, no-constant-binary-expression
|
|
1113
|
-
if (false && existingTx.type === 2) {
|
|
1114
|
-
if (feeRate) {
|
|
1115
|
-
params.maxGasFee = Web3.utils.toWei(feeRate.toString(), 'gwei');
|
|
1116
|
-
} else {
|
|
1117
|
-
// TODO placeholder until for type2 support is merged in another PR
|
|
1118
|
-
// params.maxGasFee = (await wallet.getNetworkFee({ target: feeTarget })).feerate;
|
|
1119
|
-
// console.log(`Bumping max gas price to ${Web3.utils.fromWei(params.maxGasFee.toString(), 'gwei')} gwei`);
|
|
1120
|
-
}
|
|
1121
|
-
if (feePriority) {
|
|
1122
|
-
params.maxPriorityFee = Web3.utils.toWei(feePriority.toString(), 'gwei');
|
|
1123
|
-
} else {
|
|
1124
|
-
// TODO placeholder until for type2 support is merged in another PR
|
|
1125
|
-
// params.maxPriorityFee = existingTx.maxPriorityFeePerGas;
|
|
1126
|
-
// console.log(`Bumping max priority fee to ${Web3.utils.fromWei(params.maxPriorityFee.toString(), 'gwei')} gwei`);
|
|
1127
|
-
}
|
|
1128
|
-
|
|
1129
|
-
// type 0
|
|
1130
|
-
} else {
|
|
1131
|
-
if (feeRate) {
|
|
1132
|
-
params.gasPrice = Web3.utils.toWei(feeRate.toString(), 'gwei');
|
|
1133
|
-
} else {
|
|
1134
|
-
params.gasPrice = (await this.getNetworkFee({ target: feeTarget })).feerate;
|
|
1135
|
-
console.log(`Bumping gas price to ${Web3.utils.fromWei(params.gasPrice.toString(), 'gwei')} gwei`);
|
|
1136
|
-
}
|
|
1137
|
-
}
|
|
1138
|
-
|
|
1139
|
-
}
|
|
1140
|
-
|
|
1141
|
-
const tx: string = await this.newTx(params);
|
|
1142
|
-
return { tx, params };
|
|
1143
|
-
}
|
|
1144
|
-
|
|
1145
|
-
async getAccountFlags({ index }) {
|
|
1146
|
-
const account = this.deriveAddress(index ?? 0, false);
|
|
1147
|
-
return this.client.getAccountFlags({ address: account });
|
|
1148
|
-
}
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
async estimateGas(params: { to: string; from: string; data: string; value: string }) {
|
|
1152
|
-
return this.client.estimateGas(params);
|
|
1153
|
-
}
|
|
1154
|
-
|
|
1155
|
-
async getL1Fee(rawTx) {
|
|
1156
|
-
try {
|
|
1157
|
-
return this.client.getL1Fee({ rawTx });
|
|
1158
|
-
} catch {
|
|
1159
|
-
return 0;
|
|
1160
|
-
}
|
|
1161
|
-
}
|
|
1162
|
-
|
|
1163
|
-
isMainnet() {
|
|
1164
|
-
return this.network === 'mainnet' || this.network === 'livenet';
|
|
1165
|
-
}
|
|
1166
|
-
|
|
1167
|
-
isUnlocked() {
|
|
1168
|
-
return !!this.unlocked;
|
|
1169
|
-
}
|
|
1170
|
-
}
|
|
1171
|
-
|
|
1172
|
-
export const AddressTypes = {
|
|
1173
|
-
BTC: {
|
|
1174
|
-
// pubkeyhash
|
|
1175
|
-
pubkeyhash: 'pubkeyhash',
|
|
1176
|
-
p2pkh: 'pubkeyhash',
|
|
1177
|
-
|
|
1178
|
-
// scripthash
|
|
1179
|
-
scripthash: 'scripthash',
|
|
1180
|
-
p2sh: 'scripthash',
|
|
1181
|
-
|
|
1182
|
-
// witnesspubkeyhash
|
|
1183
|
-
witnesspubkeyhash: 'witnesspubkeyhash',
|
|
1184
|
-
p2wpkh: 'witnesspubkeyhash',
|
|
1185
|
-
|
|
1186
|
-
// taproot
|
|
1187
|
-
taproot: 'taproot',
|
|
1188
|
-
p2tr: 'taproot'
|
|
1189
|
-
},
|
|
1190
|
-
BCH: {
|
|
1191
|
-
// pubkeyhash
|
|
1192
|
-
pubkeyhash: 'pubkeyhash',
|
|
1193
|
-
p2pkh: 'pubkeyhash',
|
|
1194
|
-
|
|
1195
|
-
// scripthash
|
|
1196
|
-
scripthash: 'scripthash',
|
|
1197
|
-
p2sh: 'scripthash'
|
|
1198
|
-
},
|
|
1199
|
-
LTC: {
|
|
1200
|
-
// pubkeyhash
|
|
1201
|
-
pubkeyhash: 'pubkeyhash',
|
|
1202
|
-
p2pkh: 'pubkeyhash',
|
|
1203
|
-
|
|
1204
|
-
// scripthash
|
|
1205
|
-
scripthash: 'scripthash',
|
|
1206
|
-
p2sh: 'scripthash',
|
|
1207
|
-
|
|
1208
|
-
// witnesspubkeyhash
|
|
1209
|
-
witnesspubkeyhash: 'witnesspubkeyhash',
|
|
1210
|
-
p2wpkh: 'witnesspubkeyhash',
|
|
1211
|
-
},
|
|
1212
|
-
DOGE: {
|
|
1213
|
-
// pubkeyhash
|
|
1214
|
-
pubkeyhash: 'pubkeyhash',
|
|
1215
|
-
p2pkh: 'pubkeyhash',
|
|
1216
|
-
|
|
1217
|
-
// scripthash
|
|
1218
|
-
scripthash: 'scripthash',
|
|
1219
|
-
p2sh: 'scripthash'
|
|
1220
|
-
}
|
|
1221
|
-
};
|