-
Notifications
You must be signed in to change notification settings - Fork 91
/
service.js
370 lines (314 loc) · 10.3 KB
/
service.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
import { WalletClient } from 'hs-client';
import { displayBalance, toBaseUnits, toDisplayUnits } from '../../utils/balances';
import { service as nodeService } from '../node/service';
import BigNumber from 'bignumber.js';
import { NETWORKS } from '../../constants/networks';
const Sentry = require('@sentry/electron');
const MasterKey = require('hsd/lib/wallet/masterkey');
const Mnemonic = require('hsd/lib/hd/mnemonic');
const WALLET_ID = 'allison';
const randomAddrs = {
[NETWORKS.TESTNET]: 'ts1qfcljt5ylsa9rcyvppvl8k8gjnpeh079drfrmzq',
[NETWORKS.REGTEST]: 'rs1qh57neh8npuxeyxfsl35373vshs0d40cvxx57aj',
[NETWORKS.MAINNET]: 'hs1q5e06h2fcwx9sx38k6skzwkzmm54meudhphkytx',
[NETWORKS.SIMNET]: 'ss1qfrfg6pg7emnx5m53zf4fe24vdtt8thljhyekhj',
};
class WalletService {
constructor() {
nodeService.on('started', this._onNodeStart);
nodeService.on('stopped', this._onNodeStop);
this.nodeService = nodeService;
}
getWalletInfo = async () => {
this._ensureClient();
return this.client.getInfo(WALLET_ID);
};
getAccountInfo = async () => {
this._ensureClient();
return this.client.getAccount(WALLET_ID, 'default');
};
getCoin = async (hash, index) => {
this._ensureClient();
return this.client.getCoin(WALLET_ID, hash, index);
};
getNames = async () => {
await this._selectWallet();
return this.client.execute('getnames');
};
createNewWallet = async (passphraseOrXPub, isLedger) => {
this._ensureClient();
this.didSelectWallet = false;
await this.nodeService.reset();
if (isLedger) {
return this.client.createWallet(WALLET_ID, {
watchOnly: true,
accountKey: passphraseOrXPub,
});
}
const mnemonic = new Mnemonic({bits: 256});
const options = {
passphrase: passphraseOrXPub,
witness: false,
watchOnly: false,
mnemonic: mnemonic.getPhrase(),
};
return this.client.createWallet(WALLET_ID, options);
};
importSeed = async (passphrase, mnemonic) => {
this._ensureClient();
this.didSelectWallet = false;
await this.nodeService.reset();
const options = {
passphrase,
// hsd generates different keys for
// menmonics with trailing whitespace
mnemonic: mnemonic.trim(),
};
const res = await this.client.createWallet(WALLET_ID, options);
await this.client.rescan(0);
return res;
};
generateReceivingAddress = async () => {
this._ensureClient();
return this.client.createAddress(WALLET_ID, 'default');
};
getAuctionInfo = async (name) => {
return this._executeRPC('getauctioninfo', [name]);
};
getTransactionHistory = async () => {
this._ensureClient();
return this.client.getHistory(WALLET_ID, 'default');
};
getPendingTransactions = async () => {
this._ensureClient();
return this.client.getPending(WALLET_ID, 'default');
};
getBids = async () => {
return this._executeRPC('getbids');
};
getMasterHDKey = () => this._ledgerDisabled(
'cannot get HD key for watch-only wallet',
() => this.client.getMaster(WALLET_ID),
);
setPassphrase = (newPass) => this._ledgerDisabled(
'cannot set passphrase for watch-only wallet',
() => this.client.setPassphrase(WALLET_ID, newPass),
);
revealSeed = (passphrase) => this._ledgerDisabled(
'cannot reveal seed phrase for watch-only wallet',
async () => {
const data = await this.getMasterHDKey();
// should always be encrypted - seed cannot be revealed via the UI until
// the user has finished onboarding. checking here for completeness' sake
if (!data.encrypted) {
return data.key.mnemonic.phrase;
}
const parsedData = {
encrypted: data.encrypted,
alg: data.algorithm,
iv: Buffer.from(data.iv, 'hex'),
ciphertext: Buffer.from(data.ciphertext, 'hex'),
n: data.n,
r: data.r,
p: data.p,
};
const mk = new MasterKey(parsedData);
await mk.unlock(passphrase, 100);
return mk.mnemonic.getPhrase();
},
);
estimateTxFee = async (to, amount, feeRate, subtractFee = false) => {
this._ensureClient();
const feeRateBaseUnits = Number(toBaseUnits(feeRate));
const createdTx = await this.client.createTX(WALLET_ID, {
rate: feeRateBaseUnits,
outputs: [{
value: Number(toBaseUnits(amount)),
address: to,
}],
subtractFee,
sign: false,
});
return {
feeRate,
amount: Number(toDisplayUnits(createdTx.fee)),
txSize: Number(new BigNumber(createdTx.fee).div(feeRateBaseUnits).toFixed(3)),
};
};
estimateMaxSend = async (feeRate) => {
const info = await this.getAccountInfo();
const spendable = info.balance.unconfirmed - info.balance.lockedUnconfirmed;
const value = new BigNumber(toDisplayUnits(spendable));
if (value.isZero()) {
return 0;
}
const dummyAddr = randomAddrs[this.networkName];
// Estiamte a 1-output TX consuming entire spendable balance minus fee
const {amount} = await this.estimateTxFee(dummyAddr, value, feeRate, true);
return value - amount;
};
sendOpen = (name) => this._ledgerProxy(
() => this._executeRPC('createopen', [name]),
() => this._executeRPC('sendopen', [name]),
);
sendBid = (name, amount, lockup) => this._ledgerProxy(
() => this._executeRPC('createbid', [name, Number(displayBalance(amount)), Number(displayBalance(lockup))]),
() => this._executeRPC('sendbid', [name, Number(displayBalance(amount)), Number(displayBalance(lockup))]),
);
sendUpdate = (name, json) => this._ledgerProxy(
() => this._executeRPC('createupdate', [name, json]),
() => this._executeRPC('sendupdate', [name, json]),
);
sendReveal = (name) => this._ledgerProxy(
() => this._executeRPC('createreveal', [name]),
() => this._executeRPC('sendreveal', [name]),
);
sendRedeem = (name) => this._ledgerProxy(
() => this._executeRPC('createredeem', [name]),
() => this._executeRPC('sendredeem', [name]),
);
sendRenewal = (name) => this._ledgerProxy(
() => this._executeRPC('createrenewal', [name]),
() => this._executeRPC('sendrenewal', [name]),
);
send = (to, amount, fee) => this._ledgerProxy(
() => this._executeRPC('createsendtoaddress', [to, Number(amount), '', '', false, 'default']),
() => this.client.send(WALLET_ID, {
rate: Number(toBaseUnits(fee)),
outputs: [{
value: Number(toBaseUnits(amount)),
address: to,
}],
}),
);
lock = () => this._ledgerProxy(
() => null,
() => this.client.lock(WALLET_ID),
);
unlock = (passphrase) => this._ledgerProxy(
() => null,
() => this.client.unlock(WALLET_ID, passphrase),
);
isLocked = () => this._ledgerProxy(
() => false,
async () => {
try {
const info = await this.client.getInfo(WALLET_ID);
return info === null || info.master.until === 0;
} catch (e) {
console.error(e);
return true;
}
},
);
getNonce = async (options) => {
this._ensureClient();
return this.client.getNonce(WALLET_ID, options.name, options);
};
importNonce = async (options) => {
return this._executeRPC('importnonce', [options.name, options.address, options.bid]);
};
zap = async () => {
this._ensureClient();
return this.client.zap(WALLET_ID, 'default', 1);
};
importName = (name, start) => {
return this._executeRPC('importname', [name, start]);
};
rpcGetWalletInfo = () => {
return this._executeRPC('getwalletinfo', []);
};
_onNodeStart = async (networkName, network, apiKey) => {
this.networkName = networkName;
const walletOptions = {
network: network,
port: network.walletPort,
apiKey,
};
this.client = new WalletClient(walletOptions);
};
_onNodeStop = async () => {
this.client = null;
this.didSelectWallet = false;
};
_ensureClient() {
if (!this.client) {
throw new Error('no wallet client configured');
}
}
async _selectWallet() {
this._ensureClient();
if (this.didSelectWallet) {
return;
}
if (this.pendingSelection) {
return this.pendingSelection;
}
this.pendingSelection = this.client.execute('selectwallet', [WALLET_ID]);
await this.pendingSelection;
this.pendingSelection = null;
this.didSelectWallet = true;
}
_ledgerProxy = async (onLedger, onNonLedger, shouldConfirmLedger = true) => {
const info = await this.getWalletInfo();
if (info.watchOnly) {
throw new Error('ledger is not currently enabled');
}
return onNonLedger();
};
_ledgerDisabled = (message, onNonLedger) => {
return this._ledgerProxy(() => {
throw new Error(message);
}, onNonLedger, false);
};
async _executeRPC(method, args) {
await this._selectWallet();
return this.client.execute(method, args);
}
}
const service = new WalletService();
service.createNewWallet.suppressLogging = true;
service.importSeed.suppressLogging = true;
service.getMasterHDKey.suppressLogging = true;
service.setPassphrase.suppressLogging = true;
service.revealSeed.suppressLogging = true;
service.unlock.suppressLogging = true;
const sName = 'Wallet';
const methods = {
// stub the start method in case we need it later
start: async () => null,
getWalletInfo: service.getWalletInfo,
getAccountInfo: service.getAccountInfo,
getCoin: service.getCoin,
getNames: service.getNames,
createNewWallet: service.createNewWallet,
importSeed: service.importSeed,
generateReceivingAddress: service.generateReceivingAddress,
getAuctionInfo: service.getAuctionInfo,
getTransactionHistory: service.getTransactionHistory,
getPendingTransactions: service.getPendingTransactions,
getBids: service.getBids,
getMasterHDKey: service.getMasterHDKey,
setPassphrase: service.setPassphrase,
revealSeed: service.revealSeed,
estimateTxFee: service.estimateTxFee,
estimateMaxSend: service.estimateMaxSend,
sendOpen: service.sendOpen,
sendBid: service.sendBid,
sendUpdate: service.sendUpdate,
sendReveal: service.sendReveal,
sendRedeem: service.sendRedeem,
sendRenewal: service.sendRenewal,
send: service.send,
lock: service.lock,
unlock: service.unlock,
isLocked: service.isLocked,
getNonce: service.getNonce,
importNonce: service.importNonce,
zap: service.zap,
importName: service.importName,
rpcGetWalletInfo: service.rpcGetWalletInfo,
};
export async function start(server) {
server.withService(sName, methods);
}