-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathblockchainanchor.js
486 lines (417 loc) · 19.2 KB
/
blockchainanchor.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
/* Copyright 2017 Tierion
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const bitcoin = require('bitcoinjs-lib')
const _ = require('lodash')
const utils = require('./lib/utils.js')
let AVAILABLE_SERVICES = ['insightapi', 'blockcypher']
let SERVICES_TO_USE = []
let BlockchainAnchor = function (anchorOptions) {
// in case 'new' was omitted
if (!(this instanceof BlockchainAnchor)) {
return new BlockchainAnchor(anchorOptions)
}
// set default btc network to mainnet
let btcUseTestnet = false
let btcNetwork = bitcoin.networks.bitcoin
// when btcUseTestnet set to true, testnet is to be used, otherwise defaults to mainnet
if (anchorOptions && anchorOptions.btcUseTestnet !== undefined) {
btcUseTestnet = anchorOptions.btcUseTestnet
btcNetwork = anchorOptions.btcUseTestnet ? bitcoin.networks.testnet : bitcoin.networks.bitcoin
}
// set default sevice selection to 'any', allowing for retrying across services
if (!anchorOptions || anchorOptions.service === undefined || anchorOptions.service === 'any') {
SERVICES_TO_USE = AVAILABLE_SERVICES.slice(0)
}
// if a specific service is chosen, set that as the sole service, provided it is valid
if (anchorOptions && anchorOptions.service !== undefined && anchorOptions.service !== 'any') {
let serviceLowercase = anchorOptions.service.toLowerCase()
if (AVAILABLE_SERVICES.indexOf(serviceLowercase) > -1) {
SERVICES_TO_USE.push(serviceLowercase)
} else {
throw new Error(`Unknown service : ${anchorOptions.service}`)
}
}
let defaultInsightApiBase = `https://${(btcUseTestnet ? 'test-' : '')}insight.bitpay.com/api`
let customInsightApiBase = null
// if insightApiBase is supplied, override default bitpay instance
// be sure that the btcUseTestnet setting matches the configuration of the custom insight-api instance...
// if the instance at insightApiBase is testnet, you must set btcUseTestnet to true, otherwise methods will fail
if (anchorOptions && anchorOptions.insightApiBase !== undefined) {
customInsightApiBase = anchorOptions.insightApiBase
// If insightapi service will be used, and custom uri was also supplied, add that to the services list
if (anchorOptions.service === undefined || anchorOptions.service === 'any' || anchorOptions.service === 'insightapi') SERVICES_TO_USE.unshift('custom-insightapi')
// if a custom insightapi is used, and you do not want to auto fallback to the default in case of failure, remove from list
if (!anchorOptions.insightFallback) _.remove(SERVICES_TO_USE, (x) => { return x === 'insightapi' })
}
let blockcypherToken = null
// check for blockcypherToken
if (anchorOptions && anchorOptions.blockcypherToken !== undefined) {
blockcypherToken = anchorOptions.blockcypherToken
}
if (!blockcypherToken) {
// if no token was supplied, but blockcypher service was requested, throw error
if (anchorOptions && anchorOptions.service === 'blockcypher') throw new Error(`Requested blockcypher, but missing blockcypherToken`)
// if no token was supplied, but other services avialable, remove from services to use
_.remove(SERVICES_TO_USE, (x) => { return x === 'blockcypher' })
}
/// /////////////////////////////////////////
// PUBLIC functions
/// /////////////////////////////////////////
// BTC functions
this.btcOpReturnAsync = async (privateKeyWIF, hexData, feeTotalSat) => {
if (!privateKeyWIF) throw new Error('No privateKeyWIF was provided')
let keyPair, address
try {
// get keyPair for the supplied privateKeyWIF
keyPair = bitcoin.ECPair.fromWIF(privateKeyWIF, btcNetwork)
// derive target address from the keyPair
address = keyPair.getAddress()
} catch (error) {
throw new Error(`Bad privateKeyWIF : ${error.message}`)
}
let txResults
let errors = []
let success = false
for (let index = 0; index < SERVICES_TO_USE.length; index++) {
try {
txResults = await _embedAsync(SERVICES_TO_USE[index], hexData, address, keyPair, feeTotalSat)
success = true
break
} catch (error) {
errors.push(error.message)
}
}
// if none of the services returned successfully, throw error
if (!success) throw new Error(errors)
return txResults
}
this.btcSplitOutputsAsync = async (privateKeyWIF, maxOutputs, feeTotalSat) => {
if (!privateKeyWIF) throw new Error('No privateKeyWIF was provided')
let keyPair, address
try {
// get keyPair for the supplied privateKeyWIF
keyPair = bitcoin.ECPair.fromWIF(privateKeyWIF, btcNetwork)
// derive target address from the keyPair
address = keyPair.getAddress()
} catch (error) {
throw new Error(`Bad privateKeyWIF : ${error.message}`)
}
let txResults
let errors = []
let success = false
for (let index = 0; index < SERVICES_TO_USE.length; index++) {
try {
txResults = await _pushSplitOutputsTxAsync(SERVICES_TO_USE[index], maxOutputs, address, keyPair, feeTotalSat)
success = true
break
} catch (error) {
errors.push(error.message)
}
}
// if none of the services returned successfully, throw error
if (!success) throw new Error(errors)
return txResults
}
this.btcConfirmOpReturnAsync = async (transactionId, expectedValue) => {
let confirmed = false
let errors = []
let success = false
for (let index = 0; index < SERVICES_TO_USE.length; index++) {
try {
confirmed = await _confirmOpReturnAsync(SERVICES_TO_USE[index], transactionId, expectedValue)
success = true
break
} catch (error) {
errors.push(error.message)
}
}
// if none of the services returned successfully, throw error
if (!success) throw new Error(errors)
return confirmed
}
this.btcConfirmBlockHeaderAsync = async (blockHeightOrHash, expectedValue) => {
let confirmed = false
let errors = []
let success = false
for (let index = 0; index < SERVICES_TO_USE.length; index++) {
try {
confirmed = await _confirmBTCBlockHeaderAsync(SERVICES_TO_USE[index], blockHeightOrHash, expectedValue)
success = true
break
} catch (error) {
errors.push(error.message)
}
}
// if none of the services returned successfully, throw error
if (!success) throw new Error(errors)
return confirmed
}
this.btcGetTxStatsAsync = async (transactionId) => {
let txStats
let errors = []
let success = false
for (let index = 0; index < SERVICES_TO_USE.length; index++) {
try {
txStats = await _getBTCTransactionStatsAsync(SERVICES_TO_USE[index], transactionId)
success = true
break
} catch (error) {
errors.push(error.message)
}
}
// if none of the services returned successfully, throw error
if (!success) throw new Error(errors)
return txStats
}
this.btcGetTxConfirmationCountAsync = async (transactionId) => {
let count = 0
let errors = []
let success = false
for (let index = 0; index < SERVICES_TO_USE.length; index++) {
try {
count = await _getBTCTransactionConfirmationCountAsync(SERVICES_TO_USE[index], transactionId)
success = true
break
} catch (error) {
errors.push(error.message)
}
}
// if none of the services returned successfully, throw error
if (!success) throw new Error(errors)
return count
}
this.btcGetBlockStatsAsync = async (blockHeightOrHash) => {
let blockStats
let errors = []
let success = false
for (let index = 0; index < SERVICES_TO_USE.length; index++) {
try {
blockStats = await _getBTCBlockStatsAsync(SERVICES_TO_USE[index], blockHeightOrHash)
success = true
break
} catch (error) {
errors.push(error.message)
}
}
// if none of the services returned successfully, throw error
if (!success) throw new Error(errors)
return blockStats
}
this.btcGetBlockTxIdsAsync = async (blockHeightOrHash) => {
let ids = null
let errors = []
let success = false
for (let index = 0; index < SERVICES_TO_USE.length; index++) {
try {
ids = await _getBTCBlockTxIdsAsync(SERVICES_TO_USE[index], blockHeightOrHash)
success = true
break
} catch (error) {
errors.push(error.message)
}
}
// if none of the services returned successfully, throw error
if (!success) throw new Error(errors)
return ids
}
this.btcGetEstimatedFeeRateSatPerByteAsync = async () => {
let feeRateSatPerByte = null
let errors = []
let success = false
for (let index = 0; index < SERVICES_TO_USE.length; index++) {
try {
feeRateSatPerByte = await _getEstimatedFeeRateSatPerByteAsync(SERVICES_TO_USE[index])
success = true
break
} catch (error) {
errors.push(error.message)
}
}
// if none of the services returned successfully, throw error
if (!success) throw new Error(errors)
return feeRateSatPerByte
}
// ETH functions
this.ethConfirmDataAsync = async (transactionId, expectedValue) => {
let confirmed = false
let errors = []
let success = false
for (let index = 0; index < SERVICES_TO_USE.length; index++) {
try {
confirmed = await _confirmEthDataAsync(SERVICES_TO_USE[index], transactionId, expectedValue)
success = true
break
} catch (error) {
errors.push(error.message)
}
}
// if none of the services returned successfully, throw error
if (!success) throw new Error(errors)
return confirmed
}
/// ///////////////////////////////////////
// Private Utility functions
/// ///////////////////////////////////////
async function _embedAsync (serviceName, hexData, address, keyPair, feeTotalSat) {
// get an instance of the selected service
let blockchainService = utils.getBlockchainService(serviceName)
let serviceOptions = {}
serviceOptions.btcUseTestnet = btcUseTestnet
if (serviceName === 'custom-insightapi') serviceOptions.insightApiBase = customInsightApiBase
if (serviceName === 'insightapi') serviceOptions.insightApiBase = defaultInsightApiBase
if (serviceName === 'blockcypher') serviceOptions.blockcypherToken = blockcypherToken
let unspentOutputs = await blockchainService.getUnspentOutputsAsync(address, serviceOptions)
let spendableOutput = _.orderBy(unspentOutputs, 'amountSatoshi', 'desc')[0]
if (!spendableOutput) throw new Error('No unspent outputs available, balance likely 0')
if (spendableOutput.amountSatoshi < feeTotalSat) throw new Error('No outputs with sufficient funds available')
let tx = new bitcoin.TransactionBuilder(btcNetwork)
tx.addInput(spendableOutput.fromTxHash, spendableOutput.outputIndex)
let buffer = Buffer.from(hexData, 'hex')
var dataScript = bitcoin.script.nullData.output.encode(buffer)
tx.addOutput(dataScript, 0)
let spendableAmountSatoshi = spendableOutput.amountSatoshi
let returnAmountSatoshi = spendableAmountSatoshi - feeTotalSat
tx.addOutput(address, returnAmountSatoshi)
tx.sign(0, keyPair)
let transactionHex = tx.build().toHex()
let txResults = {}
txResults.txId = await blockchainService.pushTransactionAsync(transactionHex, serviceOptions)
txResults.rawTx = transactionHex
return txResults
}
async function _pushSplitOutputsTxAsync (serviceName, maxOutputs, address, keyPair, feeTotalSat) {
// get an instacnce of the selected service
let blockchainService = utils.getBlockchainService(serviceName)
let serviceOptions = {}
serviceOptions.btcUseTestnet = btcUseTestnet
if (serviceName === 'custom-insightapi') serviceOptions.insightApiBase = customInsightApiBase
if (serviceName === 'insightapi') serviceOptions.insightApiBase = defaultInsightApiBase
if (serviceName === 'blockcypher') serviceOptions.blockcypherToken = blockcypherToken
let unspentOutputs = await blockchainService.getUnspentOutputsAsync(address, serviceOptions)
let newOutputCount = maxOutputs
let totalBalanceSatoshi = _.sumBy(unspentOutputs, (x) => { return x.amountSatoshi }) // value of all unspent outputs
let workingBalanceSatoshi = totalBalanceSatoshi - feeTotalSat // deduct the fee, the remainder is to be divided amongst the outputs
let perOutputAmountSatoshi = _.floor(workingBalanceSatoshi / newOutputCount) // amount for each output
// ensure the we dont split the outputs too much, leaving the per output balance too low, reduce output count if needed
while (perOutputAmountSatoshi < 10000) {
if (--newOutputCount < 1) throw new Error('Not enough funds to complete transaction')
perOutputAmountSatoshi = workingBalanceSatoshi / newOutputCount
}
let tx = new bitcoin.TransactionBuilder(btcNetwork)
_(unspentOutputs).forEach((spendableOutput) => {
tx.addInput(spendableOutput.fromTxHash, spendableOutput.outputIndex)
})
for (let x = 0; x < newOutputCount; x++) {
tx.addOutput(address, perOutputAmountSatoshi)
}
for (let x = 0; x < tx.inputs.length; x++) {
tx.sign(x, keyPair)
}
let transactionHex = tx.build().toHex()
let splitResult = {}
splitResult.txId = await blockchainService.pushTransactionAsync(transactionHex, serviceOptions)
splitResult.count = newOutputCount
return splitResult
}
async function _confirmOpReturnAsync (serviceName, transactionId, expectedValue) {
// get an instance of the selected service
let blockchainService = utils.getBlockchainService(serviceName)
let serviceOptions = {}
serviceOptions.btcUseTestnet = btcUseTestnet
if (serviceName === 'custom-insightapi') serviceOptions.insightApiBase = customInsightApiBase
if (serviceName === 'insightapi') serviceOptions.insightApiBase = defaultInsightApiBase
if (serviceName === 'blockcypher') serviceOptions.blockcypherToken = blockcypherToken
let result = await blockchainService.confirmOpReturnAsync(transactionId, expectedValue, serviceOptions)
return result
}
async function _confirmBTCBlockHeaderAsync (serviceName, blockHeightOrHash, expectedValue) {
// get an instance of the selected service
let blockchainService = utils.getBlockchainService(serviceName)
let serviceOptions = {}
serviceOptions.btcUseTestnet = btcUseTestnet
if (serviceName === 'custom-insightapi') serviceOptions.insightApiBase = customInsightApiBase
if (serviceName === 'insightapi') serviceOptions.insightApiBase = defaultInsightApiBase
if (serviceName === 'blockcypher') serviceOptions.blockcypherToken = blockcypherToken
let result = await blockchainService.confirmBTCBlockHeaderAsync(blockHeightOrHash, expectedValue, serviceOptions)
return result
}
async function _getBTCTransactionStatsAsync (serviceName, transactionId) {
// get an instance of the selected service
let blockchainService = utils.getBlockchainService(serviceName)
let serviceOptions = {}
serviceOptions.btcUseTestnet = btcUseTestnet
if (serviceName === 'custom-insightapi') serviceOptions.insightApiBase = customInsightApiBase
if (serviceName === 'insightapi') serviceOptions.insightApiBase = defaultInsightApiBase
if (serviceName === 'blockcypher') serviceOptions.blockcypherToken = blockcypherToken
let result = await blockchainService.getBTCTransactionStatsAsync(transactionId, serviceOptions)
return result
}
async function _getBTCBlockStatsAsync (serviceName, blockHeightOrHash) {
// get an instance of the selected service
let blockchainService = utils.getBlockchainService(serviceName)
let serviceOptions = {}
serviceOptions.btcUseTestnet = btcUseTestnet
if (serviceName === 'custom-insightapi') serviceOptions.insightApiBase = customInsightApiBase
if (serviceName === 'insightapi') serviceOptions.insightApiBase = defaultInsightApiBase
if (serviceName === 'blockcypher') serviceOptions.blockcypherToken = blockcypherToken
let result = await blockchainService.getBTCBlockStatsAsync(blockHeightOrHash, serviceOptions)
return result
}
async function _getBTCTransactionConfirmationCountAsync (serviceName, transactionId) {
// get an instance of the selected service
let blockchainService = utils.getBlockchainService(serviceName)
let serviceOptions = {}
serviceOptions.btcUseTestnet = btcUseTestnet
if (serviceName === 'custom-insightapi') serviceOptions.insightApiBase = customInsightApiBase
if (serviceName === 'insightapi') serviceOptions.insightApiBase = defaultInsightApiBase
if (serviceName === 'blockcypher') serviceOptions.blockcypherToken = blockcypherToken
let result = await blockchainService.getBTCTransactionConfirmationCountAsync(transactionId, serviceOptions)
return result
}
async function _getBTCBlockTxIdsAsync (serviceName, blockHeightOrHash) {
// get an instance of the selected service
let blockchainService = utils.getBlockchainService(serviceName)
let serviceOptions = {}
serviceOptions.btcUseTestnet = btcUseTestnet
if (serviceName === 'custom-insightapi') serviceOptions.insightApiBase = customInsightApiBase
if (serviceName === 'insightapi') serviceOptions.insightApiBase = defaultInsightApiBase
if (serviceName === 'blockcypher') serviceOptions.blockcypherToken = blockcypherToken
let result = await blockchainService.getBTCBlockTxIdsAsync(blockHeightOrHash, serviceOptions)
return result
}
async function _getEstimatedFeeRateSatPerByteAsync (serviceName) {
// get an instance of the selected service
let blockchainService = utils.getBlockchainService(serviceName)
let serviceOptions = {}
serviceOptions.btcUseTestnet = btcUseTestnet
if (serviceName === 'custom-insightapi') serviceOptions.insightApiBase = customInsightApiBase
if (serviceName === 'insightapi') serviceOptions.insightApiBase = defaultInsightApiBase
if (serviceName === 'blockcypher') serviceOptions.blockcypherToken = blockcypherToken
let result = await blockchainService.getEstimatedFeeRateSatPerByteAsync(serviceOptions)
return result
}
async function _confirmEthDataAsync (serviceName, transactionId, expectedValue) {
// get an instance of the selected service
let blockchainService = utils.getBlockchainService(serviceName)
let serviceOptions = {}
serviceOptions.btcUseTestnet = btcUseTestnet
if (serviceName === 'custom-insightapi') serviceOptions.insightApiBase = customInsightApiBase
if (serviceName === 'insightapi') serviceOptions.insightApiBase = defaultInsightApiBase
if (serviceName === 'blockcypher') serviceOptions.blockcypherToken = blockcypherToken
let result = await blockchainService.confirmEthDataAsync(transactionId, expectedValue, serviceOptions)
return result
}
}
module.exports = BlockchainAnchor
module.exports.getInstance = (anchorOptions) => {
return new BlockchainAnchor(anchorOptions)
}