-
Notifications
You must be signed in to change notification settings - Fork 15
/
utils.js
1918 lines (1835 loc) · 67.8 KB
/
utils.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
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const axios = require('axios')
const BN = require('bn.js')
const BIP84 = require('bip84')
const CryptoJS = require('crypto-js')
const bjs = require('bitcoinjs-lib')
const bitcoinops = require('bitcoin-ops')
const varuint = require('varuint-bitcoin')
const { VerifyProof, GetProof } = require('eth-proof')
const { encode } = require('eth-util-lite')
const { Log } = require('eth-object')
const Web3 = require('web3')
const syscointx = require('syscointx-js')
const utxoLib = require('@trezor/utxo-lib')
const TrezorConnect = require('trezor-connect').default
const web3 = new Web3()
const bitcoinNetworks = { mainnet: bjs.networks.bitcoin, testnet: bjs.networks.testnet }
/* global localStorage */
const syscoinNetworks = {
mainnet: {
messagePrefix: '\x18Syscoin Signed Message:\n',
bech32: 'sys',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 0x3f,
scriptHash: 0x05,
wif: 0x80
},
testnet: {
messagePrefix: '\x18Syscoin Signed Message:\n',
bech32: 'tsys',
bip32: {
public: 0x043587cf,
private: 0x04358394
},
pubKeyHash: 0x41,
scriptHash: 0xc4,
wif: 0xef
}
}
const bitcoinZPubTypes = { mainnet: { zprv: '04b2430c', zpub: '04b24746' }, testnet: { vprv: '045f18bc', vpub: '045f1cf6' } }
const bitcoinXPubTypes = { mainnet: { zprv: bitcoinNetworks.mainnet.bip32.private, zpub: bitcoinNetworks.mainnet.bip32.public }, testnet: { vprv: bitcoinNetworks.testnet.bip32.private, vpub: bitcoinNetworks.testnet.bip32.public } }
const syscoinZPubTypes = { mainnet: { zprv: '04b2430c', zpub: '04b24746' }, testnet: { vprv: '045f18bc', vpub: '045f1cf6' } }
const syscoinXPubTypes = { mainnet: { zprv: syscoinNetworks.mainnet.bip32.private, zpub: syscoinNetworks.mainnet.bip32.public }, testnet: { vprv: syscoinNetworks.testnet.bip32.private, vpub: syscoinNetworks.testnet.bip32.public } }
const syscoinSLIP44 = 57
const bitcoinSLIP44 = 0
let trezorInitialized = false
const DEFAULT_TREZOR_DOMAIN = 'https://connect.trezor.io/8/'
const ERC20Manager = '0xA738a563F9ecb55e0b2245D1e9E380f0fE455ea1'
const tokenFreezeFunction = '7ca654cf9212e4c3cf0164a529dd6159fc71113f867d0b09fdeb10aa65780732' // token freeze function signature
const axiosConfig = {
withCredentials: true
}
/* fetchNotarizationFromEndPoint
Purpose: Fetch notarization signature via axois from an endPoint URL, see spec for more info: https://github.com/syscoin/sips/blob/master/sip-0002.mediawiki
Param endPoint: Required. Fully qualified URL which will take transaction information and respond with a signature or error on denial
Param txHex: Required. Raw transaction hex
Returns: Returns JSON object in response, signature on success and error on denial of notarization
*/
async function fetchNotarizationFromEndPoint (endPoint, txHex) {
try {
// Use fetch if on browser environment
// eslint-disable-next-line no-undef
if (fetch) {
// eslint-disable-next-line no-undef
const response = await fetch(endPoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ tx: txHex })
})
if (response.ok) {
const data = await response.json()
if (data) {
return data
}
}
} else {
const request = await axios.post(endPoint, { tx: txHex }, axiosConfig)
if (request && request.data) {
return request.data
}
}
return null
} catch (e) {
return e
}
}
/* fetchBackendAsset
Purpose: Fetch asset information from backend Blockbook provider
Param backendURL: Required. Fully qualified URL for blockbook
Param assetGuid: Required. Asset to fetch
Returns: Returns JSON object in response, asset information object in JSON
*/
async function fetchBackendAsset (backendURL, assetGuid) {
try {
let blockbookURL = backendURL.slice()
if (blockbookURL) {
blockbookURL = blockbookURL.replace(/\/$/, '')
}
// eslint-disable-next-line no-undef
if (fetch) {
// eslint-disable-next-line no-undef
const response = await fetch(`${blockbookURL}/api/v2/asset/${assetGuid}?details=basic`)
if (response.ok) {
const data = await response.json()
if (data.asset) {
return data.asset
}
}
} else {
const request = await axios.get(blockbookURL + '/api/v2/asset/' + assetGuid + '?details=basic', axiosConfig)
if (request && request.data && request.data.asset) {
return request.data.asset
}
}
return null
} catch (e) {
return e
}
}
/* fetchBackendListAssets
Purpose: Fetch list of assets from backend Blockbook provider via a filter
Param backendURL: Required. Fully qualified URL for blockbook
Param filter: Required. Asset to fetch via filter, will filter contract or symbol fields
Returns: Returns JSON array in response, asset information objects in JSON
*/
async function fetchBackendListAssets (backendURL, filter) {
try {
let blockbookURL = backendURL.slice()
if (blockbookURL) {
blockbookURL = blockbookURL.replace(/\/$/, '')
}
// eslint-disable-next-line no-undef
if (fetch) {
// eslint-disable-next-line no-undef
const request = await fetch(blockbookURL + '/api/v2/assets/' + filter)
const data = await request.json()
if (data && data.asset) {
return data.asset
}
} else {
const request = await axios.get(blockbookURL + '/api/v2/assets/' + filter, axiosConfig)
if (request && request.data && request.data.asset) {
return request.data.asset
}
}
return null
} catch (e) {
return e
}
}
/* fetchBackendSPVProof
Purpose: Fetch SPV Proof from backend Blockbook provider. To be used to create a proof for the NEVM bridge.
Param backendURL: Required. Fully qualified URL for blockbook
Param addressOrXpub: Required. An address or XPUB to fetch UTXO's for
Param options: Optional. Optional queries based on https://github.com/syscoin/blockbook/blob/master/docs/api.md#get-utxo
Returns: Returns JSON object in response, UTXO object array in JSON
*/
async function fetchBackendSPVProof (backendURL, txid) {
try {
let blockbookURL = backendURL.slice()
if (blockbookURL) {
blockbookURL = blockbookURL.replace(/\/$/, '')
}
const url = blockbookURL + '/api/v2/getspvproof/' + txid
// eslint-disable-next-line no-undef
if (fetch) {
// eslint-disable-next-line no-undef
const response = await fetch(url)
if (response.ok) {
const data = await response.json()
return data
}
} else {
const request = await axios.get(url, axiosConfig)
if (request && request.data) {
return request.data
}
}
return null
} catch (e) {
return e
}
}
/* fetchBackendUTXOS
Purpose: Fetch UTXO's for an address or XPUB from backend Blockbook provider
Param backendURL: Required. Fully qualified URL for blockbook
Param addressOrXpub: Required. An address or XPUB to fetch UTXO's for
Param options: Optional. Optional queries based on https://github.com/syscoin/blockbook/blob/master/docs/api.md#get-utxo
Returns: Returns JSON object in response, UTXO object array in JSON
*/
async function fetchBackendUTXOS (backendURL, addressOrXpub, options) {
try {
let blockbookURL = backendURL.slice()
if (blockbookURL) {
blockbookURL = blockbookURL.replace(/\/$/, '')
}
let url = blockbookURL + '/api/v2/utxo/' + addressOrXpub
if (options) {
url += '?' + options
}
// eslint-disable-next-line no-undef
if (fetch) {
// eslint-disable-next-line no-undef
const response = await fetch(url)
if (response.ok) {
const data = await response.json()
if (data) {
data.addressOrXpub = addressOrXpub
return data
}
}
} else {
const request = await axios.get(url, axiosConfig)
if (request && request.data) {
request.data.addressOrXpub = addressOrXpub
return request.data
}
}
return null
} catch (e) {
return e
}
}
/* fetchBackendAccount
Purpose: Fetch address or XPUB information including transactions and balance information (based on options) from backend Blockbook provider
Param backendURL: Required. Fully qualified URL for blockbook
Param addressOrXpub: Required. An address or XPUB to fetch UTXO's for
Param options: Optional. Optional queries based on https://github.com/syscoin/blockbook/blob/master/docs/api.md#get-xpub
Param xpub: Optional. If addressOrXpub is an XPUB set to true.
Param mySignerObj: Optional. Signer object if you wish to update change/receiving indexes from backend provider (and XPUB token information is provided in response)
Returns: Returns JSON object in response, account object in JSON
*/
async function fetchBackendAccount (backendURL, addressOrXpub, options, xpub, mySignerObj) {
try {
let blockbookURL = backendURL.slice()
if (blockbookURL) {
blockbookURL = blockbookURL.replace(/\/$/, '')
}
let url = blockbookURL
if (xpub) {
url += '/api/v2/xpub/'
} else {
url += '/api/v2/address/'
}
url += addressOrXpub
if (options) {
url += '?' + options
}
// eslint-disable-next-line no-undef
if (fetch) {
// eslint-disable-next-line no-undef
const response = await fetch(url)
if (response.ok) {
const data = await response.json()
if (xpub && data.tokens && mySignerObj) {
mySignerObj.setLatestIndexesFromXPubTokens(data.tokens)
}
data.addressOrXpub = addressOrXpub
return data
}
} else {
const request = await axios.get(url, axiosConfig)
if (request && request.data) {
// if fetching xpub data
if (xpub && request.data.tokens && mySignerObj) {
mySignerObj.setLatestIndexesFromXPubTokens(request.data.tokens)
}
return request.data
}
}
return null
} catch (e) {
console.log('Exception: ' + e.message)
return null
}
}
/* sendRawTransaction
Purpose: Send raw transaction to backend Blockbook provider to send to the network
Param backendURL: Required. Fully qualified URL for blockbook
Param txHex: Required. Raw transaction hex
Param mySignerObj: Optional. Signer object if you wish to update change/receiving indexes from backend provider through fetchBackendAccount()
Returns: Returns txid in response or error
*/
async function sendRawTransaction (backendURL, txHex, mySignerObj) {
try {
let blockbookURL = backendURL.slice()
if (blockbookURL) {
blockbookURL = blockbookURL.replace(/\/$/, '')
}
// eslint-disable-next-line no-undef
if (fetch) {
const requestOptions = {
method: 'POST',
body: txHex
}
// eslint-disable-next-line no-undef
const response = await fetch(blockbookURL + '/api/v2/sendtx/', requestOptions)
if (response.ok) {
const data = await response.json()
if (mySignerObj) {
await fetchBackendAccount(blockbookURL, mySignerObj.getAccountXpub(), 'tokens=used&details=tokens', true, mySignerObj)
}
return data
}
} else {
const request = await axios.post(blockbookURL + '/api/v2/sendtx/', txHex, axiosConfig)
if (request && request.data) {
if (mySignerObj) {
await fetchBackendAccount(blockbookURL, mySignerObj.getAccountXpub(), 'tokens=used&details=tokens', true, mySignerObj)
}
return request.data
}
}
return null
} catch (e) {
return e
}
}
/* fetchBackendRawTx
Purpose: Get transaction from txid from backend Blockbook provider
Param backendURL: Required. Fully qualified URL for blockbook
Param txid: Required. Transaction ID to get information for
Returns: Returns JSON object in response, transaction object in JSON
*/
async function fetchBackendRawTx (backendURL, txid) {
try {
let blockbookURL = backendURL.slice()
if (blockbookURL) {
blockbookURL = blockbookURL.replace(/\/$/, '')
}
// eslint-disable-next-line no-undef
if (fetch) {
// eslint-disable-next-line no-undef
const response = await fetch(blockbookURL + '/api/v2/tx/' + txid)
if (response.ok) {
const data = await response.json()
if (data) {
return data
}
}
} else {
const request = await axios.get(blockbookURL + '/api/v2/tx/' + txid, axiosConfig)
if (request && request.data) {
return request.data
}
}
return null
} catch (e) {
return e
}
}
/* fetchProviderInfo
Purpose: Get prover info including blockbook and backend data
Returns: Returns JSON object in response, provider object in JSON
*/
async function fetchProviderInfo (backendURL) {
try {
let blockbookURL = backendURL.slice()
if (blockbookURL) {
blockbookURL = blockbookURL.replace(/\/$/, '')
}
// eslint-disable-next-line no-undef
if (fetch) {
// eslint-disable-next-line no-undef
const response = await fetch(blockbookURL + '/api/v2')
if (response.ok) {
const data = await response.json()
if (data) {
return data
}
}
} else {
const request = await axios.get(blockbookURL + '/api/v2', axiosConfig)
if (request && request.data) {
return request.data
}
}
return null
} catch (e) {
return e
}
}
/* fetchBackendBlock
Purpose: Get block from backend
Returns: Returns JSON object in response, block object in JSON
*/
async function fetchBackendBlock (backendURL, blockhash) {
try {
let blockbookURL = backendURL.slice()
if (blockbookURL) {
blockbookURL = blockbookURL.replace(/\/$/, '')
}
// eslint-disable-next-line no-undef
if (fetch) {
// eslint-disable-next-line no-undef
const response = await fetch(blockbookURL + '/api/v2/block/' + blockhash)
if (response.ok) {
const data = await response.json()
if (data) {
return data
}
}
} else {
const request = await axios.get(blockbookURL + '/api/v2/block/' + blockhash, axiosConfig)
if (request && request.data) {
return request.data
}
}
return null
} catch (e) {
return e
}
}
/* fetchEstimateFee
Purpose: Get estimated fee from backend
Returns: Returns JSON object in response, fee object in JSON
Param blocks: Required. How many blocks to estimate fee for.
Param options: Optional. possible value conservative=true or false for conservative fee. Default is true.
Returns: Returns fee response in integer. Fee rate in satoshi per kilobytes.
*/
async function fetchEstimateFee (backendURL, blocks, options) {
try {
let blockbookURL = backendURL.slice()
if (blockbookURL) {
blockbookURL = blockbookURL.replace(/\/$/, '')
}
let url = blockbookURL + '/api/v2/estimatefee/' + blocks
if (options) {
url += '?' + options
}
// eslint-disable-next-line no-undef
if (fetch) {
// eslint-disable-next-line no-undef
const response = await fetch(url)
if (response.ok) {
const data = await response.json()
if (data && data.result) {
let feeInt = parseInt(data.result)
// if fee is 0 it usually means not enough data, so use min relay fee which is 1000 satoshi per kb in Core by default
if (feeInt <= 0) {
feeInt = 1000
}
return feeInt
}
}
} else {
const request = await axios.get(url, axiosConfig)
if (request && request.data && request.data.result) {
let feeInt = parseInt(request.data.result)
// if fee is 0 it usually means not enough data, so use min relay fee which is 1000 satoshi per kb in Core by default
if (feeInt <= 0) {
feeInt = 1000
}
return feeInt
}
}
return null
} catch (e) {
return e
}
}
/* getNotarizationSignatures
Purpose: Get notarization signatures from a notary endpoint defined in the asset object, see spec for more info: https://github.com/syscoin/sips/blob/master/sip-0002.mediawiki
Param notaryAssets: Required. Asset objects that require notarization, fetch signatures via fetchNotarizationFromEndPoint()
Param txHex: Required. Signed transaction hex created from syscointx.createTransaction()/syscointx.createAssetTransaction()
Returns: boolean representing if notarization was done by acquiring a witness signature from notary.
*/
async function getNotarizationSignatures (notaryAssets, txHex) {
let notarizationDone = false
if (!notaryAssets) {
return notarizationDone
}
for (const valueAssetObj of notaryAssets.values()) {
if (!valueAssetObj.notarydetails || !valueAssetObj.notarydetails.endpoint) {
console.log('getNotarizationSignatures: Invalid notary details: ' + JSON.stringify(valueAssetObj))
continue
}
if (valueAssetObj.notarydone) {
continue
}
if (valueAssetObj.notarydetails.endpoint.toString() === 'https://test.com') {
return false
}
const responseNotary = await fetchNotarizationFromEndPoint(valueAssetObj.notarydetails.endpoint.toString(), txHex)
if (!responseNotary) {
throw Object.assign(
new Error('No response from notary'),
{ code: 402 }
)
} else if (responseNotary.error) {
throw Object.assign(
new Error(responseNotary.error),
{ code: 402 }
)
} else if (responseNotary.sigs) {
for (let i = 0; i < responseNotary.sigs.length; i++) {
const sigObj = responseNotary.sigs[i]
const notarysig = Buffer.from(sigObj.sig, 'base64')
const notaryAssetObj = notaryAssets.get(sigObj.asset)
if (notaryAssetObj && notarysig.length === 65) {
notaryAssetObj.notarysig = notarysig
notaryAssetObj.notarydone = true
notarizationDone = true
}
}
} else {
throw Object.assign(
responseNotary,
{ code: 402 }
)
}
}
return notarizationDone
}
/* notarizePSBT
Purpose: Notarize Result object from syscointx.createTransaction()/syscointx.createAssetTransaction() if required by the assets in the inputs of the transaction
Param psbt: Required. The resulting PSBT object passed in which is assigned from syscointx.createTransaction()/syscointx.createAssetTransaction()
Param notaryAssets: Required. Asset objects require notarization, fetch signatures via fetchNotarizationFromEndPoint()
Returns: new result PSBT output notarized along with index
*/
async function notarizePSBT (psbt, notaryAssets, rawTx) {
const notarizationDone = await getNotarizationSignatures(notaryAssets, rawTx)
if (notarizationDone) {
return syscointx.addNotarizationSignatures(psbt.version, notaryAssets, psbt.txOutputs)
}
return false
}
/* getAssetsRequiringNotarization
Purpose: Get assets from Result object assigned from syscointx.createTransaction()/syscointx.createAssetTransaction() that require notarization
Param assets: Required. Asset objects that are evaluated for notarization, and if they do require notarization then fetch signatures via fetchNotarizationFromEndPoint()
Returns: Asset map of objects requiring notarization or null if no notarization is required
*/
function getAssetsRequiringNotarization (psbt, assets) {
if (!assets || !syscointx.utils.isAssetAllocationTx(psbt.version)) {
return new Map()
}
const assetsInTx = syscointx.getAssetsFromOutputs(psbt.txOutputs)
let foundNotary = false
const assetsUsedInTxNeedingNotarization = new Map()
assetsInTx.forEach((value, baseAssetID) => {
if (assetsUsedInTxNeedingNotarization.has(baseAssetID)) {
return new Map()
}
if (!assets.has(baseAssetID)) {
console.log('Asset input not found in the UTXO assets map!')
return new Map()
}
const valueAssetObj = assets.get(baseAssetID)
if (valueAssetObj.notarydetails && valueAssetObj.notarydetails.endpoint && valueAssetObj.notarydetails.endpoint.length > 0) {
assetsUsedInTxNeedingNotarization.set(baseAssetID, valueAssetObj)
foundNotary = true
}
})
return foundNotary ? assetsUsedInTxNeedingNotarization : new Map()
}
/* signPSBTWithWIF
Purpose: Sign PSBT with WiF
Param psbt: Required. Partially signed transaction object
Param wif: Required. Private key in WIF format to sign inputs with
Param network: Required. bitcoinjs-lib Network object
Returns: psbt from bitcoinjs-lib
*/
async function signPSBTWithWIF (psbt, wif, network) {
const wifObject = bjs.ECPair.fromWIF(
wif,
network
)
// sign inputs with wif
await psbt.signAllInputsAsync(wifObject)
try {
if (psbt.validateSignaturesOfAllInputs()) {
psbt.finalizeAllInputs()
}
} catch (err) {
}
return psbt
}
/* signWithWIF
Purpose: Sign Result object with WiF
Param res: Required. The resulting object passed in which is assigned from syscointx.createTransaction()/syscointx.createAssetTransaction()
Param wif: Required. Private key in WIF format to sign inputs with, can be array of keys
Param network: Required. bitcoinjs-lib Network object
Returns: psbt from bitcoinjs-lib
*/
async function signWithWIF (psbt, wif, network) {
if (Array.isArray(wif)) {
for (const wifKey of wif) {
psbt = await signPSBTWithWIF(psbt, wifKey, network)
}
return psbt
} else {
return await signPSBTWithWIF(psbt, wif, network)
}
}
/* buildEthProof
Purpose: Build Ethereum SPV proof using eth-proof library
Param txOpts: Required. Object containing web3url and ethtxid fields populated
Returns: Returns JSON object in response, SPV proof object in JSON
*/
async function buildEthProof (txOpts) {
const ethProof = new GetProof(txOpts.web3url)
const web3Provider = new Web3(txOpts.web3url)
try {
let result = await ethProof.transactionProof(txOpts.ethtxid)
const txObj = await VerifyProof.getTxFromTxProofAt(result.txProof, result.txIndex)
const txvalue = txObj.hex.substring(2) // remove hex prefix
const inputData = txObj.data.slice(4).toString('hex') // get only data without function selector
const paramTxResults = web3.eth.abi.decodeParameters([{
type: 'uint',
name: 'value'
}, {
type: 'string',
name: 'syscoinAddress'
}], inputData)
const destinationaddress = paramTxResults.syscoinAddress
const txroot = result.header[4].toString('hex')
const txRootFromProof = VerifyProof.getRootFromProof(result.txProof)
if (txroot !== txRootFromProof.toString('hex')) {
throw new Error('TxRoot mismatch')
}
const txparentnodes = encode(result.txProof).toString('hex')
const txpath = encode(result.txIndex).toString('hex')
const blocknumber = parseInt(result.header[8].toString('hex'), 16)
const block = await web3Provider.eth.getBlock(blocknumber)
const blockhash = block.hash.substring(2) // remove hex prefix
const receiptroot = result.header[5].toString('hex')
result = await ethProof.receiptProof(txOpts.ethtxid)
const txReceipt = await VerifyProof.getReceiptFromReceiptProofAt(result.receiptProof, result.txIndex)
const receiptRootFromProof = VerifyProof.getRootFromProof(result.receiptProof)
if (receiptroot !== receiptRootFromProof.toString('hex')) {
throw new Error('ReceiptRoot mismatch')
}
const receiptparentnodes = encode(result.receiptProof).toString('hex')
const blockHashFromHeader = VerifyProof.getBlockHashFromHeader(result.header)
if (blockhash !== blockHashFromHeader.toString('hex')) {
throw new Error('BlockHash mismatch')
}
const receiptvalue = txReceipt.hex.substring(2) // remove hex prefix
let amount = new web3.utils.BN(0)
for (let i = 0; i < txReceipt.setOfLogs.length; i++) {
const log = Log.fromRaw(txReceipt.setOfLogs[i]).toObject()
if (log.topics && log.topics.length !== 1) {
continue
}
// event TokenFreeze(address freezer, uint value);
if (log.topics[0].toString('hex').toLowerCase() === tokenFreezeFunction.toLowerCase() && log.address.toLowerCase() === ERC20Manager.toLowerCase()) {
const paramResults = web3.eth.abi.decodeParameters([{
type: 'address',
name: 'freezer'
}, {
type: 'uint',
name: 'value'
}], log.data)
const value = new web3.utils.BN(paramResults.value)
// get precision
const nevmprecision = 16
const sysprecision = 8
amount = value.div(new web3.utils.BN(10).pow(nevmprecision.sub(sysprecision)))
break
}
}
const ethtxid = web3.utils.sha3(Buffer.from(txvalue, 'hex')).substring(2) // not txid but txhash of the tx object used for calculating tx commitment without requiring transaction deserialization
return { ethtxid, blockhash, destinationaddress, amount, txvalue, txroot, txparentnodes, txpath, blocknumber, receiptvalue, receiptroot, receiptparentnodes }
} catch (e) {
console.log('Exception: ' + e.message)
return e
}
}
/* sanitizeBlockbookUTXOs
Purpose: Sanitize backend provider UTXO objects to be useful for this library
Param sysFromXpubOrAddress: Required. The XPUB or address that was called to fetch UTXOs
Param utxoObj: Required. Backend provider UTXO JSON object to be sanitized
Param network: Optional. Defaults to Syscoin Mainnet. Network to be used to create address for notary and auxfee payout address if those features exist for the asset
Param txOpts: Optional. If its passed in we use assetWhiteList field of options to skip over (if assetWhiteList is null) UTXO's if they use notarization for an asset that is not a part of assetMap
Param assetMap: Optional. Destination outputs for transaction requiring UTXO sanitizing, used in assetWhiteList check described above
Param excludeZeroConf: Optional. False by default. Filtering out 0 conf UTXO, new/update/send asset transactions must use confirmed inputs only as per Syscoin Core mempool policy
Returns: Returns sanitized UTXO object for use internally in this library
*/
function sanitizeBlockbookUTXOs (sysFromXpubOrAddress, utxoObj, network, txOpts, assetMap, excludeZeroConf) {
if (!txOpts) {
txOpts = { rbf: false }
}
const sanitizedUtxos = { utxos: [] }
if (Array.isArray(utxoObj)) {
utxoObj.utxos = utxoObj
}
if (utxoObj.assets) {
sanitizedUtxos.assets = new Map()
utxoObj.assets.forEach(asset => {
const assetObj = {}
if (asset.contract) {
asset.contract = asset.contract.replace(/^0x/, '')
assetObj.contract = Buffer.from(asset.contract, 'hex')
}
if (asset.pubData) {
assetObj.pubdata = Buffer.from(JSON.stringify(asset.pubData))
}
if (asset.notaryKeyID) {
assetObj.notarykeyid = Buffer.from(asset.notaryKeyID, 'base64')
network = network || syscoinNetworks.mainnet
assetObj.notaryaddress = bjs.payments.p2wpkh({ hash: assetObj.notarykeyid, network: network }).address
// in unit tests notarySig may be provided
if (asset.notarySig) {
assetObj.notarysig = Buffer.from(asset.notarySig, 'base64')
} else {
// prefill in this likely case where notarySig isn't provided
assetObj.notarysig = Buffer.alloc(65, 0)
}
}
if (asset.notaryDetails) {
assetObj.notarydetails = {}
if (asset.notaryDetails.endPoint) {
assetObj.notarydetails.endpoint = Buffer.from(asset.notaryDetails.endPoint, 'base64')
} else {
assetObj.notarydetails.endpoint = Buffer.from('')
}
assetObj.notarydetails.instanttransfers = asset.notaryDetails.instantTransfers
assetObj.notarydetails.hdrequired = asset.notaryDetails.HDRequired
}
if (asset.auxFeeDetails) {
assetObj.auxfeedetails = {}
if (asset.auxFeeDetails.auxFeeKeyID) {
assetObj.auxfeedetails.auxfeekeyid = Buffer.from(asset.auxFeeDetails.auxFeeKeyID, 'base64')
assetObj.auxfeedetails.auxfeeaddress = bjs.payments.p2wpkh({ hash: assetObj.auxfeedetails.auxfeekeyid, network: syscoinNetworks.testnet }).address
} else {
assetObj.auxfeedetails.auxfeekeyid = Buffer.from('')
}
assetObj.auxfeedetails.auxfees = asset.auxFeeDetails.auxFees
}
if (asset.updateCapabilityFlags) {
assetObj.updatecapabilityflags = asset.updateCapabilityFlags
}
assetObj.maxsupply = new BN(asset.maxSupply)
assetObj.precision = asset.decimals
sanitizedUtxos.assets.set(asset.assetGuid, assetObj)
})
}
if (utxoObj.utxos) {
utxoObj.utxos.forEach(utxo => {
// xpub queries will return utxo.address and address queries should use sysFromXpubOrAddress as address is not provided
utxo.address = utxo.address || sysFromXpubOrAddress
if (excludeZeroConf && utxo.confirmations <= 0) {
return
}
const newUtxo = { type: 'LEGACY', address: utxo.address, txId: utxo.txid, path: utxo.path, vout: utxo.vout, value: new BN(utxo.value), locktime: utxo.locktime }
if (newUtxo.address.startsWith(network.bech32)) {
newUtxo.type = 'BECH32'
}
if (utxo.assetInfo) {
const baseAssetID = getBaseAssetID(utxo.assetInfo.assetGuid)
newUtxo.assetInfo = { assetGuid: utxo.assetInfo.assetGuid, value: new BN(utxo.assetInfo.value) }
const assetObj = sanitizedUtxos.assets.get(baseAssetID)
// sanity check to ensure sanitizedUtxos.assets has all of the assets being added to UTXO that are assets
if (!assetObj) {
return
}
// not sending this asset (assetMap) and assetWhiteList option if set with this asset will skip this check, by default this check is done and inputs will be skipped if they are notary asset inputs and user is not sending those assets (used as gas to fulfill requested output amount of SYS)
if ((!assetMap || !assetMap.has(utxo.assetInfo.assetGuid)) && (txOpts.assetWhiteList && !txOpts.assetWhiteList.has(utxo.assetInfo.assetGuid) && !txOpts.assetWhiteList.has(getBaseAssetID(utxo.assetInfo.assetGuid)))) {
console.log('SKIPPING utxo')
return
}
}
sanitizedUtxos.utxos.push(newUtxo)
})
}
return sanitizedUtxos
}
/* getMemoFromScript
Purpose: Return memo from a script, null otherwise
Param script: Required. OP_RETURN script output
Param memoHeader: Required. Memo prefix, application specific
*/
function getMemoFromScript (script, memoHeader) {
const pos = script.indexOf(memoHeader)
if (pos >= 0) {
return script.slice(pos + memoHeader.length)
}
return null
}
/* getMemoFromOpReturn
Purpose: Return memo from an array of outputs by finding the OP_RETURN output and extracting the memo from the script, return null if not found
Param outputs: Required. Tx output array
Param memoHeader: Optional. Memo prefix, application specific. If not passed in just return the raw opreturn script if found.
*/
function getMemoFromOpReturn (outputs, memoHeader) {
for (let i = 0; i < outputs.length; i++) {
const output = outputs[i]
if (output.script) {
// find opreturn
const chunks = bjs.script.decompile(output.script)
if (chunks[0] === bitcoinops.OP_RETURN) {
if (memoHeader) {
return getMemoFromScript(chunks[1], memoHeader)
} else {
return chunks[1]
}
}
}
}
return null
}
/* getAllocationsFromTx
Purpose: Return allocation information for an asset transaction. Pass through to syscointx-js
Param tx: Required. bitcoinjs transaction
*/
function getAllocationsFromTx (tx) {
return syscointx.getAllocationsFromTx(tx) || []
}
/* isBech32
Purpose: Return a boolean if a given sys address is a bech32 address
Param address: Required. Address to check
*/
function isBech32 (address) {
try {
utxoLib.address.fromBech32(address)
return true
} catch (e) {
return false
}
}
/* isScriptHash
Purpose: Return a boolean if a given sys address is a script hash accordingly to the syscoinNetwork selected
Param address: Required. Address to verify
Param networkInfo: Required. Network information to verify
*/
function isScriptHash (address, networkInfo) {
if (!isBech32(address)) {
const decoded = utxoLib.address.fromBase58Check(address)
if (decoded.version === networkInfo.pubKeyHash) {
return false
}
if (decoded.version === networkInfo.scriptHash) {
return true
}
} else {
const decoded = utxoLib.address.fromBech32(address)
if (decoded.data.length === 20) {
return false
}
if (decoded.data.length === 32) {
return true
}
}
throw new Error('isScriptHash: Unknown address type')
};
/* convertToAddressNFormat
Purpose: Return path in addressN format
Param path: Required derivation path
*/
function convertToAddressNFormat (path) {
const pathArray = path.replace(/'/g, '').split('/')
pathArray.shift()
const addressN = []
for (const index in pathArray) {
if (Number(index) <= 2 && Number(index) >= 0) {
addressN[Number(index)] = Number(pathArray[index]) | 0x80000000
} else {
addressN[Number(index)] = Number(pathArray[index])
}
}
return addressN
};
/* setTransactionMemo
Purpose: Return transaction with memo appended to the inside of the OP_RETURN output, return null if not found
Param rawHex: Required. Raw transaction hex
Param memoHeader: Required. Memo prefix, application specific
Param buffMemo: Required. Buffer memo to put into the transaction
*/
function setTransactionMemo (rawHex, memoHeader, buffMemo) {
const txn = bjs.Transaction.fromHex(rawHex)
let processed = false
if (!buffMemo) {
return txn
}
for (let key = 0; key < txn.outs.length; key++) {
const out = txn.outs[key]
const chunksIn = bjs.script.decompile(out.script)
if (chunksIn[0] !== bjs.opcodes.OP_RETURN) {
continue
}
txn.outs.splice(key, 1)
const updatedData = [chunksIn[1], memoHeader, buffMemo]
txn.addOutput(bjs.payments.embed({ data: [Buffer.concat(updatedData)] }).output, 0)
processed = true
break
}
if (processed) {
const memoRet = getMemoFromOpReturn(txn.outs, memoHeader)
if (!memoRet || !memoRet.equals(buffMemo)) {
return null
}
return txn
}
const updatedData = [memoHeader, buffMemo]
txn.addOutput(bjs.payments.embed({ data: [Buffer.concat(updatedData)] }).output, 0)
const memoRet = getMemoFromOpReturn(txn.outs, memoHeader)
if (!memoRet || !memoRet.equals(buffMemo)) {
return null
}
return txn
}
function setPoDA (bjstx, blobData) {
if (!blobData) {
return
}
for (let key = 0; key < bjstx.outs.length; key++) {
const out = bjstx.outs[key]
const chunksIn = bjs.script.decompile(out.script)
if (chunksIn[0] !== bjs.opcodes.OP_RETURN) {
continue
}
bjstx.outs.splice(key, 1)
const updatedData = [chunksIn[1], blobData]
bjstx.addOutput(bjs.payments.embed({ data: [Buffer.concat(updatedData)] }).output, 0)
}
}
function copyPSBT (psbt, networkIn, outputIndexToModify, outputScript) {
const psbtNew = new bjs.Psbt({ network: networkIn })
psbtNew.setVersion(psbt.version)
const txInputs = psbt.txInputs
for (let i = 0; i < txInputs.length; i++) {
const input = txInputs[i]
const dataInput = psbt.data.inputs[i]
const inputObj = {
hash: input.hash,
index: input.index,
sequence: input.sequence,
bip32Derivation: dataInput.bip32Derivation || []
}
if (dataInput.nonWitnessUtxo) {
inputObj.nonWitnessUtxo = dataInput.nonWitnessUtxo
} else if (dataInput.witnessUtxo) {
inputObj.witnessUtxo = dataInput.witnessUtxo
}
psbtNew.addInput(inputObj)
dataInput.unknownKeyVals.forEach(unknownKeyVal => {
psbtNew.addUnknownKeyValToInput(i, unknownKeyVal)
})
}
const txOutputs = psbt.txOutputs
for (let i = 0; i < txOutputs.length; i++) {
const output = txOutputs[i]
if (i === outputIndexToModify) {
psbtNew.addOutput({
script: outputScript,
address: outputScript,
value: output.value
})
} else {
psbtNew.addOutput(output)
}
}
return psbtNew
}
/* HDSigner
Purpose: Manage HD wallet and accounts, connects to SyscoinJS object
Param mnemonic: Required. Bip32 seed phrase
Param password: Optional. Encryption password for local storage on web clients
Param isTestnet: Optional. Is using testnet network?
Param networks: Optional. Defaults to Syscoin network. bitcoinjs-lib network settings for coin being used.
Param SLIP44: Optional. SLIP44 value for the coin, see: https://github.com/satoshilabs/slips/blob/master/slip-0044.md
Param pubTypes: Optional. Defaults to Syscoin ZPub/VPub types. Specific ZPub for bip84 and VPub for testnet