@bitpay-labs/bitcore-client 11.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/README.md +131 -0
  2. package/bin/multi-sig/wallet-derive-address +149 -0
  3. package/bin/wallet +31 -0
  4. package/bin/wallet-balance +62 -0
  5. package/bin/wallet-balance-all +77 -0
  6. package/bin/wallet-broadcast +35 -0
  7. package/bin/wallet-bump-tx +65 -0
  8. package/bin/wallet-check +62 -0
  9. package/bin/wallet-create +46 -0
  10. package/bin/wallet-decrypt +31 -0
  11. package/bin/wallet-delete +21 -0
  12. package/bin/wallet-derive +70 -0
  13. package/bin/wallet-flags +84 -0
  14. package/bin/wallet-import +80 -0
  15. package/bin/wallet-list +31 -0
  16. package/bin/wallet-paypro +175 -0
  17. package/bin/wallet-register +29 -0
  18. package/bin/wallet-send +146 -0
  19. package/bin/wallet-sign +64 -0
  20. package/bin/wallet-sign-message +55 -0
  21. package/bin/wallet-storage +79 -0
  22. package/bin/wallet-token +73 -0
  23. package/bin/wallet-token-rm +33 -0
  24. package/bin/wallet-tx +106 -0
  25. package/bin/wallet-tx-list +92 -0
  26. package/bin/wallet-utxos +28 -0
  27. package/package.json +71 -0
  28. package/src/client.ts +271 -0
  29. package/src/encryption.ts +139 -0
  30. package/src/index.ts +21 -0
  31. package/src/storage/level.ts +171 -0
  32. package/src/storage/mongo.ts +187 -0
  33. package/src/storage/textFile.ts +250 -0
  34. package/src/storage.ts +192 -0
  35. package/src/stream-util.ts +80 -0
  36. package/src/types/index.d.ts +2 -0
  37. package/src/types/storage.d.ts +1 -0
  38. package/src/types/wallet.d.ts +36 -0
  39. package/src/utils.ts +35 -0
  40. package/src/wallet.ts +983 -0
  41. package/test/unit/wallet.test.ts +552 -0
  42. package/ts_build/src/client.d.ts +77 -0
  43. package/ts_build/src/client.d.ts.map +1 -0
  44. package/ts_build/src/client.js +280 -0
  45. package/ts_build/src/client.js.map +1 -0
  46. package/ts_build/src/encryption.d.ts +27 -0
  47. package/ts_build/src/encryption.d.ts.map +1 -0
  48. package/ts_build/src/encryption.js +130 -0
  49. package/ts_build/src/encryption.js.map +1 -0
  50. package/ts_build/src/index.d.ts +11 -0
  51. package/ts_build/src/index.d.ts.map +1 -0
  52. package/ts_build/src/index.js +55 -0
  53. package/ts_build/src/index.js.map +1 -0
  54. package/ts_build/src/storage/level.d.ts +48 -0
  55. package/ts_build/src/storage/level.d.ts.map +1 -0
  56. package/ts_build/src/storage/level.js +194 -0
  57. package/ts_build/src/storage/level.js.map +1 -0
  58. package/ts_build/src/storage/mongo.d.ts +62 -0
  59. package/ts_build/src/storage/mongo.d.ts.map +1 -0
  60. package/ts_build/src/storage/mongo.js +173 -0
  61. package/ts_build/src/storage/mongo.js.map +1 -0
  62. package/ts_build/src/storage/textFile.d.ts +53 -0
  63. package/ts_build/src/storage/textFile.d.ts.map +1 -0
  64. package/ts_build/src/storage/textFile.js +268 -0
  65. package/ts_build/src/storage/textFile.js.map +1 -0
  66. package/ts_build/src/storage.d.ts +63 -0
  67. package/ts_build/src/storage.d.ts.map +1 -0
  68. package/ts_build/src/storage.js +172 -0
  69. package/ts_build/src/storage.js.map +1 -0
  70. package/ts_build/src/stream-util.d.ts +15 -0
  71. package/ts_build/src/stream-util.d.ts.map +1 -0
  72. package/ts_build/src/stream-util.js +81 -0
  73. package/ts_build/src/stream-util.js.map +1 -0
  74. package/ts_build/src/utils.d.ts +8 -0
  75. package/ts_build/src/utils.d.ts.map +1 -0
  76. package/ts_build/src/utils.js +37 -0
  77. package/ts_build/src/utils.js.map +1 -0
  78. package/ts_build/src/wallet.d.ts +229 -0
  79. package/ts_build/src/wallet.d.ts.map +1 -0
  80. package/ts_build/src/wallet.js +806 -0
  81. package/ts_build/src/wallet.js.map +1 -0
  82. package/ts_build/test/unit/wallet.test.d.ts +2 -0
  83. package/ts_build/test/unit/wallet.test.d.ts.map +1 -0
  84. package/ts_build/test/unit/wallet.test.js +533 -0
  85. package/ts_build/test/unit/wallet.test.js.map +1 -0
  86. package/tsconfig.json +40 -0
  87. package/tsconfig.prod.json +6 -0
@@ -0,0 +1,187 @@
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.insertOne({ name, address: key.address, data: toStore });
161
+ if (!params.keepAlive) {
162
+ await this.close();
163
+ }
164
+ } catch (error) {
165
+ console.error(error);
166
+ }
167
+ }
168
+
169
+ async getAddress(params: { name: string; address: string; keepAlive: boolean; open: boolean }) {
170
+ const { name, address, keepAlive, open } = params;
171
+ const data = await this.getKey({ address, name, keepAlive, open });
172
+ if (!data) {
173
+ return null;
174
+ }
175
+ const { pubKey, path } = JSON.parse(data);
176
+ return { address, pubKey, path };
177
+ }
178
+
179
+ async getAddresses(params: { name: string; limit?: number; skip?: number }) {
180
+ const { name, limit, skip } = params;
181
+ const keys = await this.addressCollection.find({ name }, {}, { $limit: limit, $skip: skip }).toArray();
182
+ return keys.map(k => {
183
+ const { pubKey, path } = JSON.parse(k.data);
184
+ return { address: k.address, pubKey, path };
185
+ });
186
+ }
187
+ }
@@ -0,0 +1,250 @@
1
+ import * as fs from 'fs';
2
+ import * as os from 'os';
3
+ import * as stream from 'stream';
4
+ import { IWallet } from 'src/types/wallet';
5
+ import { StreamUtil } from '../stream-util';
6
+ import { Wallet } from '../wallet';
7
+
8
+ export class TextFile {
9
+ db: string;
10
+ walletFileName: string;
11
+ addressFileName: string;
12
+
13
+ constructor(params: { path?: string; createIfMissing: boolean; errorIfExists: boolean }) {
14
+ const { path, createIfMissing } = params;
15
+ let basePath;
16
+ if (!path) {
17
+ basePath = `${os.homedir()}/.bitcore/bitcoreWallet/textWallets`;
18
+ try {
19
+ fs.mkdirSync(basePath);
20
+ } catch (e) {
21
+ if (e.errno !== -17) {
22
+ console.error('Unable to create bitcore storage directory');
23
+ }
24
+ }
25
+ }
26
+ this.db = path || basePath;
27
+ this.walletFileName = this.db + '/wallets.txt';
28
+ this.addressFileName = this.db + '/addresses.txt';
29
+ if (!createIfMissing) {
30
+ const walletPath = fs.existsSync(this.db);
31
+ if (!walletPath) {
32
+ throw new Error('Not a valid wallet path');
33
+ }
34
+ }
35
+ console.log('using wallets at', this.db);
36
+ }
37
+
38
+ async loadWallet(params: { name: string }) {
39
+ const { name } = params;
40
+ return new Promise<void | string>((resolve, reject) => {
41
+ const readStream = fs.createReadStream(this.walletFileName, { flags: 'a+', encoding: 'utf8' });
42
+ readStream.on('error', err => {
43
+ reject(err);
44
+ });
45
+ readStream
46
+ .pipe(StreamUtil.jsonlBufferToObjectMode())
47
+ .on('data', (wallet: IWallet) => {
48
+ if (wallet.name === name) {
49
+ resolve(JSON.stringify(wallet));
50
+ }
51
+ })
52
+ .on('end', () => {
53
+ resolve();
54
+ });
55
+ });
56
+ }
57
+
58
+ async deleteWallet(params: { name: string; keepAddresses?: boolean }) {
59
+ const { name, keepAddresses } = params;
60
+ const wallets: Array<object> = await new Promise((resolve, reject) => {
61
+ const walletArray = [];
62
+ fs.createReadStream(this.walletFileName, { flags: 'r', encoding: 'utf8' })
63
+ .pipe(StreamUtil.jsonlBufferToObjectMode())
64
+ .on('data', wallet => {
65
+ if (wallet.name !== name) {
66
+ walletArray.push(wallet);
67
+ }
68
+ })
69
+ .on('end', () => {
70
+ resolve(walletArray);
71
+ })
72
+ .on('error', err => reject(err));
73
+ });
74
+ await new Promise<void>(resolve => {
75
+ const walletStream = new stream.Readable({ objectMode: true });
76
+ for (const wallet of wallets) {
77
+ walletStream.push(wallet);
78
+ }
79
+ walletStream.push(null);
80
+ const writeStream = fs.createWriteStream(this.walletFileName, { flags: 'w', encoding: 'utf8' });
81
+ walletStream.pipe(StreamUtil.objectModeToJsonlBuffer()).pipe(writeStream);
82
+ writeStream.once('close', () => {
83
+ resolve();
84
+ });
85
+ });
86
+ if (!keepAddresses) {
87
+ const addresses: Array<object> = await new Promise((resolve, reject) => {
88
+ const addressArray = [];
89
+ fs.createReadStream(this.addressFileName, { flags: 'r', encoding: 'utf8' })
90
+ .pipe(StreamUtil.jsonlBufferToObjectMode())
91
+ .on('data', address => {
92
+ if (address.name !== name) {
93
+ addressArray.push(address);
94
+ }
95
+ })
96
+ .on('end', () => {
97
+ resolve(addressArray);
98
+ })
99
+ .on('error', err => reject(err));
100
+ });
101
+ await new Promise<void>(resolve => {
102
+ const addressStream = new stream.Readable({ objectMode: true });
103
+ for (const address of addresses) {
104
+ addressStream.push(address);
105
+ }
106
+ addressStream.push(null);
107
+ const writeStream = fs.createWriteStream(this.addressFileName, { flags: 'w', encoding: 'utf8' });
108
+ addressStream.pipe(StreamUtil.objectModeToJsonlBuffer()).pipe(writeStream);
109
+ writeStream.once('close', () => {
110
+ resolve();
111
+ });
112
+ });
113
+ }
114
+ }
115
+
116
+ async listWallets() {
117
+ return fs
118
+ .createReadStream(this.walletFileName, { flags: 'r', encoding: 'utf8' })
119
+ .pipe(StreamUtil.jsonlBufferToObjectMode())
120
+ .pipe(
121
+ new stream.Transform({
122
+ objectMode: true,
123
+ write(data, enc, next) {
124
+ this.push(JSON.stringify(data));
125
+ next();
126
+ }
127
+ })
128
+ );
129
+ }
130
+
131
+ async listKeys() {
132
+ return fs.createReadStream(this.addressFileName, { flags: 'r', encoding: 'utf8' }).pipe(
133
+ new stream.Transform({
134
+ objectMode: true,
135
+ write(data, enc, next) {
136
+ this.push({
137
+ data: data.value.toString(),
138
+ key: data.key.toString(),
139
+ storageType: 'TextFile'
140
+ });
141
+ next();
142
+ }
143
+ })
144
+ );
145
+ }
146
+
147
+ async saveWallet(params: { wallet: Wallet }) {
148
+ const { wallet } = params;
149
+ delete wallet.storage;
150
+ const wallets: Array<IWallet> = await new Promise((resolve, reject) => {
151
+ const walletArray: IWallet[] = [];
152
+ fs.createReadStream(this.walletFileName, { flags: 'r', encoding: 'utf8' })
153
+ .pipe(StreamUtil.jsonlBufferToObjectMode())
154
+ .on('data', (wallet: IWallet) => {
155
+ walletArray.push(wallet);
156
+ })
157
+ .on('end', () => {
158
+ resolve(walletArray);
159
+ })
160
+ .on('error', err => reject(err));
161
+ });
162
+ const walletAlreadyExists = wallets.find(savedWallet => savedWallet.name === wallet.name);
163
+ if (walletAlreadyExists) {
164
+ await this.deleteWallet({ name: wallet.name, keepAddresses: true });
165
+ }
166
+ return new Promise<void>(resolve => {
167
+ const walletStream = new stream.Readable({ objectMode: true });
168
+ const writeStream = fs.createWriteStream(this.walletFileName, { flags: 'a' });
169
+ walletStream.push(wallet);
170
+ walletStream.push(null);
171
+ walletStream.pipe(StreamUtil.objectModeToJsonlBuffer()).pipe(writeStream);
172
+ writeStream.once('close', () => {
173
+ resolve();
174
+ });
175
+ });
176
+ }
177
+
178
+ async getKey(params: { address: string; name: string; keepAlive: boolean; open: boolean }) {
179
+ const { address, name } = params;
180
+ return new Promise(resolve => {
181
+ fs.createReadStream(this.addressFileName, { flags: 'r', encoding: 'utf8' })
182
+ .pipe(StreamUtil.jsonlBufferToObjectMode())
183
+ .on('data', data => {
184
+ if (data.name === name && data.address === address) {
185
+ resolve(data.toStore);
186
+ }
187
+ })
188
+ .on('end', () => {
189
+ resolve(null);
190
+ });
191
+ });
192
+ }
193
+
194
+ async addKeys(params: { name: string; key: any; toStore: string; keepAlive: boolean; open: boolean }) {
195
+ const { name, key, toStore } = params;
196
+ const objectToSave = { name, address: key.address, toStore };
197
+ return new Promise<void>(resolve => {
198
+ const readStream = new stream.Readable({ objectMode: true });
199
+ const writeStream = fs.createWriteStream(this.addressFileName, { flags: 'a' });
200
+ readStream.push(objectToSave);
201
+ readStream.push(null);
202
+ readStream.pipe(StreamUtil.objectModeToJsonlBuffer()).pipe(writeStream);
203
+ writeStream.once('close', () => {
204
+ resolve();
205
+ });
206
+ });
207
+ }
208
+
209
+ async getAddress(params: { name: string; address: string; keepAlive: boolean; open: boolean }) {
210
+ const { name, address, keepAlive, open } = params;
211
+ const key: any = await this.getKey({ name, address, keepAlive, open });
212
+ if (!key) {
213
+ return null;
214
+ }
215
+ const { pubKey, path } = JSON.parse(key);
216
+ return { address, pubKey, path };
217
+ }
218
+
219
+ async getAddresses(params: { name: string; limit?: number; skip?: number }) {
220
+ const { name, limit, skip } = params;
221
+ const addresses = [];
222
+ let skipped = 0;
223
+ return new Promise((resolve, reject) => {
224
+ const stream = fs.createReadStream(this.addressFileName, { flags: 'r', encoding: 'utf8' });
225
+ stream.pipe(StreamUtil.jsonlBufferToObjectMode())
226
+ .on('data', data => {
227
+ if (data.name === name) {
228
+ if (skipped <= skip) {
229
+ skipped++;
230
+ return;
231
+ }
232
+ if (limit && addresses.length >= limit) {
233
+ stream.destroy();
234
+ resolve(addresses);
235
+ }
236
+
237
+ const address = data.address;
238
+ const valJSON = JSON.parse(data.toStore.toString());
239
+ addresses.push({ address, pubKey: valJSON.pubKey, path: valJSON.path });
240
+ }
241
+ })
242
+ .on(('error'), err => {
243
+ reject(err);
244
+ })
245
+ .on('end', () => {
246
+ resolve(addresses);
247
+ });
248
+ });
249
+ }
250
+ }
package/src/storage.ts ADDED
@@ -0,0 +1,192 @@
1
+ import 'source-map-support/register';
2
+ import { PassThrough } from 'stream';
3
+ import { BitcoreLib } from '@bitpay-labs/crypto-wallet-core';
4
+ import { Encryption } from './encryption';
5
+ import { Level } from './storage/level';
6
+ import { Mongo } from './storage/mongo';
7
+ import { TextFile } from './storage/textFile';
8
+ import { StorageType } from './types/storage';
9
+ import { IWallet, KeyImport } from './types/wallet';
10
+
11
+ export class Storage {
12
+ path: string;
13
+ db: Array<Mongo | Level | TextFile>;
14
+ url?: string;
15
+ errorIfExists?: boolean;
16
+ createIfMissing: boolean;
17
+ storageType: Mongo | Level | TextFile;
18
+
19
+ constructor(params: { path?: string; createIfMissing: boolean; errorIfExists: boolean; storageType?: StorageType }) {
20
+ const { path, createIfMissing, errorIfExists, storageType } = params;
21
+ if (storageType && !['Mongo', 'Level', 'TextFile'].includes(storageType)) {
22
+ throw new Error('Storage Type passed in must be Mongo, Level, or TextFile');
23
+ }
24
+ this.path = path;
25
+ this.createIfMissing = createIfMissing;
26
+ this.errorIfExists = errorIfExists;
27
+ const dbMap = {
28
+ Mongo,
29
+ Level,
30
+ TextFile
31
+ };
32
+ this.db = [];
33
+ if (dbMap[storageType]) {
34
+ this.db.push(new dbMap[storageType]({ createIfMissing, errorIfExists, path }));
35
+ this.storageType = this.db[0];
36
+ } else {
37
+ for (const DbType of Object.values(dbMap)) {
38
+ this.db.push(new DbType({ createIfMissing, errorIfExists, path }));
39
+ }
40
+ }
41
+ }
42
+
43
+ async verifyDbs(dbs: Storage['db']) {
44
+ for await (const db of dbs) {
45
+ if (typeof (db as any).testConnection === 'function') {
46
+ // test mongo connection
47
+ if (!(await (db as any).testConnection())) {
48
+ // remove from dbs
49
+ dbs.splice(dbs.indexOf(db), 1);
50
+ }
51
+ }
52
+ }
53
+ return dbs;
54
+ }
55
+
56
+ async close() {
57
+ (this.storageType as Mongo)?.close?.();
58
+ }
59
+
60
+ async loadWallet(params: { name: string }): Promise<void | IWallet> {
61
+ const { name } = params;
62
+ let wallet: string | void;
63
+ for (const db of await this.verifyDbs(this.db)) {
64
+ try {
65
+ wallet = await db.loadWallet({ name });
66
+ if (wallet) {
67
+ this.storageType = db;
68
+ break;
69
+ }
70
+ } catch { /* ignore */ }
71
+ }
72
+ if (!wallet) {
73
+ return;
74
+ }
75
+ return JSON.parse(wallet) as IWallet;
76
+ }
77
+
78
+ async deleteWallet(params: { name: string }) {
79
+ const { name } = params;
80
+ for (const db of await this.verifyDbs(this.db)) {
81
+ try {
82
+ await db.deleteWallet({ name });
83
+ } catch (e) {
84
+ console.log(e);
85
+ }
86
+ }
87
+ }
88
+
89
+ async listWallets() {
90
+ let passThrough = new PassThrough();
91
+ const dbs = await this.verifyDbs(this.db);
92
+ for (const db of dbs) {
93
+ const listWalletStream = await db.listWallets();
94
+ passThrough = listWalletStream.pipe(passThrough, { end: false });
95
+ listWalletStream.once('end', () => --dbs.length === 0 && passThrough.end());
96
+ }
97
+ return passThrough;
98
+ }
99
+
100
+ async listKeys() {
101
+ let passThrough = new PassThrough();
102
+ const dbs = await this.verifyDbs(this.db);
103
+ for (const db of dbs) {
104
+ const listWalletStream = await db.listKeys();
105
+ passThrough = listWalletStream.pipe(passThrough, { end: false });
106
+ listWalletStream.once('end', () => --dbs.length === 0 && passThrough.end());
107
+ }
108
+ return passThrough;
109
+ }
110
+
111
+ async saveWallet(params) {
112
+ const { wallet } = params;
113
+ return this.storageType.saveWallet({ wallet });
114
+ }
115
+
116
+ async getKey(params: {
117
+ address: string;
118
+ name: string;
119
+ encryptionKey: string;
120
+ keepAlive: boolean;
121
+ open: boolean;
122
+ }): Promise<KeyImport> {
123
+ const { address, name, encryptionKey, keepAlive, open } = params;
124
+ const payload = await this.storageType.getKey({ name, address, keepAlive, open });
125
+ const json = JSON.parse(payload) || payload;
126
+ const { encKey, pubKey } = json;
127
+ if (encryptionKey && pubKey) {
128
+ const decrypted = Encryption.decryptPrivateKey(encKey, pubKey, encryptionKey);
129
+ return JSON.parse(decrypted);
130
+ } else {
131
+ return json;
132
+ }
133
+ }
134
+
135
+ async getKeys(params: { addresses: string[]; name: string; encryptionKey: string }): Promise<Array<KeyImport>> {
136
+ const { addresses, name, encryptionKey } = params;
137
+ const keys = new Array<KeyImport>();
138
+ let keepAlive = true;
139
+ let open = true;
140
+ for (const address of addresses) {
141
+ if (address === addresses[addresses.length - 1]) {
142
+ keepAlive = false;
143
+ }
144
+ try {
145
+ const key = await this.getKey({
146
+ name,
147
+ address,
148
+ encryptionKey,
149
+ keepAlive,
150
+ open
151
+ });
152
+ keys.push(key);
153
+ } catch (err) {
154
+ console.error(err);
155
+ }
156
+ open = false;
157
+ }
158
+ return keys;
159
+ }
160
+
161
+ async addKeys(params: { name: string; keys: KeyImport[]; encryptionKey: string }) {
162
+ const { name, keys, encryptionKey } = params;
163
+ let open = true;
164
+ for (const key of keys) {
165
+ const { path } = key;
166
+ const pubKey = key.pubKey || new BitcoreLib.PrivateKey(key.privKey).publicKey.toString();
167
+ let payload = {};
168
+ if (pubKey && key.privKey && encryptionKey) {
169
+ const toEncrypt = JSON.stringify(key);
170
+ const encKey = Encryption.encryptPrivateKey(toEncrypt, pubKey, encryptionKey);
171
+ payload = { encKey, pubKey, path };
172
+ }
173
+ const toStore = JSON.stringify(payload);
174
+ let keepAlive = true;
175
+ if (key === keys[keys.length - 1]) {
176
+ keepAlive = false;
177
+ }
178
+ await this.storageType.addKeys({ name, key, toStore, keepAlive, open });
179
+ open = false;
180
+ }
181
+ }
182
+
183
+ async getAddress(params: { name: string; address: string }) {
184
+ const { name, address } = params;
185
+ return this.storageType.getAddress({ name, address, keepAlive: true, open: true });
186
+ }
187
+
188
+ async getAddresses(params: { name: string; limit?: number; skip?: number }) {
189
+ const { name, limit, skip } = params;
190
+ return this.storageType.getAddresses({ name, limit, skip });
191
+ }
192
+ }
@@ -0,0 +1,80 @@
1
+ import { Transform } from 'stream';
2
+
3
+ export class ParseApiStream extends Transform {
4
+ constructor() {
5
+ super({ objectMode: true });
6
+ }
7
+
8
+ _write(data, _encoding, cb) {
9
+ const stringDatas = data.toString().split('\n');
10
+ for (const stringData of stringDatas) {
11
+ const normalized = stringData.endsWith(',') ? stringData.slice(0, stringData.length - 1) : stringData;
12
+ if (normalized.includes('{') && normalized.includes('}')) {
13
+ this.push(JSON.parse(normalized));
14
+ }
15
+ }
16
+ cb();
17
+ }
18
+ }
19
+
20
+ function signTxStream(wallet: any, keys: object, utxosPassedIn: object, passphrase: string) {
21
+ return new Transform({
22
+ objectMode: true,
23
+ async transform(chunk, encoding, callback) {
24
+ const rawTransaction = chunk.rawTransaction;
25
+ const utxos = utxosPassedIn || chunk.utxos;
26
+ const signedTx = await wallet.signTx({ tx: rawTransaction, utxos, keys, passphrase });
27
+ chunk.signedRawTransaction = signedTx;
28
+ return callback(null, chunk);
29
+ }
30
+ });
31
+ }
32
+
33
+ function objectModeToJsonlBuffer() {
34
+ return new Transform({
35
+ writableObjectMode: true,
36
+ readableObjectMode: false,
37
+ transform(chunk, encoding, callback) {
38
+ if (typeof chunk !== 'object') {
39
+ return callback(new Error(`invalid data not in form of object: ${chunk}`));
40
+ }
41
+ let jsonl;
42
+ try {
43
+ jsonl = JSON.stringify(chunk).concat('\n');
44
+ callback(null, jsonl);
45
+ } catch (e) {
46
+ return callback(e);
47
+ }
48
+ }
49
+ });
50
+ }
51
+
52
+ function jsonlBufferToObjectMode() {
53
+ return new Transform({
54
+ writableObjectMode: false,
55
+ readableObjectMode: true,
56
+ transform(chunk, encoding, callback) {
57
+ const buffer = chunk;
58
+ const lineArray = buffer.toString().split('\n');
59
+ while (lineArray.length > 1) {
60
+ try {
61
+ const data = lineArray.shift();
62
+ if (data === '') {
63
+ continue;
64
+ }
65
+ const obj = JSON.parse(data);
66
+ this.push(obj);
67
+ } catch (e) {
68
+ return callback(e);
69
+ }
70
+ }
71
+ callback();
72
+ }
73
+ });
74
+ }
75
+
76
+ export const StreamUtil = {
77
+ signTxStream,
78
+ objectModeToJsonlBuffer,
79
+ jsonlBufferToObjectMode
80
+ };
@@ -0,0 +1,2 @@
1
+ export type * as StorageTypes from './storage';
2
+ export type * as WalletTypes from './wallet';