-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathindex.js
584 lines (485 loc) · 17.4 KB
/
index.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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
/*
An npm JavaScript library for front end web apps. Implements a minimal
Bitcoin Cash wallet.
*/
/* eslint-disable no-async-promise-executor */
'use strict'
const BCHJS = require('@psf/bch-js')
const crypto = require('crypto-js')
// Local libraries
const SendBCH = require('./lib/send-bch')
const Utxos = require('./lib/utxos')
const Tokens = require('./lib/tokens')
const AdapterRouter = require('./lib/adapters/router')
const OpReturn = require('./lib/op-return')
const ConsolidateUtxos = require('./lib/consolidate-utxos.js')
// let this
class MinimalBCHWallet {
constructor (hdPrivateKeyOrMnemonic, advancedOptions = {}) {
this.advancedOptions = advancedOptions
// BEGIN Handle advanced options.
// HD Derivation path.
this.hdPath = this.advancedOptions.hdPath || "m/44'/245'/0'/0/0"
// bch-js options.
const bchjsOptions = {}
if (this.advancedOptions.restURL) {
bchjsOptions.restURL = advancedOptions.restURL
}
// JWT token for increased rate limits.
if (this.advancedOptions.apiToken) {
bchjsOptions.apiToken = advancedOptions.apiToken
}
// Basic Auth token for private installations of bch-api.
if (this.advancedOptions.authPass) {
bchjsOptions.authPass = advancedOptions.authPass
}
// Set the sats-per-byte fee rate.
this.fee = 1.2
if (this.advancedOptions.fee) {
this.fee = this.advancedOptions.fee
}
// END Handle advanced options.
// Encapsulae the external libraries.
this.crypto = crypto
this.BCHJS = BCHJS
this.bchjs = new BCHJS(bchjsOptions)
bchjsOptions.bchjs = this.bchjs
// Instantiate the adapter router.
if (advancedOptions.interface === 'consumer-api') {
bchjsOptions.interface = 'consumer-api'
// bchjsOptions.walletService = advancedOptions.walletService
// bchjsOptions.bchWalletApi = advancedOptions.bchWalletApi
}
this.ar = new AdapterRouter(bchjsOptions)
bchjsOptions.ar = this.ar
// Instantiate local libraries.
this.sendBch = new SendBCH(bchjsOptions)
this.utxos = new Utxos(bchjsOptions)
this.tokens = new Tokens(bchjsOptions)
this.opReturn = new OpReturn(bchjsOptions)
this.consolidateUtxos = new ConsolidateUtxos(this)
this.temp = []
this.isInitialized = false
// The create() function returns a promise. When it resolves, the
// walletInfoCreated flag will be set to true. The instance will also
// have a new `walletInfo` property that will contain the wallet information.
this.walletInfoCreated = false
this.walletInfoPromise = this.create(hdPrivateKeyOrMnemonic)
// Bind the 'this' object to all functions
this.create = this.create.bind(this)
this.initialize = this.initialize.bind(this)
this.getUtxos = this.getUtxos.bind(this)
this.getBalance = this.getBalance.bind(this)
this.getTransactions = this.getTransactions.bind(this)
this.getTxData = this.getTxData.bind(this)
this.send = this.send.bind(this)
this.sendTokens = this.sendTokens.bind(this)
this.burnTokens = this.burnTokens.bind(this)
this.listTokens = this.listTokens.bind(this)
this.sendAll = this.sendAll.bind(this)
this.burnAll = this.burnAll.bind(this)
this.getUsd = this.getUsd.bind(this)
this.sendOpReturn = this.sendOpReturn.bind(this)
this.utxoIsValid = this.utxoIsValid.bind(this)
this.getTokenData = this.getTokenData.bind(this)
this.getKeyPair = this.getKeyPair.bind(this)
this.optimize = this.optimize.bind(this)
this.getTokenBalance = this.getTokenBalance.bind(this)
this.getPubKey = this.getPubKey.bind(this)
this.broadcast = this.broadcast.bind(this)
}
// Create a new wallet. Returns a promise that resolves into a wallet object.
async create (mnemonicOrWif) {
// return new Promise(async (resolve, reject) => {
try {
// Attempt to decrypt mnemonic if password is provided.
if (mnemonicOrWif && this.advancedOptions.password) {
mnemonicOrWif = this.decrypt(
mnemonicOrWif,
this.advancedOptions.password
)
}
const walletInfo = {}
// No input. Generate a new mnemonic.
if (!mnemonicOrWif) {
const mnemonic = this.bchjs.Mnemonic.generate(128)
const rootSeedBuffer = await this.bchjs.Mnemonic.toSeed(mnemonic)
const masterHDNode = this.bchjs.HDNode.fromSeed(rootSeedBuffer)
const childNode = masterHDNode.derivePath(this.hdPath)
walletInfo.privateKey = this.bchjs.HDNode.toWIF(childNode)
walletInfo.publicKey = this.bchjs.HDNode.toPublicKey(
childNode
).toString('hex')
walletInfo.mnemonic = mnemonic
walletInfo.address = walletInfo.cashAddress = this.bchjs.HDNode.toCashAddress(
childNode
)
walletInfo.legacyAddress = this.bchjs.HDNode.toLegacyAddress(childNode)
walletInfo.hdPath = this.hdPath
//
} else {
// A WIF will start with L or K, will have no spaces, and will be 52
// characters long.
const startsWithKorL =
mnemonicOrWif &&
(mnemonicOrWif[0].toString().toLowerCase() === 'k' ||
mnemonicOrWif[0].toString().toLowerCase() === 'l')
const is52Chars = mnemonicOrWif && mnemonicOrWif.length === 52
if (startsWithKorL && is52Chars) {
// WIF Private Key
walletInfo.privateKey = mnemonicOrWif
const ecPair = this.bchjs.ECPair.fromWIF(mnemonicOrWif)
// walletInfo.publicKey = ecPair.toPublicKey().toString('hex')
walletInfo.publicKey = this.bchjs.ECPair.toPublicKey(ecPair).toString(
'hex'
)
walletInfo.mnemonic = null
walletInfo.address = walletInfo.cashAddress = this.bchjs.ECPair.toCashAddress(
ecPair
)
walletInfo.legacyAddress = this.bchjs.ECPair.toLegacyAddress(ecPair)
walletInfo.hdPath = null
} else {
// 12-word Mnemonic
const mnemonic = mnemonicOrWif || this.bchjs.Mnemonic.generate(128)
const rootSeedBuffer = await this.bchjs.Mnemonic.toSeed(mnemonic)
const masterHDNode = this.bchjs.HDNode.fromSeed(rootSeedBuffer)
const childNode = masterHDNode.derivePath(this.hdPath)
walletInfo.privateKey = this.bchjs.HDNode.toWIF(childNode)
walletInfo.publicKey = this.bchjs.HDNode.toPublicKey(
childNode
).toString('hex')
walletInfo.mnemonic = mnemonic
walletInfo.address = walletInfo.cashAddress = this.bchjs.HDNode.toCashAddress(
childNode
)
walletInfo.legacyAddress = this.bchjs.HDNode.toLegacyAddress(
childNode
)
walletInfo.hdPath = this.hdPath
}
}
// Encrypt the mnemonic if a password is provided.
if (this.advancedOptions.password) {
walletInfo.mnemonicEncrypted = this.encrypt(
mnemonicOrWif,
this.advancedOptions.password
)
}
walletInfo.slpAddress = this.bchjs.SLP.Address.toSLPAddress(
walletInfo.address
)
this.walletInfoCreated = true
this.walletInfo = walletInfo
return walletInfo
} catch (err) {
// return reject(err)
console.error('Error in create()')
throw err
}
// })
}
// Initialize is called to initialize the UTXO store, download token data, and
// get a balance of the wallet.
async initialize () {
await this.walletInfoPromise
await this.utxos.initUtxoStore(this.walletInfo.address)
this.isInitialized = true
return true
}
// Get the UTXO information for this wallet.
async getUtxos (bchAddress) {
let addr = bchAddress
// If no address is passed in, but the wallet has been initialized, use the
// wallet's address.
if (!bchAddress && this.walletInfo && this.walletInfo.cashAddress) {
addr = this.walletInfo.cashAddress
return this.utxos.initUtxoStore(addr)
}
const utxos = await this.ar.getUtxos(addr)
// console.log(`utxos: ${JSON.stringify(utxos, null, 2)}`)
return utxos
}
// Encrypt the mnemonic of the wallet.
encrypt (mnemonic, password) {
return this.crypto.AES.encrypt(mnemonic, password).toString()
}
// Decrypt the mnemonic of the wallet.
decrypt (mnemonicEncrypted, password) {
let mnemonic
try {
mnemonic = this.crypto.AES.decrypt(mnemonicEncrypted, password).toString(
this.crypto.enc.Utf8
)
} catch (err) {
throw new Error('Wrong password')
}
return mnemonic
}
// Get the balance of the wallet.
async getBalance (inObj = {}) {
const { bchAddress } = inObj
let addr = bchAddress
// If no address is passed in, but the wallet has been initialized, use the
// wallet's address.
if (!bchAddress && this.walletInfo && this.walletInfo.cashAddress) {
addr = this.walletInfo.cashAddress
}
const balances = await this.ar.getBalance(addr)
return balances.balance.confirmed + balances.balance.unconfirmed
}
// Get transactions associated with the wallet.
// Returns an array of object. Each object has a 'tx_hash' and 'height' property.
async getTransactions (bchAddress, sortingOrder = 'DESCENDING') {
let addr = bchAddress
// If no address is passed in, but the wallet has been initialized, use the
// wallet's address.
if (!bchAddress && this.walletInfo && this.walletInfo.cashAddress) {
addr = this.walletInfo.cashAddress
}
// console.log(`Getting transactions for ${addr}`)
const data = await this.ar.getTransactions(addr, sortingOrder)
return data.transactions
}
// Get transaction data for up to 20 TXIDs. txids should be an array. Each
// element should be a string containing a TXID.
async getTxData (txids = []) {
const data = await this.ar.getTxData(txids)
return data
}
// Send BCH. Returns a promise that resolves into a TXID.
// This is a wrapper for the send-bch.js library.
send (outputs) {
try {
// console.log(
// `this.utxos.bchUtxos: ${JSON.stringify(this.utxos.bchUtxos, null, 2)}`
// )
return this.sendBch.sendBch(
outputs,
{
mnemonic: this.walletInfo.mnemonic,
cashAddress: this.walletInfo.address,
hdPath: this.walletInfo.hdPath,
fee: this.fee,
privateKey: this.walletInfo.privateKey
},
// this.utxos.bchUtxos
this.utxos.utxoStore.bchUtxos
)
} catch (err) {
console.error('Error in send()')
throw err
}
}
// Send Tokens. Returns a promise that resolves into a TXID.
// This is a wrapper for the tokens.js library.
sendTokens (output, satsPerByte, opts = {}) {
try {
// console.log(`utxoStore: ${JSON.stringify(this.utxos.utxoStore, null, 2)}`)
// If mining fee is not specified, use the value assigned in the constructor.
if (!satsPerByte) satsPerByte = this.fee
// If output was passed in as an array, use only the first element of the Array.
if (Array.isArray(output)) {
output = output[0]
}
// Combine all Type 1, Group, and NFT token UTXOs. Ignore minting batons.
const tokenUtxos = this.utxos.getSpendableTokenUtxos()
// console.log('msw tokenUtxos: ', tokenUtxos)
return this.tokens.sendTokens(
output,
this.walletInfo,
this.utxos.utxoStore.bchUtxos,
tokenUtxos,
satsPerByte,
opts
)
} catch (err) {
console.error('Error in send()')
throw err
}
}
async burnTokens (qty, tokenId, satsPerByte) {
try {
// console.log(`utxoStore: ${JSON.stringify(this.utxos.utxoStore, null, 2)}`)
// If mining fee is not specified, use the value assigned in the constructor.
if (!satsPerByte) satsPerByte = this.fee
// Combine all Type 1, Group, and NFT token UTXOs. Ignore minting batons.
const tokenUtxos = this.utxos.getSpendableTokenUtxos()
// Generate the transaction.
return this.tokens.burnTokens(
qty,
tokenId,
this.walletInfo,
this.utxos.utxoStore.bchUtxos,
tokenUtxos,
satsPerByte
)
} catch (err) {
console.error('Error in burnTokens()')
throw err
}
}
// Return information on SLP tokens held by this wallet.
listTokens (slpAddress) {
const addr = slpAddress || this.walletInfo.slpAddress
return this.tokens.listTokensFromAddress(addr)
}
// Get the balance for a specific SLP token.
getTokenBalance (inObj = {}) {
const { tokenId, slpAddress } = inObj
const addr = slpAddress || this.walletInfo.slpAddress
return this.tokens.getTokenBalance(tokenId, addr)
}
// Send BCH. Returns a promise that resolves into a TXID.
// This is a wrapper for the send-bch.js library.
sendAll (toAddress) {
try {
return this.sendBch.sendAllBch(
toAddress,
{
mnemonic: this.walletInfo.mnemonic,
cashAddress: this.walletInfo.address,
hdPath: this.walletInfo.hdPath,
fee: this.fee,
privateKey: this.walletInfo.privateKey
},
// this.utxos.bchUtxos
this.utxos.utxoStore.bchUtxos
)
} catch (err) {
console.error('Error in sendAll()')
throw err
}
}
// Burn all the SLP tokens associated to the token ID
async burnAll (tokenId) {
try {
// Combine all Type 1, Group, and NFT token UTXOs. Ignore minting batons.
const tokenUtxos = this.utxos.getSpendableTokenUtxos()
// console.log(`tokenUtxos: ${JSON.stringify(tokenUtxos, null, 2)}`)
// Generate the transaction.
const txid = await this.tokens.burnAll(
tokenId,
this.walletInfo,
this.utxos.utxoStore.bchUtxos,
tokenUtxos
)
return txid
} catch (err) {
console.error('Error in burnAll()')
throw err
}
}
// Get the spot price of BCH in USD.
async getUsd () {
return await this.ar.getUsd()
}
// Generate and broadcast a transaction with an OP_RETURN output.
// Returns the txid of the transactions.
async sendOpReturn (
msg = '',
prefix = '6d02', // Default to memo.cash
bchOutput = [],
satsPerByte = 1.0
) {
try {
// Wait for the wallet to finish initializing.
await this.walletInfoPromise
// console.log(
// `this.utxos.utxoStore ${JSON.stringify(this.utxos.utxoStore, null, 2)}`
// )
const txid = await this.opReturn.sendOpReturn(
this.walletInfo,
this.utxos.utxoStore.bchUtxos,
msg,
prefix,
bchOutput,
satsPerByte
)
return txid
} catch (err) {
console.error('Error in sendOpReturn()')
throw err
}
}
// Validate that a UTXO can be spent.
// const utxo = {
// tx_hash: 'b94e1ff82eb5781f98296f0af2488ff06202f12ee92b0175963b8dba688d1b40',
// tx_pos: 0
// }
// isValid = await wallet.utxoIsValid(utxo)
async utxoIsValid (utxo) {
return await this.ar.utxoIsValid(utxo)
}
// Get mutable and immutable data associated with a token.
async getTokenData (tokenId, withTxHistory = false) {
return await this.ar.getTokenData(tokenId, withTxHistory)
}
// Get token icon and other media
async getTokenData2 (tokenId, updateCache) {
return await this.ar.getTokenData2(tokenId, updateCache)
}
// This method returns an object that contains a private key WIF, public key,
// public address, and the index of the HD wallet that the key pair was
// generated from. If no index is provided, it generates the root key pair
// (index 0).
async getKeyPair (hdIndex = 0) {
await this.walletInfoPromise
const mnemonic = this.walletInfo.mnemonic
if (!mnemonic) {
throw new Error('Wallet does not have a mnemonic. Can not generate a new key pair.')
}
// root seed buffer
const rootSeed = await this.bchjs.Mnemonic.toSeed(mnemonic)
const masterHDNode = this.bchjs.HDNode.fromSeed(rootSeed)
const childNode = masterHDNode.derivePath(`m/44'/245'/0'/0/${hdIndex}`)
const cashAddress = this.bchjs.HDNode.toCashAddress(childNode)
console.log('Generating a new key pair for cashAddress: ', cashAddress)
const wif = this.bchjs.HDNode.toWIF(childNode)
const publicKey = this.bchjs.HDNode.toPublicKey(childNode).toString('hex')
const slpAddress = this.bchjs.SLP.Address.toSLPAddress(cashAddress)
const outObj = {
hdIndex,
wif,
publicKey,
cashAddress,
slpAddress
}
return outObj
}
// Optimize the wallet by consolidating UTXOs. This has the effect of speeding
// up all API calls and improving the UX.
async optimize (dryRun = false) {
return await this.consolidateUtxos.start({ dryRun })
}
// Get token icon and other media
async getPubKey (addr) {
try {
return await this.ar.getPubKey(addr)
} catch (err) {
console.error('Error in minimal-slp-wallet/getPubKey()')
throw err
}
}
// Broadcast a hex-encoded TX to the network
async broadcast (inObj = {}) {
try {
const { hex } = inObj
return await this.ar.sendTx(hex)
} catch (err) {
console.error('Error in minimal-slp-wallet/broadcast()')
throw err
}
}
// Get the cost in PSF tokens to write 1MB of data to the PSFFPP IPFS pinning
// network. Find out more at psffpp.com.
async getPsfWritePrice () {
try {
return await this.ar.getPsfWritePrice()
} catch (err) {
console.error('Error in minimal-slp-wallet/getPsfWritePrice()')
throw err
}
}
}
module.exports = MinimalBCHWallet