@bitpay-labs/bitcore-client 11.11.5 → 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.
Files changed (35) hide show
  1. package/package.json +13 -8
  2. package/ts_build/src/wallet.d.ts +3 -3
  3. package/.mocharc.json +0 -6
  4. package/LICENSE +0 -21
  5. package/mcr.config.js +0 -16
  6. package/src/client.ts +0 -275
  7. package/src/encryption.ts +0 -191
  8. package/src/index.ts +0 -21
  9. package/src/storage/level.ts +0 -171
  10. package/src/storage/mongo.ts +0 -191
  11. package/src/storage/textFile.ts +0 -327
  12. package/src/storage.ts +0 -271
  13. package/src/stream-util.ts +0 -80
  14. package/src/types/index.d.ts +0 -2
  15. package/src/types/storage.d.ts +0 -1
  16. package/src/types/wallet.d.ts +0 -36
  17. package/src/utils.ts +0 -35
  18. package/src/wallet.ts +0 -1221
  19. package/test/unit/data/ethMigrationTestWallet.fixture.ts +0 -68
  20. package/test/unit/wallet.arc.test.ts +0 -10
  21. package/test/unit/wallet.test.ts +0 -1177
  22. package/ts_build/test/unit/data/ethMigrationTestWallet.fixture.d.ts +0 -51
  23. package/ts_build/test/unit/data/ethMigrationTestWallet.fixture.d.ts.map +0 -1
  24. package/ts_build/test/unit/data/ethMigrationTestWallet.fixture.js +0 -68
  25. package/ts_build/test/unit/data/ethMigrationTestWallet.fixture.js.map +0 -1
  26. package/ts_build/test/unit/wallet.arc.test.d.ts +0 -2
  27. package/ts_build/test/unit/wallet.arc.test.d.ts.map +0 -1
  28. package/ts_build/test/unit/wallet.arc.test.js +0 -12
  29. package/ts_build/test/unit/wallet.arc.test.js.map +0 -1
  30. package/ts_build/test/unit/wallet.test.d.ts +0 -2
  31. package/ts_build/test/unit/wallet.test.d.ts.map +0 -1
  32. package/ts_build/test/unit/wallet.test.js +0 -1037
  33. package/ts_build/test/unit/wallet.test.js.map +0 -1
  34. package/tsconfig.json +0 -40
  35. package/tsconfig.prod.json +0 -6
@@ -1,171 +0,0 @@
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: ' + this.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
- }
@@ -1,191 +0,0 @@
1
- import 'source-map-support/register';
2
- import { Transform } from 'stream';
3
- import { Db, MongoClient } from 'mongodb';
4
-
5
- export class Mongo {
6
- path: string;
7
- db: Db;
8
- walletCollectionName: string = 'wallets';
9
- addressCollectionName: string = 'walletaddresses';
10
- walletCollection: any;
11
- addressCollection: any;
12
- errorIfExists?: boolean;
13
- createIfMissing: boolean;
14
- storageType: string;
15
- databaseName: string;
16
- client: MongoClient;
17
- port: string;
18
-
19
- constructor(params: { path?: string; createIfMissing: boolean; errorIfExists: boolean }) {
20
- const { path, createIfMissing, errorIfExists } = params;
21
- if (path) {
22
- this.path = path;
23
- const databasePath = path.split('/');
24
- if (databasePath[databasePath.length - 1] === '') {
25
- databasePath.pop();
26
- }
27
- this.databaseName = databasePath.pop();
28
- } else {
29
- this.path = 'mongodb://localhost/bitcoreWallet';
30
- this.databaseName = 'bitcoreWallets';
31
- }
32
- this.createIfMissing = createIfMissing;
33
- this.errorIfExists = errorIfExists;
34
- }
35
-
36
- async init() {
37
- if (this.db) {
38
- return;
39
- }
40
- try {
41
- this.client = new MongoClient(this.path, { useNewUrlParser: true, useUnifiedTopology: true });
42
- await this.client.connect();
43
- this.db = this.client.db(this.databaseName);
44
- this.walletCollection = this.db.collection(this.walletCollectionName);
45
- this.addressCollection = this.db.collection(this.addressCollectionName);
46
- await this.walletCollection.createIndex({ name: 1 });
47
- await this.addressCollection.createIndex({ name: 1 });
48
- } catch { /* ignore */ }
49
- }
50
-
51
- async close() {
52
- await this.client?.close();
53
- this.client = null;
54
- this.db = null;
55
- }
56
-
57
- async testConnection() {
58
- try {
59
- const client = new MongoClient(this.path, {
60
- useNewUrlParser: true,
61
- useUnifiedTopology: true,
62
- noDelay: true,
63
- serverSelectionTimeoutMS: 5000
64
- });
65
- await client.connect();
66
- await client.close();
67
- return true;
68
- } catch {
69
- return false;
70
- }
71
- }
72
-
73
- async listWallets() {
74
- await this.init();
75
- const stream = new Transform({
76
- objectMode: true,
77
- transform(data, enc, next) {
78
- this.push(JSON.stringify(data));
79
- next();
80
- }
81
- });
82
- const cursor = this.walletCollection
83
- .find({ name: { $exists: true } }, { name: 1, chain: 1, network: 1, storageType: 1, tokens: 1 })
84
- .pipe(stream);
85
- stream.on('end', async () => await this.close());
86
- return cursor;
87
- }
88
-
89
- async listKeys() {
90
- await this.init();
91
- const stream = new Transform({
92
- objectMode: true,
93
- transform(data, enc, next) {
94
- this.push(JSON.parse(JSON.stringify(data)));
95
- next();
96
- }
97
- });
98
- const cursor = this.addressCollection.find({}, { name: 1, key: 1, toStore: 1, storageType: 1 }).pipe(stream);
99
- stream.on('end', async () => await this.close());
100
- return cursor;
101
- }
102
-
103
- async saveWallet(params) {
104
- const { wallet } = params;
105
- await this.init();
106
- if (wallet.lite) {
107
- delete wallet.masterKey;
108
- delete wallet.pubKey;
109
- }
110
- wallet.authKey = wallet.authKey.toString('hex');
111
- try {
112
- delete wallet.storage;
113
- delete wallet.client;
114
- delete wallet._id;
115
- await this.walletCollection.updateOne({ name: wallet.name }, { $set: wallet }, { upsert: 1 });
116
- await this.close();
117
- } catch (error) {
118
- console.error(error);
119
- }
120
- return;
121
- }
122
-
123
- async loadWallet(params: { name: string }) {
124
- await this.init();
125
- const { name } = params;
126
- const wallet = await this.walletCollection.findOne({ name });
127
- await this.close();
128
- if (!wallet) {
129
- return;
130
- }
131
- return JSON.stringify(wallet);
132
- }
133
-
134
- async deleteWallet(params: { name: string }) {
135
- await this.init();
136
- const { name } = params;
137
- await this.walletCollection.deleteOne({ name });
138
- await this.addressCollection.deleteMany({ name });
139
- await this.close();
140
- }
141
-
142
- async getKey(params: { address: string; name: string; keepAlive: boolean; open: boolean }) {
143
- if (params.open) {
144
- await this.init();
145
- }
146
- const { address, name } = params;
147
- const key = await this.addressCollection.findOne({ name, address });
148
- if (!params.keepAlive) {
149
- await this.close();
150
- }
151
- return key?.data;
152
- }
153
-
154
- async addKeys(params: { name: string; key: any; toStore: string; keepAlive: boolean; open: boolean }) {
155
- try {
156
- if (params.open) {
157
- await this.init();
158
- }
159
- const { name, key, toStore } = params;
160
- await this.addressCollection.updateOne(
161
- { name, address: key.address },
162
- { $set: { name, address: key.address, data: toStore } },
163
- { upsert: true }
164
- );
165
- if (!params.keepAlive) {
166
- await this.close();
167
- }
168
- } catch (error) {
169
- console.error(error);
170
- }
171
- }
172
-
173
- async getAddress(params: { name: string; address: string; keepAlive: boolean; open: boolean }) {
174
- const { name, address, keepAlive, open } = params;
175
- const data = await this.getKey({ address, name, keepAlive, open });
176
- if (!data) {
177
- return null;
178
- }
179
- const { pubKey, path } = JSON.parse(data);
180
- return { address, pubKey, path };
181
- }
182
-
183
- async getAddresses(params: { name: string; limit?: number; skip?: number }) {
184
- const { name, limit, skip } = params;
185
- const keys = await this.addressCollection.find({ name }, {}, { $limit: limit, $skip: skip }).toArray();
186
- return keys.map(k => {
187
- const { pubKey, path } = JSON.parse(k.data);
188
- return { address: k.address, pubKey, path };
189
- });
190
- }
191
- }
@@ -1,327 +0,0 @@
1
- import * as fs from 'fs';
2
- import * as os from 'os';
3
- import * as stream from 'stream';
4
- import { pipeline } from 'stream/promises';
5
- import { IWallet } from 'src/types/wallet';
6
- import { StreamUtil } from '../stream-util';
7
- import { Wallet } from '../wallet';
8
-
9
- export class TextFile {
10
- db: string;
11
- walletFileName: string;
12
- addressFileName: string;
13
-
14
- constructor(params: { path?: string; createIfMissing: boolean; errorIfExists: boolean }) {
15
- const { path, createIfMissing } = params;
16
- let basePath;
17
- if (!path) {
18
- basePath = `${os.homedir()}/.bitcore/bitcoreWallet/textWallets`;
19
- try {
20
- fs.mkdirSync(basePath);
21
- } catch (e) {
22
- if (e.errno !== -17) {
23
- console.error('Unable to create bitcore storage directory');
24
- }
25
- }
26
- }
27
- this.db = path || basePath;
28
- this.walletFileName = this.db + '/wallets.txt';
29
- this.addressFileName = this.db + '/addresses.txt';
30
- if (!createIfMissing) {
31
- const walletPath = fs.existsSync(this.db);
32
- if (!walletPath) {
33
- throw new Error('Not a valid wallet path: ' + this.db);
34
- }
35
- }
36
- console.log('using wallets at', this.db);
37
- }
38
-
39
- async loadWallet(params: { name: string }) {
40
- const { name } = params;
41
- return new Promise<void | string>((resolve, reject) => {
42
- const readStream = fs.createReadStream(this.walletFileName, { flags: 'a+', encoding: 'utf8' });
43
- readStream.on('error', err => {
44
- reject(err);
45
- });
46
- readStream
47
- .pipe(StreamUtil.jsonlBufferToObjectMode())
48
- .on('data', (wallet: IWallet) => {
49
- if (wallet.name === name) {
50
- resolve(JSON.stringify(wallet));
51
- }
52
- })
53
- .on('end', () => {
54
- resolve();
55
- });
56
- });
57
- }
58
-
59
- async deleteWallet(params: { name: string; keepAddresses?: boolean }): Promise<void> {
60
- if (!fs.existsSync(this.walletFileName)) {
61
- return; // nothing to delete if the wallet file doesn't exist
62
- }
63
- const { name, keepAddresses } = params;
64
- const wallets: Array<object> = await new Promise((resolve, reject) => {
65
- const walletArray = [];
66
- fs.createReadStream(this.walletFileName, { flags: 'r', encoding: 'utf8' })
67
- .pipe(StreamUtil.jsonlBufferToObjectMode())
68
- .on('data', wallet => {
69
- if (wallet.name !== name) {
70
- walletArray.push(wallet);
71
- }
72
- })
73
- .on('end', () => {
74
- resolve(walletArray);
75
- })
76
- .on('error', err => reject(err));
77
- });
78
- await new Promise<void>(resolve => {
79
- const walletStream = new stream.Readable({ objectMode: true });
80
- for (const wallet of wallets) {
81
- walletStream.push(wallet);
82
- }
83
- walletStream.push(null);
84
- const writeStream = fs.createWriteStream(this.walletFileName, { flags: 'w', encoding: 'utf8' });
85
- walletStream.pipe(StreamUtil.objectModeToJsonlBuffer()).pipe(writeStream);
86
- writeStream.once('close', () => {
87
- resolve();
88
- });
89
- });
90
- if (!keepAddresses) {
91
- const addresses: Array<object> = await new Promise((resolve, reject) => {
92
- const addressArray = [];
93
- fs.createReadStream(this.addressFileName, { flags: 'r', encoding: 'utf8' })
94
- .pipe(StreamUtil.jsonlBufferToObjectMode())
95
- .on('data', address => {
96
- if (address.name !== name) {
97
- addressArray.push(address);
98
- }
99
- })
100
- .on('end', () => {
101
- resolve(addressArray);
102
- })
103
- .on('error', err => reject(err));
104
- });
105
- await new Promise<void>(resolve => {
106
- const addressStream = new stream.Readable({ objectMode: true });
107
- for (const address of addresses) {
108
- addressStream.push(address);
109
- }
110
- addressStream.push(null);
111
- const writeStream = fs.createWriteStream(this.addressFileName, { flags: 'w', encoding: 'utf8' });
112
- addressStream.pipe(StreamUtil.objectModeToJsonlBuffer()).pipe(writeStream);
113
- writeStream.once('close', () => {
114
- resolve();
115
- });
116
- });
117
- }
118
- }
119
-
120
- async listWallets() {
121
- return fs
122
- .createReadStream(this.walletFileName, { flags: 'r', encoding: 'utf8' })
123
- .pipe(StreamUtil.jsonlBufferToObjectMode())
124
- .pipe(
125
- new stream.Transform({
126
- objectMode: true,
127
- write(data, enc, next) {
128
- this.push(JSON.stringify(data));
129
- next();
130
- }
131
- })
132
- );
133
- }
134
-
135
- async listKeys() {
136
- return fs.createReadStream(this.addressFileName, { flags: 'r', encoding: 'utf8' }).pipe(
137
- new stream.Transform({
138
- objectMode: true,
139
- write(data, enc, next) {
140
- this.push({
141
- data: data.value.toString(),
142
- key: data.key.toString(),
143
- storageType: 'TextFile'
144
- });
145
- next();
146
- }
147
- })
148
- );
149
- }
150
-
151
- async saveWallet(params: { wallet: Wallet }) {
152
- const { wallet } = params;
153
- delete wallet.storage;
154
- const wallets: Array<IWallet> = await new Promise((resolve, reject) => {
155
- const walletArray: IWallet[] = [];
156
- fs.createReadStream(this.walletFileName, { flags: 'r', encoding: 'utf8' })
157
- .pipe(StreamUtil.jsonlBufferToObjectMode())
158
- .on('data', (wallet: IWallet) => {
159
- walletArray.push(wallet);
160
- })
161
- .on('end', () => {
162
- resolve(walletArray);
163
- })
164
- .on('error', err => reject(err));
165
- });
166
- const walletAlreadyExists = wallets.find(savedWallet => savedWallet.name === wallet.name);
167
- if (walletAlreadyExists) {
168
- await this.deleteWallet({ name: wallet.name, keepAddresses: true });
169
- }
170
- return new Promise<void>(resolve => {
171
- const walletStream = new stream.Readable({ objectMode: true });
172
- const writeStream = fs.createWriteStream(this.walletFileName, { flags: 'a' });
173
- walletStream.push(wallet);
174
- walletStream.push(null);
175
- walletStream.pipe(StreamUtil.objectModeToJsonlBuffer()).pipe(writeStream);
176
- writeStream.once('close', () => {
177
- resolve();
178
- });
179
- });
180
- }
181
-
182
- async getKey(params: { address: string; name: string; keepAlive: boolean; open: boolean }) {
183
- const { address, name } = params;
184
- return new Promise(resolve => {
185
- fs.createReadStream(this.addressFileName, { flags: 'r', encoding: 'utf8' })
186
- .pipe(StreamUtil.jsonlBufferToObjectMode())
187
- .on('data', data => {
188
- if (data.name === name && data.address === address) {
189
- resolve(data.toStore);
190
- }
191
- })
192
- .on('end', () => {
193
- resolve(null);
194
- });
195
- });
196
- }
197
-
198
- async addKeys(params: { name: string; key: any; toStore: string; keepAlive: boolean; open: boolean }) {
199
- const { name, key, toStore } = params;
200
- /**
201
- * `addresses.txt` is stored as JSONL: one address record per line.
202
- *
203
- * That line-oriented contract matters beyond normal reads/writes. The migration
204
- * rewrite path reparses the file as individual JSON records, transforms selected
205
- * records, and writes the file back out. If this writer ever stops emitting exactly
206
- * one serialized address object per line, `migrate()` would need to change too.
207
- */
208
- const objectToSave = { name, address: key.address, toStore };
209
- return new Promise<void>(resolve => {
210
- const readStream = new stream.Readable({ objectMode: true });
211
- const writeStream = fs.createWriteStream(this.addressFileName, { flags: 'a' });
212
- readStream.push(objectToSave);
213
- readStream.push(null);
214
- readStream.pipe(StreamUtil.objectModeToJsonlBuffer()).pipe(writeStream);
215
- writeStream.once('close', () => {
216
- resolve();
217
- });
218
- });
219
- }
220
-
221
- /**
222
- * Rewrite the address file in place for a specific migration version.
223
- */
224
- async migrate(params: { version: number; name: string; keys: any[] }) {
225
- const { version, name, keys } = params;
226
- if (version !== 1) {
227
- throw new Error(`TextFile migration for wallet version ${version} is not supported`);
228
- }
229
-
230
- const replacementRecords = new Map(
231
- keys.map(key => {
232
- const { path, pubKey } = key;
233
- if (!pubKey) {
234
- throw new Error(`pubKey is undefined for ${name}. TextFile migration aborted`);
235
- }
236
- const toStore = JSON.stringify({ key: JSON.stringify(key), pubKey, path });
237
- return [key.address, { name, address: key.address, toStore }];
238
- })
239
- );
240
-
241
- const tempAddressFileName = `${this.addressFileName}.v${version}.migrating`;
242
-
243
- const migrationTransform = new stream.Transform({
244
- writableObjectMode: true,
245
- readableObjectMode: true,
246
- transform(record, _encoding, callback) {
247
- try {
248
- // Not target wallet - pass through unchanged
249
- if (record.name !== name) {
250
- this.push(record);
251
- callback();
252
- return;
253
- }
254
-
255
- const replacement = replacementRecords.get(record.address);
256
- /**
257
- * If replacement not in map, indicates a prior-existing address which was not included in the keys to migrate.
258
- * Warn & fall back to prior.
259
- */
260
- if (!replacement) {
261
- console.warn(`TextFile migration warning: found address ${record.address} for wallet ${name}, but no replacement key was provided. Keeping original record.`);
262
- }
263
- this.push(replacement ?? record);
264
- callback();
265
- } catch (err) {
266
- callback(err as Error);
267
- }
268
- }
269
- });
270
-
271
- try {
272
- await pipeline(
273
- fs.createReadStream(this.addressFileName, { flags: 'r', encoding: 'utf8' }),
274
- StreamUtil.jsonlBufferToObjectMode(),
275
- migrationTransform,
276
- StreamUtil.objectModeToJsonlBuffer(),
277
- fs.createWriteStream(tempAddressFileName, { flags: 'w', encoding: 'utf8' })
278
- );
279
- await fs.promises.rename(tempAddressFileName, this.addressFileName);
280
- } catch (err) {
281
- await fs.promises.rm(tempAddressFileName, { force: true }).catch(() => undefined);
282
- throw err;
283
- }
284
- }
285
-
286
- async getAddress(params: { name: string; address: string; keepAlive: boolean; open: boolean }) {
287
- const { name, address, keepAlive, open } = params;
288
- const key: any = await this.getKey({ name, address, keepAlive, open });
289
- if (!key) {
290
- return null;
291
- }
292
- const { pubKey, path } = JSON.parse(key);
293
- return { address, pubKey, path };
294
- }
295
-
296
- async getAddresses(params: { name: string; limit?: number; skip?: number }) {
297
- const { name, limit, skip } = params;
298
- const addresses = [];
299
- let skipped = 0;
300
- return new Promise((resolve, reject) => {
301
- const stream = fs.createReadStream(this.addressFileName, { flags: 'r', encoding: 'utf8' });
302
- stream.pipe(StreamUtil.jsonlBufferToObjectMode())
303
- .on('data', data => {
304
- if (data.name === name) {
305
- if (skipped <= skip) {
306
- skipped++;
307
- return;
308
- }
309
- if (limit && addresses.length >= limit) {
310
- stream.destroy();
311
- resolve(addresses);
312
- }
313
-
314
- const address = data.address;
315
- const valJSON = JSON.parse(data.toStore.toString());
316
- addresses.push({ address, pubKey: valJSON.pubKey, path: valJSON.path });
317
- }
318
- })
319
- .on(('error'), err => {
320
- reject(err);
321
- })
322
- .on('end', () => {
323
- resolve(addresses);
324
- });
325
- });
326
- }
327
- }