@bitpay-labs/bitcore-client 11.6.6 → 11.7.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 BitPay, Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/bin/wallet-derive CHANGED
@@ -44,20 +44,19 @@ const main = async () => {
44
44
  }
45
45
 
46
46
  while (unusedAddressCounter < gap) {
47
- const address = await wallet.generateAddressPair(index, !noChange);
47
+ const [address, changeAddress] = await wallet.generateAddressPair(index, !noChange);
48
48
 
49
49
  const transactions = await wallet.client.getAddressTxos({ address });
50
+ if (changeAddress) {
51
+ transactions.push(...await wallet.client.getAddressTxos({ address: changeAddress }));
52
+ }
50
53
 
51
54
  if (!transactions.length || !wallet.isUtxoChain()) {
52
55
  unusedAddressCounter++;
53
56
  } else {
54
57
  unusedAddressCounter = 0;
55
58
  }
56
- if (!noChange) {
57
- console.log(`Current change index: ${index}: ${address}`);
58
- } else {
59
- console.log(`Current address index: ${index}: ${address}`);
60
- }
59
+ console.log(`Current address index: ${index}: ${address}${changeAddress ? ` (change: ${changeAddress})` : ''}`);
61
60
  index++;
62
61
  }
63
62
  } catch (e) {
package/bin/wallet-send CHANGED
@@ -88,10 +88,11 @@ const main = async () => {
88
88
  } else if (wallet.isEvmChain()) {
89
89
  const balance = await wallet.getBalance({ tokenName, address: from, hex: true });
90
90
  const tx = await wallet.newTx({ ...params, recipients: [{ address: to, amount: 1 }] }); // create dummy tx to estimate gas
91
- const { data } = wallet.getLib().ethers.utils.parseTransaction(tx);
91
+ const { data } = wallet.getLib().ethers.Transaction.from(tx);
92
92
  const gasLimit = await wallet.estimateGas({ to, from, data, value: BigInt(balance.confirmed).toString() });
93
93
  const l1FeeWei = await wallet.getL1Fee(tx); // OP-stack chains have a "hidden" layer-1 data fee (in wei). Returns 0 for non-OP-stack chains.
94
- const amtToSend = (BigInt(balance.confirmed) - (BigInt(gasLimit) * BigInt(params.feeRate)) - BigInt(l1FeeWei)).toString();
94
+ const feeWei = (BigInt(gasLimit) * BigInt(params.feeRate)) - BigInt(l1FeeWei);
95
+ const amtToSend = (BigInt(balance.confirmed) - (tokenName ? 0n : feeWei)).toString();
95
96
  params.recipients.push({ address: to, amount: amtToSend });
96
97
  params.gasLimit = gasLimit;
97
98
  } else if (wallet.chain.toUpperCase() === 'XRP') {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@bitpay-labs/bitcore-client",
3
3
  "description": "Wallet client for Bitcore-Node",
4
- "version": "11.6.6",
4
+ "version": "11.7.2",
5
5
  "author": "Justin Langston <nitsujlangston@gmail.com>",
6
6
  "main": "./ts_build/src/index.js",
7
7
  "types": "./ts_build/src/index.d.ts",
@@ -23,7 +23,8 @@
23
23
  "watch": "tsc --watch",
24
24
  "precompile": "cd ../bitcore-node && npm run clean && npm run build:prod",
25
25
  "compile": "npm run clean && npm run build",
26
- "test": "npm run compile && mocha --exit -r tsx 'test/**/*.test.ts'",
26
+ "test": "npm run compile && mocha -r tsx --exit 'test/**/*.test.ts'",
27
+ "coverage": "npm run compile && nyc mocha -r tsx --exit 'test/**/*.test.ts'",
27
28
  "precommit": "npm run lint",
28
29
  "lint": "eslint .",
29
30
  "fix:errors": "eslint --fix --quiet .",
@@ -31,8 +32,8 @@
31
32
  "fix": "npm run fix:errors"
32
33
  },
33
34
  "dependencies": {
34
- "@bitpay-labs/bitcore-mnemonic": "^11.6.6",
35
- "@bitpay-labs/crypto-wallet-core": "^11.6.6",
35
+ "@bitpay-labs/bitcore-mnemonic": "^11.7.2",
36
+ "@bitpay-labs/crypto-wallet-core": "^11.7.2",
36
37
  "async": "2.5.0",
37
38
  "bcrypt": "5.1.0",
38
39
  "commander": "11.1.0",
@@ -62,10 +63,26 @@
62
63
  "@types/secp256k1": "3.5.0",
63
64
  "chai": "5.1.2",
64
65
  "mocha": "11.1.0",
66
+ "nyc": "^17.1.0",
65
67
  "sinon": "19.0.2",
66
68
  "supertest": "7.0.0",
67
69
  "tsx": "^4.21.0",
68
70
  "typescript": "5.7.3"
69
71
  },
70
- "gitHead": "e091d99915d099863ad3e78dbe867aa7780191e4"
72
+ "nyc": {
73
+ "include": [
74
+ "ts_build/src",
75
+ "src"
76
+ ],
77
+ "reporter": [
78
+ "html",
79
+ "text-summary"
80
+ ],
81
+ "check-coverage": true,
82
+ "lines": 60,
83
+ "functions": 60,
84
+ "branches": 60,
85
+ "statements": 60
86
+ },
87
+ "gitHead": "d7f26cd2fae506cba9bb8965c5a196b13d8f0586"
71
88
  }
package/src/client.ts CHANGED
@@ -194,11 +194,15 @@ export class Client {
194
194
  async importAddresses(params: { pubKey: string; payload: Array<{ address: string }> }): Promise<void> {
195
195
  const { payload, pubKey } = params;
196
196
  const url = `${this.apiUrl}/wallet/${pubKey}`;
197
+ const pageSize = 100;
197
198
 
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) {
199
+ for (let i = 0; i < payload.length; i += pageSize) {
200
+ const body = payload.slice(i, i + pageSize);
201
+ if (payload.length > pageSize) {
202
+ // If we're paginating through a long list of addresses, log progress so the user knows something is happening
203
+ console.log(`Importing addresses ${i + 1}-${i + body.length} of ${payload.length}`);
204
+ }
205
+ if (i >= pageSize) {
202
206
  await utils.sleep(1000); // cooldown
203
207
  }
204
208
 
package/src/encryption.ts CHANGED
@@ -23,33 +23,83 @@ export function encryptEncryptionKey(encryptionKey, password) {
23
23
  return encData;
24
24
  }
25
25
 
26
- export function decryptEncryptionKey(encEncryptionKey, password) {
26
+ export function decryptEncryptionKey(encEncryptionKey, password, toBuffer: true): Buffer;
27
+ export function decryptEncryptionKey(encEncryptionKey, password, toBuffer: false): string;
28
+ export function decryptEncryptionKey(encEncryptionKey, password, toBuffer?: boolean): Buffer | string {
27
29
  const password_hash = Buffer.from(SHA512(password));
28
30
  const key = password_hash.subarray(0, 32);
29
31
  const iv = password_hash.subarray(32, 48);
30
32
  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
+ let payload: Buffer | undefined;
35
+ let final: Buffer | undefined;
36
+ let output: Buffer | undefined;
37
+ try {
38
+ payload = decipher.update(encEncryptionKey, 'hex');
39
+ final = decipher.final();
40
+ output = Buffer.concat([payload, final]);
41
+ return toBuffer ? output : output.toString('hex');
42
+ } finally {
43
+ payload.fill(0);
44
+ final.fill(0);
45
+ if (!toBuffer) {
46
+ // Don't fill output if it's what's returned directly
47
+ output.fill(0);
48
+ }
49
+ }
33
50
  }
34
51
 
52
+ /** @deprecated - Use encryptBuffer */
35
53
  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;
54
+ encryptionKey = Buffer.from(encryptionKey, 'hex');
55
+ privKey = Buffer.from(privKey, 'utf8');
56
+ return encryptBuffer(privKey, pubKey, encryptionKey).toString('hex');
42
57
  }
43
58
 
44
- function decryptPrivateKey(encPrivateKey: string, pubKey: string, encryptionKey: string) {
45
- const key = Buffer.from(encryptionKey, 'hex');
59
+ function decryptPrivateKey(encPrivateKey: string, pubKey: string, encryptionKey: Buffer | string) {
60
+ if (!Buffer.isBuffer(encryptionKey)) {
61
+ encryptionKey = Buffer.from(encryptionKey, 'hex');
62
+ }
46
63
  const doubleHash = Buffer.from(SHA256(SHA256(pubKey)), 'hex');
47
64
  const iv = doubleHash.subarray(0, 16);
48
- const decipher = crypto.createDecipheriv(algo, key, iv);
65
+ const decipher = crypto.createDecipheriv(algo, encryptionKey, iv);
49
66
  const decrypted = decipher.update(encPrivateKey, 'hex', 'utf8') + decipher.final('utf8');
50
67
  return decrypted;
51
68
  }
52
69
 
70
+ function encryptBuffer(data: Buffer, pubKey: string, encryptionKey: Buffer): Buffer {
71
+ let payload: Buffer | undefined;
72
+ try {
73
+ const iv = Buffer.from(SHA256(SHA256(pubKey)), 'hex').subarray(0, 16);
74
+ const cipher = crypto.createCipheriv(algo, encryptionKey, iv);
75
+ payload = cipher.update(data);
76
+ return Buffer.concat([payload, cipher.final()]);
77
+ } finally {
78
+ if (Buffer.isBuffer(payload)) {
79
+ payload.fill(0);
80
+ }
81
+ }
82
+ }
83
+
84
+ function decryptToBuffer(encHex: string, pubKey: string, encryptionKey: Buffer): Buffer {
85
+ let decrypted: Buffer | undefined;
86
+ let final: Buffer | undefined;
87
+ try {
88
+ const iv = Buffer.from(SHA256(SHA256(pubKey)), 'hex').subarray(0, 16);
89
+ const decipher = crypto.createDecipheriv(algo, encryptionKey, iv);
90
+ decrypted = decipher.update(encHex, 'hex');
91
+ final = decipher.final();
92
+ return Buffer.concat([decrypted, final]);
93
+ } finally {
94
+ if (Buffer.isBuffer(decrypted)) {
95
+ decrypted.fill(0);
96
+ }
97
+ if (Buffer.isBuffer(final)) {
98
+ final.fill(0);
99
+ }
100
+ }
101
+ }
102
+
53
103
  function sha512KDF(passphrase: string, salt: Buffer, derivationOptions: { rounds?: number }): string {
54
104
  const rounds = derivationOptions.rounds || 1;
55
105
  // if salt was sent in as a string, we will have to assume the default encoding type
@@ -134,6 +184,8 @@ export const Encryption = {
134
184
  decryptEncryptionKey,
135
185
  encryptPrivateKey,
136
186
  decryptPrivateKey,
187
+ encryptBuffer,
188
+ decryptToBuffer,
137
189
  generateEncryptionKey,
138
190
  bitcoinCoreDecrypt
139
191
  };
@@ -157,7 +157,11 @@ export class Mongo {
157
157
  await this.init();
158
158
  }
159
159
  const { name, key, toStore } = params;
160
- await this.addressCollection.insertOne({ name, address: key.address, data: toStore });
160
+ await this.addressCollection.updateOne(
161
+ { name, address: key.address },
162
+ { $set: { name, address: key.address, data: toStore } },
163
+ { upsert: true }
164
+ );
161
165
  if (!params.keepAlive) {
162
166
  await this.close();
163
167
  }
@@ -1,6 +1,7 @@
1
1
  import * as fs from 'fs';
2
2
  import * as os from 'os';
3
3
  import * as stream from 'stream';
4
+ import { pipeline } from 'stream/promises';
4
5
  import { IWallet } from 'src/types/wallet';
5
6
  import { StreamUtil } from '../stream-util';
6
7
  import { Wallet } from '../wallet';
@@ -193,6 +194,14 @@ export class TextFile {
193
194
 
194
195
  async addKeys(params: { name: string; key: any; toStore: string; keepAlive: boolean; open: boolean }) {
195
196
  const { name, key, toStore } = params;
197
+ /**
198
+ * `addresses.txt` is stored as JSONL: one address record per line.
199
+ *
200
+ * That line-oriented contract matters beyond normal reads/writes. The migration
201
+ * rewrite path reparses the file as individual JSON records, transforms selected
202
+ * records, and writes the file back out. If this writer ever stops emitting exactly
203
+ * one serialized address object per line, `migrate()` would need to change too.
204
+ */
196
205
  const objectToSave = { name, address: key.address, toStore };
197
206
  return new Promise<void>(resolve => {
198
207
  const readStream = new stream.Readable({ objectMode: true });
@@ -206,6 +215,71 @@ export class TextFile {
206
215
  });
207
216
  }
208
217
 
218
+ /**
219
+ * Rewrite the address file in place for a specific migration version.
220
+ */
221
+ async migrate(params: { version: number; name: string; keys: any[] }) {
222
+ const { version, name, keys } = params;
223
+ if (version !== 1) {
224
+ throw new Error(`TextFile migration for wallet version ${version} is not supported`);
225
+ }
226
+
227
+ const replacementRecords = new Map(
228
+ keys.map(key => {
229
+ const { path, pubKey } = key;
230
+ if (!pubKey) {
231
+ throw new Error(`pubKey is undefined for ${name}. TextFile migration aborted`);
232
+ }
233
+ const toStore = JSON.stringify({ key: JSON.stringify(key), pubKey, path });
234
+ return [key.address, { name, address: key.address, toStore }];
235
+ })
236
+ );
237
+
238
+ const tempAddressFileName = `${this.addressFileName}.v${version}.migrating`;
239
+
240
+ const migrationTransform = new stream.Transform({
241
+ writableObjectMode: true,
242
+ readableObjectMode: true,
243
+ transform(record, _encoding, callback) {
244
+ try {
245
+ // Not target wallet - pass through unchanged
246
+ if (record.name !== name) {
247
+ this.push(record);
248
+ callback();
249
+ return;
250
+ }
251
+
252
+ const replacement = replacementRecords.get(record.address);
253
+ /**
254
+ * If replacement not in map, indicates a prior-existing address which was not included in the keys to migrate.
255
+ * Warn & fall back to prior.
256
+ */
257
+ if (!replacement) {
258
+ console.warn(`TextFile migration warning: found address ${record.address} for wallet ${name}, but no replacement key was provided. Keeping original record.`);
259
+ }
260
+ this.push(replacement ?? record);
261
+ callback();
262
+ } catch (err) {
263
+ callback(err as Error);
264
+ }
265
+ }
266
+ });
267
+
268
+ try {
269
+ await pipeline(
270
+ fs.createReadStream(this.addressFileName, { flags: 'r', encoding: 'utf8' }),
271
+ StreamUtil.jsonlBufferToObjectMode(),
272
+ migrationTransform,
273
+ StreamUtil.objectModeToJsonlBuffer(),
274
+ fs.createWriteStream(tempAddressFileName, { flags: 'w', encoding: 'utf8' })
275
+ );
276
+ await fs.promises.rename(tempAddressFileName, this.addressFileName);
277
+ } catch (err) {
278
+ await fs.promises.rm(tempAddressFileName, { force: true }).catch(() => undefined);
279
+ throw err;
280
+ }
281
+ }
282
+
209
283
  async getAddress(params: { name: string; address: string; keepAlive: boolean; open: boolean }) {
210
284
  const { name, address, keepAlive, open } = params;
211
285
  const key: any = await this.getKey({ name, address, keepAlive, open });
package/src/storage.ts CHANGED
@@ -8,6 +8,14 @@ import { TextFile } from './storage/textFile';
8
8
  import { StorageType } from './types/storage';
9
9
  import { IWallet, KeyImport } from './types/wallet';
10
10
 
11
+ function tryParse(json: string) {
12
+ try {
13
+ return JSON.parse(json);
14
+ } catch {
15
+ return json;
16
+ }
17
+ }
18
+
11
19
  export class Storage {
12
20
  path: string;
13
21
  db: Array<Mongo | Level | TextFile>;
@@ -57,8 +65,11 @@ export class Storage {
57
65
  (this.storageType as Mongo)?.close?.();
58
66
  }
59
67
 
60
- async loadWallet(params: { name: string }): Promise<void | IWallet> {
61
- const { name } = params;
68
+ async loadWallet(params: { name: string }): Promise<void | IWallet>
69
+ async loadWallet(params: { name: string; raw: true }): Promise<void | string>
70
+ async loadWallet(params: { name: string; raw: false }): Promise<void | IWallet>
71
+ async loadWallet(params: { name: string; raw?: boolean }): Promise<void | IWallet | string> {
72
+ const { name, raw } = params;
62
73
  let wallet: string | void;
63
74
  for (const db of await this.verifyDbs(this.db)) {
64
75
  try {
@@ -72,7 +83,7 @@ export class Storage {
72
83
  if (!wallet) {
73
84
  return;
74
85
  }
75
- return JSON.parse(wallet) as IWallet;
86
+ return raw ? wallet : JSON.parse(wallet) as IWallet;
76
87
  }
77
88
 
78
89
  async deleteWallet(params: { name: string }) {
@@ -113,6 +124,7 @@ export class Storage {
113
124
  return this.storageType.saveWallet({ wallet });
114
125
  }
115
126
 
127
+ /** @deprecated - Use getStoredKey */
116
128
  async getKey(params: {
117
129
  address: string;
118
130
  name: string;
@@ -132,6 +144,7 @@ export class Storage {
132
144
  }
133
145
  }
134
146
 
147
+ /** @deprecated - Use getStoredKeys */
135
148
  async getKeys(params: { addresses: string[]; name: string; encryptionKey: string }): Promise<Array<KeyImport>> {
136
149
  const { addresses, name, encryptionKey } = params;
137
150
  const keys = new Array<KeyImport>();
@@ -158,6 +171,7 @@ export class Storage {
158
171
  return keys;
159
172
  }
160
173
 
174
+ /** @deprecated - Use addKeysSafe */
161
175
  async addKeys(params: { name: string; keys: KeyImport[]; encryptionKey: string }) {
162
176
  const { name, keys, encryptionKey } = params;
163
177
  let open = true;
@@ -189,4 +203,69 @@ export class Storage {
189
203
  const { name, limit, skip } = params;
190
204
  return this.storageType.getAddresses({ name, limit, skip });
191
205
  }
206
+
207
+ async addKeysSafe(params: { name: string; keys: KeyImport[] }) {
208
+ const { name, keys } = params;
209
+ let i = 0;
210
+ for (const key of keys) {
211
+ const { path } = key;
212
+ const pubKey = key.pubKey;
213
+ // key.privKey is encrypted - cannot be directly used to retrieve pubKey if required
214
+ if (!pubKey) {
215
+ throw new Error(`pubKey is undefined for ${name}. Keys not added to storage`);
216
+ }
217
+ let payload = {};
218
+ if (pubKey) {
219
+ payload = { key: JSON.stringify(key), pubKey, path };
220
+ }
221
+ const toStore = JSON.stringify(payload);
222
+ // open on first, close on last
223
+ await this.storageType.addKeys({ name, key, toStore, open: i === 0, keepAlive: i < keys.length - 1 });
224
+ ++i;
225
+ }
226
+ }
227
+
228
+ async getStoredKeys(params: { addresses: string[]; name: string }): Promise<Array<any>> {
229
+ const { addresses, name } = params;
230
+ const keys = new Array<any>();
231
+ let i = 0;
232
+ for (const address of addresses) {
233
+ try {
234
+ const key = await this.getStoredKey({
235
+ name,
236
+ address,
237
+ open: i === 0, // open on first
238
+ keepAlive: i < addresses.length - 1, // close on last
239
+ });
240
+ if (key) {
241
+ keys.push(key);
242
+ } else {
243
+ console.warn(`Key not found for address ${address}`);
244
+ }
245
+ } catch (err) {
246
+ // don't continue from catch - i must be incremented
247
+ console.error(err);
248
+ }
249
+ ++i;
250
+ }
251
+ return keys;
252
+ }
253
+
254
+ private async getStoredKey(params: {
255
+ address: string;
256
+ name: string;
257
+ keepAlive: boolean;
258
+ open: boolean;
259
+ }): Promise<any> {
260
+ const { address, name, keepAlive, open } = params;
261
+ const payload = await this.storageType.getKey({ name, address, keepAlive, open });
262
+ // Note: payload could be undefined if the server has an address that local storage did not save
263
+ const json = tryParse(payload) || payload;
264
+ const { key } = json || {}; // pubKey available - not needed
265
+ if (key) {
266
+ return JSON.parse(key);
267
+ } else {
268
+ return json;
269
+ }
270
+ }
192
271
  }