forked from hyle-team/block_explorer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
1549 lines (1457 loc) · 52.1 KB
/
server.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 fs = require('fs')
const express = require('express')
const http = require('http')
const app = express()
const server = http.createServer(app)
const { Server } = require('socket.io')
const io = new Server(server, {transports: ['websocket', 'polling']})
const db = require('better-sqlite3')('db', { verbose: null, timeout: 30000 })
const axios = require('axios')
const BigNumber = require('bignumber.js')
const exceptionHandler = require('./exceptionHandler')
const { rows } = require('pg/lib/defaults')
let config = fs.readFileSync('config.json', 'utf8')
config = JSON.parse(config)
const api = config.api + '/json_rpc'
const wallet = `${config.auditable_wallet.api}/json_rpc`
const server_port = config.server_port
const frontEnd_api = config.frontEnd_api
const frontEnd_html = config.frontEnd_html
let enabled_during_sync = config.websocket.enabled_during_sync
let enable_Visibility_Info = config.enableVisibilityInfo
let maxCount = 1000
let lastBlock = {
height: -1,
id: '0000000000000000000000000000000000000000000000000000000000000000'
}
let blockInfo = {}
let now_blocks_sync = false
// market
let now_delete_offers = false
// pool
let countTrPoolServer
let statusSyncPool = false
// aliases
let countAliasesDB
let countAliasesServer
// alt_blocks
let countAltBlocksDB = 0
let countAltBlocksServer
let statusSyncAltBlocks = false
let block_array = []
let pools_array = []
let serverTimeout = 30
io.engine.on('initial_headers', (headers, req) => {
headers['Access-Control-Allow-Origin'] = frontEnd_api
})
io.engine.on('headers', (headers, req) => {
headers['Access-Control-Allow-Origin'] = frontEnd_api
})
app.use(express.static(frontEnd_html))
app.use(function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*')
res.header(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept'
)
next()
})
function log(msg) {
let t = new Date()
console.log(
t.getFullYear() +
'-' +
t.getMonth() +
'-' +
t.getDate() +
' ' +
t.getHours() +
':' +
t.getMinutes() +
':' +
t.getSeconds() +
'.' +
t.getMilliseconds() +
' ' +
msg
)
}
const get_info = () => {
return axios({
method: 'get',
url: api,
data: {
method: 'getinfo',
params: { flags: 0x410 }
},
transformResponse: [(data) => JSON.parse(data)]
})
}
const get_blocks_details = (start, count) => {
return axios({
method: 'get',
url: api,
data: {
method: 'get_blocks_details',
params: {
height_start: parseInt(start ? start : 0),
count: parseInt(count ? count : 10),
ignore_transactions: false
}
},
transformResponse: [(data) => JSON.parse(data)]
})
}
const get_alt_blocks_details = (offset, count) => {
return axios({
method: 'get',
url: api,
data: {
method: 'get_alt_blocks_details',
params: {
offset: parseInt(offset),
count: parseInt(count)
}
},
transformResponse: [(data) => JSON.parse(data)]
})
}
const get_all_pool_tx_list = () => {
return axios({
method: 'get',
url: api,
data: {
method: 'get_all_pool_tx_list'
},
transformResponse: [(data) => JSON.parse(data)]
})
}
const get_pool_txs_details = (ids) => {
return axios({
method: 'get',
url: api,
data: {
method: 'get_pool_txs_details',
params: { ids: ids }
},
transformResponse: [(data) => JSON.parse(data)]
})
}
const get_tx_details = (tx_hash) => {
return axios({
method: 'get',
url: api,
data: {
method: 'get_tx_details',
params: { tx_hash: tx_hash }
},
transformResponse: [(data) => JSON.parse(data)]
})
}
const get_out_info = (amount, i) => {
return axios({
method: 'get',
url: api,
data: {
method: 'get_out_info',
params: { amount: parseInt(amount), i: parseInt(i) }
},
transformResponse: [(data) => JSON.parse(data)]
})
}
const getbalance = () => {
return axios({
method: 'post',
url: wallet,
data: {
method: 'getbalance',
params: {}
},
transformResponse: [(data) => JSON.parse(data)]
})
}
const get_mining_history = (howManyDays = 7) => {
let now = new Date()
let date = now.getDate() - howManyDays
let timestamp = Math.round(now.setDate(date) / 1000)
return axios({
method: 'post',
url: wallet,
data: {
method: 'get_mining_history',
params: { v: timestamp }
},
transformResponse: [(data) => JSON.parse(data)]
})
}
app.get('/get_info', (req, res) => {
blockInfo.lastBlock = lastBlock.height
res.json(blockInfo)
})
// Blockchain page
app.get(
'/get_blocks_details/:start/:count',
exceptionHandler(async (req, res) => {
let start = req.params.start
let count = req.params.count
if (start && count) {
let rows = db
.prepare(
'SELECT blocks.* FROM blocks WHERE blocks.height >= ? ORDER BY blocks.height ASC LIMIT ?;'
)
.all(start, count)
res.json(rows && rows.length > 0 ? rows : [])
}
})
)
app.get(
'/get_visibility_info',
exceptionHandler(async (req, res, next) => {
const result = await getVisibilityInfo()
res.send(result)
})
)
app.get(
'/get_main_block_details/:id',
exceptionHandler(async (req, res) => {
let id = req.params.id.toLowerCase()
if (id) {
let row = db
.prepare(
'SELECT b2.id as next_id, b1.* FROM blocks as b1 left join blocks as b2 on b2.height > b1.height WHERE b1.id == ? ORDER BY b2.height ASC LIMIT 1;'
)
.get(id)
if (row) {
let rows = db
.prepare(
'SELECT * FROM transactions WHERE keeper_block = ?'
)
.all(row.height)
row.transactions_details = rows
res.json(row)
} else {
res.send('block not found')
}
}
})
)
app.get(
'/get_tx_pool_details/:count',
exceptionHandler(async (req, res) => {
let count = req.params.count
if (count !== undefined) {
res.json(await getTxPoolDetails(count))
} else {
res.send("Error. Need 'count' params")
}
})
)
// Alt-blocks
app.get(
'/get_alt_blocks_details/:offset/:count',
exceptionHandler(async (req, res) => {
let offset = req.params.offset
let count = req.params.count
if (count > maxCount) {
count = maxCount
}
let rows = db
.prepare(
'SELECT * FROM alt_blocks ORDER BY height DESC limit ? offset ?'
)
.all(count, offset)
res.json(rows && rows.length > 0 ? rows : [])
})
)
app.get(
'/get_alt_block_details/:id',
exceptionHandler(async (req, res) => {
let id = req.params.id.toLowerCase()
if (id) {
try {
let row = db
.prepare('SELECT * FROM alt_blocks WHERE hash == ? ;')
.get(id)
res.json(row ? row : {})
} catch (error) {
return res.status({ status: 500 }).json({
message: `/get_out_info/:amount/:i ${req.params}`
})
}
}
})
)
// Transactions
app.get(
'/get_tx_details/:tx_hash',
exceptionHandler(async (req, res) => {
let tx_hash = req.params.tx_hash.toLowerCase()
if (tx_hash) {
let row = db
.prepare(
'SELECT transactions.*, blocks.id as block_hash, blocks.timestamp as block_timestamp FROM transactions LEFT JOIN blocks ON transactions.keeper_block = blocks.height WHERE transactions.id == ? ;'
)
.all(tx_hash)
if (row && row.length > 0) {
res.json(row[0])
} else {
let response = await get_tx_details(tx_hash)
let data = response.data
if (data.result !== undefined) {
res.json(data.result.tx_info)
} else {
res.send("Error. Need 'tx_hash' param")
}
}
}
})
)
app.get('/get_out_info/:amount/:i', async (req, res) => {
let amount = req.params.amount
let i = req.params.i
if (!!amount && !!i) {
let row = db
.prepare(`SELECT * FROM out_info WHERE amount = ? AND i = ?`)
.get(amount, i)
if (!row) {
let response = await get_out_info(amount, i)
res.json({ tx_id: response.data.result.tx_id })
} else {
res.json(row)
}
}
})
// Aliases
app.get('/get_aliases/:offset/:count/:search', (req, res) => {
let offset = req.params.offset
let count = req.params.count
let search = req.params.search.toLowerCase()
if (count > maxCount) {
count = maxCount
}
if (search === 'all' && offset !== undefined && count !== undefined) {
let rows = db
.prepare(
'SELECT * FROM aliases WHERE enabled == 1 ORDER BY block DESC limit ? offset ?'
)
.all(count, offset)
res.json(rows && rows.length > 0 ? rows : [])
} else if (
search !== undefined &&
offset !== undefined &&
count !== undefined
) {
let rows = db
.prepare(
"SELECT * FROM aliases WHERE enabled == 1 AND (alias LIKE '%?%' OR address LIKE '%?%' OR comment LIKE '%?%') ORDER BY block DESC limit ? offset ?"
)
.all(serach, count, offset)
res.json(rows && rows.length > 0 ? rows : [])
}
})
// Charts
app.get('/get_chart/:chart/:period', (req, res) => {
let chart = req.params.chart
let period = req.params.period
if (chart !== undefined) {
let period = Math.round(new Date().getTime() / 1000) - 24 * 3600 // + 86400000
let period2 = Math.round(new Date().getTime() / 1000) - 48 * 3600 // + 86400000
if (chart === 'all') {
let arrayAll = null
let rows0 = null
let rows1 = null
try {
arrayAll = db
.prepare(
'SELECT actual_timestamp as at, block_cumulative_size as bcs, tr_count as trc, difficulty as d, type as t FROM charts WHERE actual_timestamp > ? ORDER BY actual_timestamp;'
)
.all(period)
} catch (error) {
log('all charts error', error)
}
try {
rows0 = db
.prepare(
"SELECT actual_timestamp as at, SUM(tr_count) as sum_trc FROM charts GROUP BY strftime('%Y-%m-%d', datetime(actual_timestamp, 'unixepoch')) ORDER BY actual_timestamp;"
)
.all()
} catch (error) {
log('all charts confirmed-transactions-per-day', error)
}
try {
rows1 = db
.prepare(
'SELECT actual_timestamp as at, difficulty120 as d120, hashrate100 as h100, hashrate400 as h400 FROM charts WHERE type=1 AND actual_timestamp > ? ORDER BY actual_timestamp;'
)
.all(period2)
} catch (error) {
log('all hashrate', error)
return
}
arrayAll[0] = rows0
arrayAll[1] = rows1
res.json(arrayAll)
} else if (chart === 'AvgBlockSize') {
try {
let rows = db
.prepare(
"SELECT actual_timestamp as at, avg(block_cumulative_size) as bcs FROM charts GROUP BY strftime('%Y-%m-%d, %H', datetime(actual_timestamp, 'unixepoch')) ORDER BY actual_timestamp"
)
.all()
res.json(rows && rows.length > 0 ? rows : [])
} catch (error) {
log('AvgBlockSize', error)
}
} else if (chart === 'AvgTransPerBlock') {
try {
let rows = db
.prepare(
"SELECT actual_timestamp as at, avg(tr_count) as trc FROM charts GROUP BY strftime('%Y-%m-%d, %H', datetime(actual_timestamp, 'unixepoch')) ORDER BY actual_timestamp"
)
.all()
res.json(rows && rows.length > 0 ? rows : [])
} catch (error) {
log('AvgTransPerBlock', error)
}
} else if (chart === 'hashRate') {
try {
let rows = db
.prepare(
"SELECT actual_timestamp as at, avg(difficulty120) as d120, avg(hashrate100) as h100, avg(hashrate400) as h400 FROM charts WHERE type=1 GROUP BY strftime('%Y-%m-%d, %H', datetime(actual_timestamp, 'unixepoch')) ORDER BY actual_timestamp"
)
.all()
res.json(rows && rows.length > 0 ? rows : [])
} catch (error) {
log('hashrate', error)
}
} else if (chart === 'pos-difficulty') {
let rows = null
try {
rows = db
.prepare(
"SELECT actual_timestamp as at, case when (max(difficulty)-avg(difficulty))>(avg(difficulty)-min(difficulty)) then max(difficulty) else min(difficulty) end as d FROM charts WHERE type=0 GROUP BY strftime('%Y-%m-%d, %H', datetime(actual_timestamp, 'unixepoch')) ORDER BY actual_timestamp"
)
.all()
} catch (error) {
log('pos-difficulty', err)
return
}
try {
rows2 = db
.prepare(
'SELECT actual_timestamp as at, difficulty as d FROM charts WHERE type=0 ORDER BY actual_timestamp'
)
.all()
} catch (error) {
log('pos-difficulty', error)
return
}
res.json({
aggregated: rows.length > 0 ? rows : [],
detailed: rows2.length > 0 ? rows2 : []
})
} else if (chart === 'pow-difficulty') {
let rows = null
try {
rows = db
.prepare(
"SELECT actual_timestamp as at, case when (max(difficulty)-avg(difficulty))>(avg(difficulty)-min(difficulty)) then max(difficulty) else min(difficulty) end as d FROM charts WHERE type=1 GROUP BY strftime('%Y-%m-%d, %H', datetime(actual_timestamp, 'unixepoch')) ORDER BY actual_timestamp"
)
.all()
} catch (error) {
log('pow-difficulty', err)
return
}
try {
rows2 = db
.prepare(
'SELECT actual_timestamp as at, difficulty as d FROM charts WHERE type=1 ORDER BY actual_timestamp'
)
.all()
} catch (error) {
log('pow-difficulty', error)
return
}
res.json({
aggregated: rows.length > 0 ? rows : [],
detailed: rows2.length > 0 ? rows2 : []
})
} else if (chart === 'ConfirmTransactPerDay') {
let rows = db
.prepare(
"SELECT actual_timestamp as at, SUM(tr_count) as sum_trc FROM charts GROUP BY strftime('%Y-%m-%d', datetime(actual_timestamp, 'unixepoch')) ORDER BY actual_timestamp"
)
.all()
res.json(rows && rows.length > 0 ? rows : [])
}
}
})
// Search
app.get('/search_by_id/:id', async (req, res) => {
let id = req.params.id.toLowerCase()
if (id) {
let row = db.prepare('SELECT * FROM blocks WHERE id == ? ;').all(id)
if (!row || row.length === 0) {
let row = db
.prepare('SELECT * FROM alt_blocks WHERE hash == ?')
.all(id)
if (!row || row.length === 0) {
let row = db
.prepare('SELECT * FROM transactions WHERE id == ?')
.all(id)
if (!row || row.length === 0) {
try {
let response = await get_tx_details(id)
if (response.data.result) {
res.send(JSON.stringify({ result: 'tx' }))
} else {
let rows = db
.prepare(
"SELECT * FROM aliases WHERE enabled == 1 AND (alias LIKE '%?%' OR address LIKE '%?%' OR comment LIKE '%?%') ORDER BY block DESC limit ? offset ?"
)
.all(id, 1, 0)
if (rows && rows.length > 0) {
res.json({ result: 'alias' })
} else {
res.json({ result: 'NOT FOUND' })
}
}
} catch (error) {
res.json({ result: 'NOT FOUND' })
}
} else {
res.json({ result: 'tx' })
}
} else {
res.json({ result: 'alt_block' })
}
} else {
res.json({ result: 'block' })
}
}
})
db.prepare(
'create table if not exists blocks (height INTEGER UNIQUE' +
', actual_timestamp INTEGER' +
', base_reward TEXT' +
', blob TEXT' +
', block_cumulative_size INTEGER' +
', block_tself_size TEXT' +
', cumulative_diff_adjusted TEXT' +
', cumulative_diff_precise TEXT' +
', difficulty TEXT' +
', effective_fee_median TEXT' +
', id TEXT' +
', is_orphan INTEGER' +
', penalty TEXT' +
', prev_id TEXT' +
', summary_reward TEXT' +
', this_block_fee_median TEXT' +
', timestamp INTEGER' +
', total_fee TEXT' +
', total_txs_size INTEGER' +
', tr_count INTEGER' +
', type INTEGER' +
', miner_text_info TEXT' +
', pow_seed TEXT' +
');'
).run()
db.prepare(
'CREATE INDEX if not exists index_bl_height ON blocks(height);'
).run()
db.prepare('CREATE INDEX if not exists index_bl_id ON blocks(id);').run()
db.prepare(
'create table if not exists transactions (keeper_block INTEGER, ' +
'id TEXT, ' +
'amount TEXT,' +
'blob_size INTEGER,' +
'extra TEXT,' +
'fee TEXT,' +
'ins TEXT,' +
'outs TEXT,' +
'pub_key TEXT,' +
'timestamp INTEGER,' +
'attachments TEXT' +
');'
).run()
db.prepare(
'CREATE INDEX if not exists index_tr_keeper_block ON transactions(keeper_block);'
).run()
db.prepare('CREATE INDEX if not exists index_tr_id ON transactions(id);').run()
db.prepare(
'create table if not exists aliases (' +
'alias TEXT,' +
'address TEXT,' +
'comment TEXT,' +
'tracking_key TEXT,' +
'block INTEGER,' +
'transact TEXT,' +
'enabled INTEGER' +
');'
).run()
db.prepare('CREATE INDEX if not exists index_al_block ON aliases(block);').run()
db.prepare(
'create table if not exists alt_blocks (' +
'height INTEGER,' +
'timestamp INTEGER,' +
'actual_timestamp INTEGER,' +
'size INTEGER,' +
'hash TEXT,' +
'type INTEGER,' +
'difficulty TEXT,' +
'cumulative_diff_adjusted TEXT,' +
'cumulative_diff_precise TEXT,' +
'is_orphan INTEGER,' +
'base_reward TEXT,' +
'total_fee TEXT,' +
'penalty TEXT,' +
'summary_reward TEXT,' +
'block_cumulative_size INTEGER,' +
'this_block_fee_median TEXT,' +
'effective_fee_median TEXT,' +
'total_txs_size INTEGER,' +
'transactions_details TEXT,' +
'miner_txt_info TEXT,' +
'pow_seed TEXT' +
');'
).run()
db.prepare(
'CREATE INDEX if not exists index_ab_hash ON alt_blocks(hash);'
).run()
db.prepare(
'create table if not exists pool (' +
'blob_size TEXT,' +
'fee TEXT,' +
'id TEXT,' +
'timestamp TEXT' +
');'
).run()
db.prepare('CREATE INDEX if not exists index_pool_id ON pool(id);').run()
db.prepare(
'create table if not exists charts (' +
'height INTEGER' +
', actual_timestamp INTEGER' +
', block_cumulative_size INTEGER' +
', cumulative_diff_precise TEXT' +
', difficulty TEXT' +
', tr_count INTEGER' +
', type INTEGER' +
', difficulty120 TEXT' +
', hashrate100 TEXT' +
', hashrate400 TEXT' +
');'
).run()
db.prepare(
'CREATE INDEX if not exists index_bl_height ON charts(height);'
).run()
db.prepare('DELETE FROM alt_blocks').run()
db.prepare(
'create table if not exists out_info (' +
'amount TEXT,' +
'i INTEGER,' +
'tx_id TEXT,' +
'block INTEGER' +
');'
).run()
db.prepare(
'CREATE UNIQUE INDEX if not exists index_out_info ON out_info(amount, i, tx_id);'
).run()
const start = async () => {
try {
db.prepare('DELETE FROM alt_blocks;').run()
let row = db
.prepare(
'SELECT * FROM blocks WHERE height=(SELECT MAX(height) FROM blocks)'
)
.get()
if (row) lastBlock = row
countAliasesDB =
db.prepare('SELECT COUNT(*) AS alias FROM aliases').get().alias || 0
countAltBlocksDB =
db.prepare('SELECT COUNT(*) AS height FROM alt_blocks').height || 0
getInfoTimer()
} catch (error) {
log('Start Error', error)
}
}
start()
const syncPool = async () => {
try {
statusSyncPool = true
countTrPoolServer = blockInfo.tx_pool_size
if (countTrPoolServer === 0) {
db.prepare('DELETE FROM alt_blocks;').run()
statusSyncPool = false
io.emit('get_transaction_pool_info', JSON.stringify([]))
} else {
let response = await get_all_pool_tx_list()
if (response.data.result.ids) {
pools_array = response.data.result.ids
? response.data.result.ids
: []
try {
db.prepare('DELETE FROM pool WHERE id NOT IN (?)').run(
pools_array.join("','")
)
} catch (error) {
log('pool delete', error)
}
try {
let rows = db.prepare('SELECT id FROM pool').all()
var new_ids = []
for (var j = 0; j < pools_array.length; j++) {
var find = false
for (var i = 0; i < rows.length; i++) {
if (pools_array[j] === rows[i].id) {
find = true
break
} else {
log('pools_array[j] !== rows[i].id')
}
}
if (!find) {
new_ids.push(pools_array[j])
}
}
if (new_ids.length) {
try {
let response = await get_pool_txs_details(new_ids)
if (
response.data.result &&
response.data.result.txs
) {
const insert = db.prepare(
'INSERT INTO pool VALUES (@blob_size, @fee, @id, @timestamp)'
)
const insertMany = db.transaction(
(transactions) => {
for (const transaction of transactions)
insert.run(transaction)
}
)
let values = []
for (const tx of response.data.result.txs) {
values.push({
blob_size: tx.blob_size,
fee: tx.fee,
id: tx.id,
timestamp: tx.timestamp
})
}
insertMany(values)
statusSyncPool = false
} else {
statusSyncPool = false
}
io.emit('get_transaction_pool_info', JSON.stringify(await getTxPoolDetails(0)))
} catch (error) {
statusSyncPool = false
}
} else {
statusSyncPool = false
}
} catch (error) {
log('select id from pool', error)
}
} else {
statusSyncPool = false
}
}
} catch (error) {
db.prepare('DELETE FROM alt_blocks;').run()
statusSyncPool = false
}
}
function parseComment(comment) {
var splitComment = comment.split(/\s*,\s*/).filter((el) => !!el)
var splitResult = splitComment[4]
if (splitResult) {
var result = splitResult.split(/\s*"\s*/)
var input = result[3].toString()
if (input) {
var output = Buffer.from(input, 'hex')
return output.toString()
} else {
return ''
}
} else {
return ''
}
}
function parseTrackingKey(trackingKey) {
var splitKey = trackingKey.split(/\s*,\s*/)
var resultKey = splitKey[5]
if (resultKey) {
var key = resultKey.split(':')
var keyValue = key[1].replace(/\[|\]/g, '')
if (keyValue) {
keyValue.toString()
keyValue = keyValue.replace(/\s+/g, '')
return keyValue
} else {
return ''
}
} else {
return ''
}
}
async function syncTransactions() {
if (block_array.length > 0) {
var localBl = block_array[0]
if (localBl.transactions_details.length === 0) {
if (localBl.tr_out.length === 0) {
db.prepare('begin')
var hashrate100 = 0
var hashrate400 = 0
if (localBl.type === 1) {
try {
let rows = db
.prepare(
`SELECT height, actual_timestamp, cumulative_diff_precise FROM charts WHERE type=1`
)
.all()
for (let i = 0; i < rows.length; i++) {
hashrate100 =
i > 99 - 1
? (localBl['cumulative_diff_precise'] -
rows[rows.length - 100][
'cumulative_diff_precise'
]) /
(localBl['actual_timestamp'] -
rows[rows.length - 100][
'actual_timestamp'
])
: 0
hashrate400 =
i > 399 - 1
? (localBl['cumulative_diff_precise'] -
rows[rows.length - 400][
'cumulative_diff_precise'
]) /
(localBl['actual_timestamp'] -
rows[rows.length - 400][
'actual_timestamp'
])
: 0
}
db.prepare(
'INSERT INTO charts VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
).run(
localBl.height,
localBl.actual_timestamp,
localBl.block_cumulative_size,
localBl.cumulative_diff_precise.toString(),
localBl.difficulty.toString(),
localBl.tr_count ? localBl.tr_count : 0,
localBl.type,
(localBl.difficulty / 120).toFixed(0),
hashrate100,
hashrate400
)
} catch (error) {
log('syncTransactions', error)
}
} else {
db.prepare(
'INSERT INTO charts VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
).run(
localBl.height,
localBl.actual_timestamp,
localBl.block_cumulative_size,
localBl.cumulative_diff_precise.toString(),
localBl.difficulty.toString(),
localBl.tr_count ? localBl.tr_count : 0,
localBl.type,
0,
0,
0
)
}
db.prepare(
'INSERT INTO blocks VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
).run(
localBl.height,
localBl.actual_timestamp,
localBl.base_reward,
localBl.blob,
localBl.block_cumulative_size,
localBl.block_tself_size,
localBl.cumulative_diff_adjusted.toString(),
localBl.cumulative_diff_precise.toString(),
localBl.difficulty.toString(),
localBl.effective_fee_median,
localBl.id,
localBl.is_orphan ? 1 : 0,
localBl.penalty,
localBl.prev_id,
localBl.summary_reward,
localBl.this_block_fee_median,
localBl.timestamp,
localBl.total_fee.toString(),
localBl.total_txs_size,
localBl.tr_count ? localBl.tr_count : 0,
localBl.type,
localBl.miner_text_info,
localBl.pow_seed
)
db.prepare('commit')
lastBlock = block_array.splice(0, 1)[0]
log(
'BLOCKS: db =' +
lastBlock.height +
'/server =' +
blockInfo.height +
' transaction left = ' +
localBl.tr_count
)
await delay(serverTimeout)
await syncTransactions()
} else {
var localOut = localBl.tr_out[0]
let localOutAmount = new BigNumber(localOut.amount).toNumber()
try {
let response = await get_out_info(
localOutAmount,
localOut.i
)
// let data2 = response.data
db.prepare('begin')
db.prepare(`REPLACE INTO out_info VALUES (?, ?, ?, ?)`).run(
localOut.amount.toString(),
localOut.i,
response.data.result.tx_id,
localBl.height
)
localBl.tr_out.splice(0, 1)
db.prepare('commit')
log('tr_out left = ' + localBl.tr_out.length)
await delay(serverTimeout)
await syncTransactions()
} catch (error) {
log('syncTransactions() get_out_info ERROR', error)
now_blocks_sync = false
}
}
} else {
if (localBl.tr_count === undefined)
localBl.tr_count = localBl.transactions_details.length
if (localBl.tr_out === undefined) localBl.tr_out = []
var localTr = localBl.transactions_details.splice(0, 1)[0]
try {