forked from VerusCoin/Verusbridgekeeper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ethInteractor.js
1604 lines (1306 loc) · 63.8 KB
/
ethInteractor.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 Web3 = require('web3');
const bitGoUTXO = require('bitgo-utxo-lib');
const confFile = require('./confFile.js')
const constants = require('./constants');
const ethersUtils = require('ethers').utils
const { addHexPrefix } = require('./utils');
const util = require('./utils.js');
const abi = new Web3().eth.abi
const deserializer = require('./deserializer.js');
const {
initApiCache,
initBlockCache,
setCachedApi,
getCachedApi,
clearCachedApis,
getCachedBlock,
setCachedBlock,
getCachedImport,
setCachedImport
} = require('./cache/apicalls')
const notarization = require('./utilities/notarizationSerializer.js');
let log = function(){};
const enableLog = function() {
var old = console.log;
console.log("> Log Date Format DD/MM/YY HH:MM:SS - UTCString");
console.log = function() {
var n = new Date();
var d = ("0" + (n.getDate().toString())).slice(-2),
m = ("0" + ((n.getMonth() + 1).toString())).slice(-2),
y = ("0" + (n.getFullYear().toString())).slice(-2),
t = n.toUTCString().slice(-13, -4);
Array.prototype.unshift.call(arguments, "[" + d + "/" + m + "/" + y + t + "]");
old.apply(this, arguments);
}
log = console.log;
};
class EthInteractorConfig {
constructor() {}
init(ticker, debug, debugsubmit, debugnotarization, noimports, checkhash, userpass, rpcallowip, nowitnesssubmissions) {
this._ticker = ticker ?? process.argv.indexOf('-testnet') > -1 ? "VRSCTEST" : "VRSC";
this._debug = debug ?? (process.argv.indexOf('-debug') > -1);
this._debugsubmit = debugsubmit ?? (process.argv.indexOf('-debugsubmit') > -1);
this._debugnotarization = debugnotarization ?? (process.argv.indexOf('-debugnotarization') > -1);
this._noimports = noimports ?? (process.argv.indexOf('-noimports') > -1);
this._checkhash = checkhash ?? (process.argv.indexOf('-checkhash') > -1);
this._consolelog = (process.argv.indexOf('-consolelog') > -1);
this._nowitnesssubmit = nowitnesssubmissions;
this._userpass = userpass;
this._rpcallowip = rpcallowip;
if(this._consolelog) enableLog();
}
get ticker() { return this._ticker };
get debug() { return this._debug };
get debugsubmit() { return this._debugsubmit };
get debugnotarization() { return this._debugnotarization };
get noimports() { return this._noimports };
get checkhash() { return this._checkhash };
get ethSystemId() { return constants.VETHCURRENCYID[this.ticker] };
get verusSystemId() { return constants.VERUSSYSTEMID[this.ticker] };
get bridgeId() { return constants.BRIDGEID[this.ticker] };
get spendDisabled() { return this._nowitnesssubmit };
}
const InteractorConfig = new EthInteractorConfig();
exports.InteractorConfig = InteractorConfig;
//Main coin ID's
const IAddressBaseConst = constants.IAddressBaseConst;
const RAddressBaseConst = constants.RAddressBaseConst;
const notarizationMaxGas = constants.notarizationMaxGas;
const submitImportMaxGas = constants.submitImportMaxGas;
const verusDelegatorAbi = require('./abi/VerusDelegator.json');
// Global settings
let settings = undefined;
let noaccount = false;
let web3 = undefined;
let provider = undefined;
let d = new Date();
let globalsubmitimports = { "transactionHash": "" };
let globaltimedelta = constants.globaltimedelta; //60s for getnewblocks
let globaltimedeltaNota = 300000;
let globallastinfo = d.valueOf() - globaltimedelta;
let globallastcurrency = d.valueOf() - globaltimedelta;
let globalgetlastimport = d.valueOf() - globaltimedelta;
let transactioncount = 0;
let account = undefined;
let delegatorContract = undefined;
let lastblocknumber = null;
let lasttimestamp = null
let notarizationEvent = undefined;
let blockEvent = undefined;
let webSocketFault = false;
const reconnectOptions = {
auto: false,
delay: 5000, // ms
maxAttempts: 0,
onTimeout: false,
}
const web3Options = {
clientConfig: {
maxReceivedFrameSize: 100000000,
maxReceivedMessageSize: 100000000,
keepalive: true,
keepaliveInterval: 60000 // ms
},
reconnect: reconnectOptions
};
Object.assign(String.prototype, {
reversebytes() {
return this.match(/[a-fA-F0-9]{2}/g).reverse().join('');
}
});
async function setupConf() {
if (!settings) {
settings = confFile.loadConfFile(InteractorConfig.ticker);
if(!settings.delegatorcontractaddress) {
throw new Error("Delegator contract address not set in conf file");
}
InteractorConfig._userpass = `${settings.rpcuser}:${settings.rpcpassword}`;
// Default ip to 127.0.0.1 if not set
InteractorConfig._rpcallowip = settings.rpcallowip || "127.0.0.1";
InteractorConfig._nowitnesssubmit = settings.nowitnesssubmissions == "true";
}
if (web3) {
await disconnectProviderSocket();
}
// create new provider connection
provider = new Web3.providers.WebsocketProvider(settings.ethnode, web3Options);
provider.on('error', e => { log('web3 provider socket error'); });
provider.on('end', e => { log('web3 provider socket end'); });
if (web3 === undefined) {
// create new web3 object
web3 = new Web3(provider);
// add our wallet only once
if (settings.privatekey.length == 64) {
account = web3.eth.accounts.privateKeyToAccount(settings.privatekey);
web3.eth.accounts.wallet.add(account);
} else {
noaccount = true;
}
web3.eth.handleRevert = false;
delegatorContract = new web3.eth.Contract(verusDelegatorAbi, settings.delegatorcontractaddress);
} else {
// update provider on existing web3 object
web3.setProvider(provider);
}
try {
let isListening = await web3.eth.net.isListening();
if (isListening === true) {
webSocketFault = false;
log('web3 provider is connected');
return true;
} else {
webSocketFault = true;
}
} catch (e) {
webSocketFault = true;
}
if (webSocketFault === true) {
log('web3 provider is offline');
}
return false;
}
/**
* Initializes the ETH interactor
* @param {{ ticker: string, debug?: boolean, debugsubmit?: boolean, debugnotarization?: boolean, noimports?: boolean, checkhash?: boolean }} config
*/
exports.init = async (config = {}) => {
InteractorConfig.init(
config.ticker,
config.debug,
config.debugsubmit,
config.debugnotarization,
config.noimports,
config.checkhash,
config.userpass,
config.rpcallowip,
config.nowitnesssubmissions,
)
await setupConf();
initApiCache();
initBlockCache();
eventListener(settings.delegatorcontractaddress);
return settings.rpcport;
};
async function disconnectProviderSocket() {
if (notarizationEvent) {
notarizationEvent.unsubscribe(function(error, success){});
notarizationEvent = undefined;
}
if (blockEvent) {
blockEvent.unsubscribe(function(error, success){});
blockEvent = undefined;
}
if(web3) {
web3.eth.clearSubscriptions();
await web3.eth.currentProvider.disconnect();
log("web3 provider disconnect");
}
}
exports.end = disconnectProviderSocket;
exports.web3status = async () => {
let websocketOk = false;
try {
if(web3) {
websocketOk = await Promise.race([web3.eth.net.isListening(), new Promise((_r, rej) => setTimeout(rej, 3000))])
}
} catch (error) {
websocketOk = false;
}
return websocketOk;
}
async function eventListener(notarizerAddress) {
let options = {
reconnect: reconnectOptions,
address: notarizerAddress,
topics: [
'0x680ce19d19cb7479bae869cebd27efcca33f6f22a43fd4d52d6c62a64890b7fd'
]
};
if (notarizationEvent === undefined) {
notarizationEvent = web3.eth.subscribe('logs', options, function(error, result) {
if (!error) log('Notarization at ETH Height: ' + result?.blockNumber);
else console.log("notarizationEvent", error);
}).on("data", function() {
log('***** EVENT: New Notarization, Clearing the cache(data)*********');
clearCachedApis();
setCachedApi(null, 'lastgetNotarizationDatatime');
// await setCachedApi(log?.blockNumber, 'lastNotarizationHeight');
}).on("changed", function() {
log('***** EVENT: New Notarization, Clearing the cache(changed)**********');
clearCachedApis();
});
}
if (blockEvent === undefined) {
blockEvent = web3.eth.subscribe('newBlockHeaders', (error, blockHeader) => {
if (error) {
console.error("blockEvent error:", error);
} else {
lastblocknumber = blockHeader.number;
lasttimestamp = blockHeader.timestamp;
log("New block received", blockHeader.number);
}
});
}
}
function amountFromValue(incoming) {
if (incoming == 0) return 0;
return (incoming * 100000000).toFixed(0);
}
function serializeCCurrencyValueMap(ccvm) {
let encodedOutput = Buffer.from(util.removeHexLeader(ccvm.currency), 'hex');
encodedOutput = Buffer.concat([encodedOutput, util.writeUInt(amountFromValue(ccvm.amount), 64)]);
return encodedOutput
}
function serializeCCurrencyValueMapVarInt(ccvm) {
let encodedOutput = Buffer.from(util.removeHexLeader(ccvm.currency), 'hex');
encodedOutput = Buffer.concat([encodedOutput, util.writeVarInt(parseInt(ccvm.amount, 10))]);
return encodedOutput
}
const FLAG_DEST_AUX = 64;
function serializeCTransferDestination(ctd) {
let encodedOutput = Buffer.alloc(1);
encodedOutput.writeUInt8(ctd.destinationtype);
let lengthOfDestination = {};
let destination = Buffer.from(util.removeHexLeader(ctd.destinationaddress), 'hex');
if (ctd.destinationtype == constants.DEST_REGISTERCURRENCY ||
ctd.destinationtype == constants.DEST_REGISTERCURRENCY + constants.FLAG_DEST_AUX) {
lengthOfDestination = Buffer.byteLength(destination);
} else {
lengthOfDestination = constants.UINT160_LENGTH;
}
encodedOutput = Buffer.concat([encodedOutput, util.writeCompactSize(lengthOfDestination), destination]);
if (parseInt(ctd.destinationtype & FLAG_DEST_AUX) == FLAG_DEST_AUX && destination.length != 92)
{
let mainVecLength = ctd.auxdests.length;
let subLength = util.writeCompactSize(mainVecLength);
let subvector = Buffer.from("");
for (let i = 0; i < mainVecLength; i++)
{
let subType = Buffer.alloc(1);
subType.writeUInt8(ctd.auxdests[i].type);
let subDestination = Buffer.from(bitGoUTXO.address.fromBase58Check(ctd.auxdests[i].address, 160).hash);
let arrayItem = Buffer.concat([subType, util.writeCompactSize(Buffer.byteLength(subDestination)), subDestination])
subvector = Buffer.concat([subvector, util.writeCompactSize(Buffer.byteLength(arrayItem)), arrayItem])
}
encodedOutput = Buffer.concat([encodedOutput, subLength, subvector]);
}
return encodedOutput;
}
function serializeCrossChainExport(cce) {
let encodedOutput = util.writeUInt(cce.version, 16);
encodedOutput = Buffer.concat([encodedOutput, util.writeUInt(cce.flags, 16)]);
encodedOutput = Buffer.concat([encodedOutput, bitGoUTXO.address.fromBase58Check(cce.sourcesystemid, 160).hash]);
//hashtransfers uint256
encodedOutput = Buffer.concat([encodedOutput, Buffer.from(util.removeHexLeader(cce.hashtransfers), 'hex')]);
encodedOutput = Buffer.concat([encodedOutput, bitGoUTXO.address.fromBase58Check(cce.destinationsystemid, 160).hash]);
encodedOutput = Buffer.concat([encodedOutput, bitGoUTXO.address.fromBase58Check(cce.destinationcurrencyid, 160).hash]);
encodedOutput = Buffer.concat([encodedOutput, Buffer.from('0000', 'hex')]); //exporter set to type 00 and address length 00
encodedOutput = Buffer.concat([encodedOutput, util.writeUInt(cce.firstinput, 32)]);
encodedOutput = Buffer.concat([encodedOutput, util.writeUInt(cce.numinputs, 32)]);
encodedOutput = Buffer.concat([encodedOutput, util.writeVarInt(cce.sourceheightstart)]);
encodedOutput = Buffer.concat([encodedOutput, util.writeVarInt(cce.sourceheightend)]);
//totalfees CCurrencyValueMap
encodedOutput = Buffer.concat([encodedOutput, util.serializeCCurrencyValueMapArray(cce.totalfees)]);
//totalamounts CCurrencyValueMap
encodedOutput = Buffer.concat([encodedOutput, util.serializeCCurrencyValueMapArray(cce.totalamounts)]);
//totalburned CCurrencyValueMap
encodedOutput = Buffer.concat([encodedOutput, util.writeCompactSize(1), serializeCCurrencyValueMap(cce.totalburned[0])]); //fees always blank value map 0
//CTransfer DEstionation for Reward Address
let reserveTransfers = Buffer.alloc(1);
reserveTransfers.writeUInt8(0); //empty reserve transfers
encodedOutput = Buffer.concat([encodedOutput, reserveTransfers]);
return encodedOutput;
}
function serializeCReserveTransfers(crts) {
let encodedOutput = Buffer.from('');
for (let i = 0; i < crts.length; i++) {
encodedOutput = Buffer.concat([encodedOutput, util.writeVarInt(crts[i].version)]); // should be 1 for single transfer
if (crts[i].currencyvalue)
encodedOutput = Buffer.concat([encodedOutput, serializeCCurrencyValueMapVarInt(crts[i].currencyvalue)]); // TODO: [EB-2] Varint instead of uint64
else
encodedOutput = Buffer.concat([encodedOutput, serializeCCurrencyValueMapVarInt(crts[i].currencyvalues)]);
encodedOutput = Buffer.concat([encodedOutput, util.writeVarInt(crts[i].flags)]);
encodedOutput = Buffer.concat([encodedOutput, Buffer.from(util.removeHexLeader(crts[i].feecurrencyid), 'hex')]);
encodedOutput = Buffer.concat([encodedOutput, util.writeVarInt(crts[i].fees)]);
encodedOutput = Buffer.concat([encodedOutput, serializeCTransferDestination(crts[i].destination)]);
if (crts[i].destcurrencyid)
encodedOutput = Buffer.concat([encodedOutput, Buffer.from(util.removeHexLeader(crts[i].destcurrencyid), 'hex')]);
else
encodedOutput = Buffer.concat([encodedOutput, Buffer.from(util.removeHexLeader(crts[i].destinationcurrencyid), 'hex')]);
if ((crts[i].flags & constants.RESERVE_TO_RESERVE) == constants.RESERVE_TO_RESERVE)
encodedOutput = Buffer.concat([encodedOutput, Buffer.from(util.removeHexLeader(crts[i].secondreserveid), 'hex')]);
if ((crts[i].flags & constants.CROSS_SYSTEM) == constants.CROSS_SYSTEM && crts[i].destsystemid)
encodedOutput = Buffer.concat([encodedOutput, Buffer.from(util.removeHexLeader(crts[i].destsystemid), 'hex')]);
else if ((crts[i].flags & constants.CROSS_SYSTEM) == constants.CROSS_SYSTEM && crts[i].exportto)
encodedOutput = Buffer.concat([encodedOutput, Buffer.from(util.removeHexLeader(crts[i].exportto), 'hex')]);
}
return encodedOutput;
}
//takes in an array of proof strings and serializes
function serializeEthProof(proofArray) {
if (proofArray === undefined) return null;
let encodedOutput = util.writeVarInt(proofArray.length);
//loop through the array and add each string length and the string
//serialize account proof
for (let i = 0; i < proofArray.length; i++) {
//remove the 0x at the start of the string
let proofElement = util.removeHexLeader(proofArray[i]);
encodedOutput = Buffer.concat([encodedOutput, util.writeCompactSize(proofElement.length / 2)]);
encodedOutput = Buffer.concat([encodedOutput, Buffer.from(proofElement, 'hex')]);
}
return encodedOutput;
}
function serializeEthFullProof(ethProof) {
let encodedOutput = Buffer.alloc(1);
let version = 1;
encodedOutput.writeUInt8(version);
let type = constants.TRANSFER_TYPE_ETH;
let typeBuffer = Buffer.alloc(1);
typeBuffer.writeUInt8(type);
encodedOutput = Buffer.concat([encodedOutput, typeBuffer]);
//write accountProof length
let sizeBuffer = Buffer.alloc(4);
sizeBuffer.writeUInt32LE(1);
encodedOutput = Buffer.concat([encodedOutput, sizeBuffer]);
let branchTypeBuffer = Buffer.alloc(1);
branchTypeBuffer.writeUInt8(4); //eth branch type
encodedOutput = Buffer.concat([encodedOutput, branchTypeBuffer]);
//merkle branch base
encodedOutput = Buffer.concat([encodedOutput, branchTypeBuffer]);
//serialize account proof
encodedOutput = Buffer.concat([encodedOutput, serializeEthProof(ethProof.accountProof)]);
//serialize address bytes 20
encodedOutput = Buffer.concat([encodedOutput, Buffer.from(util.removeHexLeader(ethProof.address), 'hex')]);
let balancehex = util.removeHexLeader(web3.utils.numberToHex(ethProof.balance));
let temphexreversed = web3.utils.padLeft(balancehex, 64).reversebytes();
encodedOutput = Buffer.concat([encodedOutput, Buffer.from(temphexreversed, 'hex')]);
//serialize codehash bytes 32
encodedOutput = Buffer.concat([encodedOutput, Buffer.from(util.removeHexLeader(ethProof.codeHash), 'hex')]);
//serialize nonce as uint32
encodedOutput = Buffer.concat([encodedOutput, util.writeVarInt(ethProof.nonce)]);
//serialize storageHash bytes 32
encodedOutput = Buffer.concat([encodedOutput, Buffer.from(util.removeHexLeader(ethProof.storageHash), 'hex')]);
//loop through storage proofs
let key = util.removeHexLeader(ethProof.storageProof[0].key);
key = web3.utils.padLeft(key, 64);
encodedOutput = Buffer.concat([encodedOutput, Buffer.from(key, 'hex')]);
encodedOutput = Buffer.concat([encodedOutput, serializeEthProof(ethProof.storageProof[0].proof)]);
return encodedOutput;
}
async function getProof(eIndex, blockHeight) {
let index = "0000000000000000000000000000000000000000000000000000000000000000";
let position = Buffer.alloc(4);
position.writeUInt32BE(eIndex);
let posString = position.toString('hex');
posString = web3.utils.padLeft(posString, 64);
let key = web3.utils.sha3("0x" + posString + index, { "encoding": "hex" });
// If error thrown, it is caught in the calling function
let proof = await web3.eth.getProof(settings.delegatorcontractaddress, [key], blockHeight);
return proof;
}
// create the component parts for the proof
function createComponents(transfers, startHeight, endHeight, previousExportHash, bridgeConverterActive) {
let cce = createCrossChainExport(transfers, startHeight, endHeight, false, bridgeConverterActive);
//Var Int Components size as this can only
let encodedOutput = util.writeCompactSize(1);
//eltype
encodedOutput = Buffer.concat([encodedOutput, util.writeUInt(7, 16)]);
//elIdx
encodedOutput = Buffer.concat([encodedOutput, util.writeUInt(0, 16)]);
//elVchObj
let exportKey = constants.VDXFDATAKEY[InteractorConfig.ticker];
let serializedVDXF = Buffer.from(exportKey, 'hex');
let version = 1;
serializedVDXF = Buffer.concat([serializedVDXF, util.writeUInt(version, 1)]);
let serialized = Buffer.from(serializeCrossChainExport(cce));
let prevhash = Buffer.from(util.removeHexLeader(previousExportHash), 'hex');
serialized = Buffer.concat([serialized, prevhash]);
if (InteractorConfig.checkhash) {
let hashofcce_reserves = ethersUtils.keccak256(serialized);
let serialization = Buffer.concat([serializeCrossChainExport(cce), prevhash]);
console.log("Hash of cce + prevhash: ", hashofcce_reserves.toString('hex'));
console.log("serialization of ccx + previous txid hash: ", serialization.toString('hex'));
}
serialized = Buffer.concat([util.writeCompactSize(serialized.length), serialized]);
serialized = Buffer.concat([serializedVDXF, serialized]);
serialized = Buffer.concat([util.writeCompactSize(serialized.length), serialized]);
encodedOutput = Buffer.concat([encodedOutput, serialized]);
encodedOutput = Buffer.concat([encodedOutput, Buffer.from('00000000', 'hex')]); //no elproof
return encodedOutput.toString('Hex');
}
//create an outbound trans
function createOutboundTransfers(transfers) {
let outTransfers = [];
for (let i = 0; i < transfers.length; i++) {
let transfer = transfers[i];
let outTransfer = {};
outTransfer.version = 1;
outTransfer.currencyvalues = {
[util.ethAddressToVAddress(transfer.currencyvalue.currency, IAddressBaseConst)]: util.uint64ToVerusFloat(transfer.currencyvalue.amount)
};
outTransfer.flags = transfer.flags;
if ((parseInt(outTransfer.flags) & constants.CROSS_SYSTEM) == constants.CROSS_SYSTEM) {
outTransfer.exportto = util.ethAddressToVAddress(transfer.destsystemid, IAddressBaseConst);
}
outTransfer.feecurrencyid = util.ethAddressToVAddress(transfer.feecurrencyid, IAddressBaseConst);
outTransfer.fees = util.uint64ToVerusFloat(transfer.fees);
if ((parseInt(transfer.flags) & constants.RESERVETORESERVE) == constants.RESERVETORESERVE) {
outTransfer.destinationcurrencyid = util.ethAddressToVAddress(transfer.secondreserveid, IAddressBaseConst);
outTransfer.via = util.ethAddressToVAddress(transfer.destcurrencyid, IAddressBaseConst);
} else {
outTransfer.destinationcurrencyid = util.ethAddressToVAddress(transfer.destcurrencyid, IAddressBaseConst);
}
let address = {};
address = util.hexAddressToBase58(transfer.destination.destinationtype, transfer.destination.destinationaddress.slice(0, 42));
if (transfer.destination.destinationaddress.length > 42)
outTransfer.destination = {
"type": transfer.destination.destinationtype,
"address": address,
"gateway": util.ethAddressToVAddress(transfer.destination.destinationaddress.slice(42, 82), IAddressBaseConst),
"fees": parseInt(transfer.destination.destinationaddress.slice(122, 138).reversebytes(), 16) / 100000000
}
else{
outTransfer.destination = {
"type": transfer.destination.destinationtype,
"address": address
}
}
if ((parseInt(transfer.destination.destinationtype & constants.FLAG_DEST_AUX)) == constants.FLAG_DEST_AUX)
{
const auxType = parseInt(transfer.destination.destinationaddress.slice(142,144), 16);
const auxAddress = util.hexAddressToBase58(auxType, transfer.destination.destinationaddress.slice(146))
outTransfer.destination.auxdests = [{type: auxType, address: auxAddress}]
}
outTransfers.push(outTransfer);
}
return outTransfers;
}
function createCrossChainExport(transfers, startHeight, endHeight, jsonready = false, bridgeConverterActive) {
let cce = {};
let hash = ethersUtils.keccak256(serializeCReserveTransfers(transfers));
if (InteractorConfig.checkhash) {
console.log("hash of transfers: ",hash.toString('Hex'));
}
cce.version = 1;
cce.flags = 2;
cce.sourcesystemid = InteractorConfig.ethSystemId;
cce.hashtransfers = hash;
cce.destinationsystemid = InteractorConfig.verusSystemId;
if (bridgeConverterActive) {
cce.destinationcurrencyid = InteractorConfig.bridgeId;
} else {
cce.destinationcurrencyid = InteractorConfig.verusSystemId;
}
cce.sourceheightstart = startHeight;
cce.sourceheightend = endHeight;
cce.numinputs = transfers.length;
cce.totalamounts = [];
let totalamounts = [];
cce.totalfees = [];
let totalfees = [];
for (let i = 0; i < transfers.length; i++) {
//sum up all the currencies
if (util.uint160ToVAddress(transfers[i].currencyvalue.currency, IAddressBaseConst) in totalamounts)
totalamounts[util.uint160ToVAddress(transfers[i].currencyvalue.currency, IAddressBaseConst)] += parseInt(transfers[i].currencyvalue.amount);
else
totalamounts[util.uint160ToVAddress(transfers[i].currencyvalue.currency, IAddressBaseConst)] = parseInt(transfers[i].currencyvalue.amount);
//add fees to the total amounts
if (util.uint160ToVAddress(transfers[i].feecurrencyid, IAddressBaseConst) in totalamounts)
totalamounts[util.uint160ToVAddress(transfers[i].feecurrencyid, IAddressBaseConst)] += parseInt(transfers[i].fees);
else
totalamounts[util.uint160ToVAddress(transfers[i].feecurrencyid, IAddressBaseConst)] = parseInt(transfers[i].fees);
if (util.uint160ToVAddress(transfers[i].feecurrencyid, IAddressBaseConst) in totalfees)
totalfees[util.uint160ToVAddress(transfers[i].feecurrencyid, IAddressBaseConst)] += parseInt(transfers[i].fees);
else
totalfees[util.uint160ToVAddress(transfers[i].feecurrencyid, IAddressBaseConst)] = parseInt(transfers[i].fees);
}
for (let key in totalamounts) {
cce.totalamounts.push({ "currency": key, "amount": (jsonready ? util.uint64ToVerusFloat(totalamounts[key]) : totalamounts[key]) });
}
for (let key in totalfees) {
cce.totalfees.push({ "currency": key, "amount": (jsonready ? util.uint64ToVerusFloat(totalfees[key]) : totalfees[key]) });
}
cce.totalburned = [{ "currency": '0x0000000000000000000000000000000000000000', "amount": 0 }]; // serialiser doesnt like empty strings or non BIgints
cce.rewardaddress = ""; // blank
cce.firstinput = 1;
if (InteractorConfig.debugsubmit) {
console.log("cce", JSON.stringify(cce),null,2);
}
return cce;
}
// function createCrossChainExportToETH(transfers, blockHeight, jsonready = false) {
// let cce = {};
// let hash = ethersUtils.keccak256(serializeCReserveTransfers(transfers));
// if (InteractorConfig.checkhash) {
// console.log("hash of transfers: ",hash.toString('Hex'));
// console.log("Serialize: ",serializeCReserveTransfers(transfers).slice(1).toString('Hex'));
// }
// cce.version = 1;
// cce.flags = 2;
// cce.sourcesystemid = util.convertVerusAddressToEthAddress(ETHSystemID);
// cce.hashtransfers = addHexPrefix(hash);
// cce.destinationsystemid = util.convertVerusAddressToEthAddress(InteractorConfig.verusSystemId);
// if (transfers[0].destcurrencyid.slice(0, 2) == "0x" && transfers[0].destcurrencyid.length == 42) {
// cce.destinationcurrencyid = transfers[0].destcurrencyid;
// } else {
// cce.destinationcurrencyid = util.convertVerusAddressToEthAddress(transfers[0].destcurrencyid);
// }
// cce.sourceheightstart = 1;
// cce.sourceheightend = 2;
// cce.numinputs = transfers.length;
// cce.totalamounts = [];
// let totalamounts = [];
// cce.totalfees = [];
// let totalfees = [];
// for (let i = 0; i < transfers.length; i++) {
// //sum up all the currencies
// if (transfers[i].currencyvalue.currency in totalamounts)
// totalamounts[transfers[i].currencyvalue.currency] += transfers[i].currencyvalue.amount;
// else
// totalamounts[transfers[i].currencyvalue.currency] = transfers[i].currencyvalue.amount;
// //add fees to the total amounts
// if (transfers[i].feecurrencyid in totalamounts)
// totalamounts[transfers[i].feecurrencyid] += transfers[i].fees;
// else
// totalamounts[transfers[i].feecurrencyid] = transfers[i].fees;
// if (transfers[i].feecurrencyid in totalfees)
// totalfees[transfers[i].feecurrencyid] += transfers[i].fees;
// else
// totalfees[transfers[i].feecurrencyid] = transfers[i].fees;
// }
// for (let key in totalamounts) {
// cce.totalamounts.push({ "currency": key, "amount": (jsonready ? util.uint64ToVerusFloat(totalamounts[key]) : totalamounts[key]) });
// }
// for (let key in totalfees) {
// cce.totalfees.push({ "currency": key, "amount": (jsonready ? util.uint64ToVerusFloat(totalfees[key]) : totalfees[key]) });
// }
// cce.totalburned = [{ "currency": '0x0000000000000000000000000000000000000000', "amount": 0 }];
// cce.rewardaddress = {};
// cce.firstinput = 1;
// return cce;
// }
var restoringProviderSocket = false;
async function restoreProviderSocket() {
if(restoringProviderSocket === false) {
restoringProviderSocket = true;
let online = await setupConf();
if (online) {
clearCachedApis();
eventListener(settings.delegatorcontractaddress);
log("web3 provider restored");
}
restoringProviderSocket = false;
return online;
}
log("web3 provider is already being restored...");
return false;
}
/** core functions */
const timeoutCheck = (prom, time) => Promise.race([prom, new Promise((_r, rej) => setTimeout(rej, time))]);
async function isProviderSocketOnline() {
let online = false;
try {
online = await timeoutCheck(web3.eth.net.isListening(), 5000);
} catch (e) {
online = false;
}
if (!online) {
// attempt to restore/re-connect
online = await restoreProviderSocket();
}
return online?true:false;
}
exports.getInfo = async() => {
//getinfo is just tested to see that its not null therefore we can just return the version
//check that we can connect to Ethereum if not return null to kill the connection
try {
var d = new Date();
var timenow = d.valueOf();
let cacheGetInfo = await getCachedApi('getInfo');
let getInfo = cacheGetInfo ? JSON.parse(cacheGetInfo) : null;
if (globaltimedelta + globallastinfo < timenow || !getInfo) {
let isOnline = await isProviderSocketOnline();
if (isOnline !== true) {
return { "result": { error: true, message: "web3 provider is not connected" } };
}
globallastinfo = timenow;
const blknum = lastblocknumber;
const timestamp = lasttimestamp;
if(!timestamp) {
return { "result": null };
}
getinfo = {
"version": 2000753,
"name": "vETH",
"VRSCversion": constants.VERSION,
"blocks": blknum,
"tiptime": timestamp,
"chainid": constants.VETHCURRENCYID[InteractorConfig.ticker]
}
log("Command: getinfo");
await setCachedApi(getinfo, 'getInfo');
}
return { "result": getinfo };
} catch (error) {
console.log( "Error getInfo:" + error);
return { "result": { "error": true, "message": error } };
}
}
exports.getCurrency = async(input) => {
try {
let currency = input[0];
var d = new Date();
var timenow = d.valueOf();
let cacheGetCurrency = await getCachedApi('getCurrency');
let getCurrency = cacheGetCurrency ? JSON.parse(cacheGetCurrency) : null;
if (globaltimedelta + globallastcurrency < timenow || !getCurrency) {
globallastcurrency = timenow;
let info = await delegatorContract.methods.getcurrency(util.convertVerusAddressToEthAddress(currency)).call();
let notaries = [];
let abiPattern = ['uint', 'string', 'address', 'address', 'address', 'uint8', 'uint8', [
['uint8', 'bytes']
], 'address', 'uint', 'uint', 'uint256', 'uint256', 'address', 'address[]', 'uint']
let decodedParams = abi.decodeParameters(abiPattern,
"0x" + info.slice(66));
for (let i = 0; i < decodedParams[14].length; i++) {
notaries[i] = util.ethAddressToVAddress(decodedParams[14][i], IAddressBaseConst);
}
getcurrency = {
"version": decodedParams[0],
"name": decodedParams[1],
"options": (decodedParams[1] === "VETH") ? 172 : 96,
"currencyid": util.uint160ToVAddress(decodedParams[2], IAddressBaseConst),
"parent": util.uint160ToVAddress(decodedParams[3], IAddressBaseConst),
"systemid": util.uint160ToVAddress(decodedParams[4], IAddressBaseConst),
"notarizationprotocol": decodedParams[5],
"proofprotocol": decodedParams[6],
"nativecurrencyid": { "address": '0x' + BigInt(decodedParams[7][1], IAddressBaseConst).toString(16), "type": decodedParams[7][0] },
"launchsystemid": util.uint160ToVAddress(decodedParams[8], IAddressBaseConst),
"startblock": decodedParams[9],
"endblock": decodedParams[10],
"initialsupply": decodedParams[11],
"prelaunchcarveout": decodedParams[12],
"gatewayid": util.uint160ToVAddress(decodedParams[13], IAddressBaseConst),
"notaries": notaries,
"minnotariesconfirm": decodedParams[15],
"gatewayconvertername": "Bridge"
};
log("Command: getcurrency");
await setCachedApi(getCurrency, 'getCurrency');
}
return { "result": getCurrency };
} catch (error) {
console.log( "getCurrency:" + error);
return { "result": { "error": true, "message": error } };
}
}
exports.getExports = async(input) => {
let output = [];
const lastCTransferArray = await getCachedApi('lastgetExports');
const lastGetExport = await getCachedApi('lastgetExportResult');
let chainname = input[0];
let heightstart = input[1];
let heightend = input[2];
let srtInput = JSON.stringify(input);
if (lastCTransferArray == srtInput && lastGetExport) {
return { "result": JSON.parse(lastGetExport) };
}
// web3 connection management
let isOnline = await isProviderSocketOnline();
if (isOnline !== true) {
return { "result": { error: true, message: "web3 provider is not connected" } };
}
heightstart = heightstart == 1 ? 0 : heightstart;
try {
//input chainname should always be VETH
let bridgeConverterActive;
if (chainname != constants.VERUSSYSTEMID[InteractorConfig.ticker]) throw `i-Address not ${InteractorConfig.ticker}`;
let exportSets = [];
const previousStartHeight = await delegatorContract.methods.exportHeights(heightstart).call();
exportSets = await delegatorContract.methods.getReadyExportsByRange(previousStartHeight, heightend).call();
log("Height end: ", heightend, "heightStart:", heightstart, {previousStartHeight});
for (const exportSet of exportSets) {
//loop through and add in the proofs for each export set and the additional fields
let outputSet = {};
const importCurrency = (parseInt(exportSet.transfers[0].flags) & constants.FLAG_IMPORT_TO_SOURCE) > 0 ?
exportSet.transfers[0].currencyvalue.currency :
exportSet.transfers[0].destcurrencyid ;
bridgeConverterActive = (importCurrency.toLowerCase() === constants.BRIDGECURRENCYHEX[InteractorConfig.ticker].toLowerCase())
outputSet.height = exportSet.endHeight;
outputSet.txid = util.removeHexLeader(exportSet.exportHash).reversebytes(); //export hash used for txid
outputSet.txoutnum = 0; //exportSet.position;
outputSet.exportinfo = createCrossChainExport(exportSet.transfers, exportSet.startHeight, exportSet.endHeight, true, bridgeConverterActive);
outputSet.partialtransactionproof = await getProof(exportSet.startHeight, heightend);
//serialize the prooflet index
let components = createComponents(exportSet.transfers, exportSet.startHeight, exportSet.endHeight, exportSet.prevExportHash, bridgeConverterActive);
outputSet.partialtransactionproof = serializeEthFullProof(outputSet.partialtransactionproof).toString('hex') + components;
//build transfer list
//get the transactions at the index
let test = await delegatorContract.methods._readyExports(outputSet.height).call();
outputSet.transfers = createOutboundTransfers(exportSet.transfers);
if (InteractorConfig.debugnotarization)
console.log("First Ethereum Send to Verus: ", outputSet.transfers[0].currencyvalues, " to ", outputSet.transfers[0].destination);
//loop through the
output.push(outputSet);
}
if (InteractorConfig.debugsubmit) {
console.log(JSON.stringify(output, null, 2));
}
await setCachedApi(input, 'lastgetExports');
await setCachedApi(output, 'lastgetExportResult');
return { "result": output };
} catch (error) {
let message = "unknown";
if (error && error.message == "Returned error: execution reverted" && heightstart == 0)
message = "First get Export call, no exports found.";
else if (error && error.message)
message = error.message;
else if (error)
message = JSON.stringify(error);
console.log("getExports error:", message);
return { "result": { "error": true, "message": message } };
}
}
exports.getBestProofRoot = async(input) => {
//loop through the proofroots and check each one
let proofroots = input[0].proofroots;
let bestindex = -1;
let validindexes = [];
let latestproofroot = {};
var d = new Date();
var timenow = d.valueOf();
const lastTime = await getCachedApi('lastBestProofinputtime');
let latestBlock = null;
let cachedValue = await getCachedApi('lastGetBestProofRoot');
if (cachedValue) {
if (lastTime && (JSON.parse(lastTime) + 20000) < timenow) {
latestBlock = lastblocknumber; //await web3.eth.getBlockNumber();
await setCachedApi(latestBlock, 'lastGetBestProofRoot');
}
else {
latestBlock = cachedValue
}
}
else {
// wait for block to come in, this is only normally for the frist 15 seconds of startup
if (lastblocknumber){
latestBlock = lastblocknumber; //await web3.eth.getBlockNumber();
await setCachedApi(latestBlock, 'lastGetBestProofRoot');
}
return { "result": { "error": true } };
}
setCachedApi(timenow, 'lastBestProofinputtime');
try {
if (input.length && proofroots) {
for (let i = 0; i < proofroots.length; i++) {
if ((parseInt(proofroots[i].height) > 1) && await checkProofRoot(proofroots[i].height, proofroots[i].stateroot, proofroots[i].blockhash, BigInt(util.addBytesIndicator(proofroots[i].power)))) {
validindexes.push(i);
if (bestindex == -1)
bestindex = 0;
if (proofroots[bestindex].height < proofroots[i].height) {
bestindex = i;
}
}
}
}
let latestProofHeight = 0;
if(bestindex != -1)
latestProofHeight = proofroots[bestindex].height;
if (parseInt(latestProofHeight) >= (parseInt(latestBlock) - 2)) {
latestproofroot = proofroots[bestindex];
} else {
latestproofroot = await getProofRoot(parseInt(latestBlock) - 2);
}
let laststableproofroot = null;
laststableproofroot = await getProofRoot(parseInt(latestBlock) - 30);
if (InteractorConfig.debugnotarization) {
console.log("getbestproofroot result:", { bestindex, validindexes, latestproofroot, laststableproofroot });
}
let retval = { "result": { bestindex, validindexes, latestproofroot, laststableproofroot} };
return retval;
} catch (error) {
let message = "unknown";
if (error && error.message)
message = error.message;
else if (error)
message = JSON.stringify(error);
console.log("getBestProofRoot error:", message);
return { "result": { "error": true, "message": message } };