-
Notifications
You must be signed in to change notification settings - Fork 2
/
server-pg.js
1364 lines (1282 loc) · 47 KB
/
server-pg.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 { Pool } = require('pg')
const axios = require('axios')
const BigNumber = require('bignumber.js')
const exceptionHandler = require('./exceptionHandler')
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
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('dist'))
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()
})
const db = new Pool(config.database)
const log = (msg) => {
let now = new Date()
console.log(
now.getFullYear() +
'-' +
now.getMonth() +
'-' +
now.getDate() +
' ' +
now.getHours() +
':' +
now.getMinutes() +
':' +
now.getSeconds() +
'.' +
now.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',
exceptionHandler((req, res, next) => {
blockInfo.lastBlock = lastBlock.height
res.json(blockInfo)
})
)
// Blockchain page
app.get(
'/get_blocks_details/:start/:count',
exceptionHandler(async (req, res, next) => {
let start = req.params.start
let count = req.params.count
if (start && count) {
const query = {
text: "SELECT height, CASE WHEN type = 0 THEN actual_timestamp ELSE timestamp END as timestamp, base_reward, blob, block_cumulative_size, block_tself_size, cumulative_diff_adjusted, cumulative_diff_precise, difficulty, effective_fee_median, id, is_orphan, penalty, prev_id, summary_reward, this_block_fee_median, actual_timestamp , total_fee, total_txs_size, tr_count, type, miner_text_info, pow_seed FROM blocks WHERE blocks.height >= $1 ORDER BY blocks.height ASC LIMIT $2;",
values: [start, count]
}
let result = await db.query(query)
res.json(result && result.rowCount > 0 ? result.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, next) => {
let id = req.params.id.toLowerCase()
if (id) {
const query = {
text: `SELECT b2.id as next_id, b1.* FROM blocks as b1 left join blocks as b2 on b2.height > b1.height WHERE b1.id = $1 ORDER BY b2.height ASC LIMIT 1;`,
values: [id]
}
let result = await db.query(query)
if (result && result.rowCount > 0) {
let row = result.rows[0]
let response = await db.query(
`SELECT * FROM transactions WHERE keeper_block = ${row.height};`
)
row.transactions_details = response.rows
res.json(row)
} else {
res.send('block not found')
}
}
})
)
app.get(
'/get_tx_pool_details/:count',
exceptionHandler(async (req, res, next) => {
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, next) => {
let offset = parseInt(req.params.offset)
let count = parseInt(req.params.count)
if (count > maxCount) {
count = maxCount
}
const query = {
text: 'SELECT * FROM alt_blocks ORDER BY height DESC limit $1 offset $2;',
values: [count, offset]
}
let result = await db.query(query)
res.json(result && result.rowCount > 0 ? result.rows : [])
})
)
app.get(
'/get_alt_block_details/:id',
exceptionHandler(async (req, res, next) => {
let id = req.params.id.toLowerCase()
if (!!id) {
const query = {
text: `SELECT * FROM alt_blocks WHERE hash = $1;`,
values: [id]
}
let result = await db.query(query)
res.json(result && result.rowCount > 0 ? result.rows[0] : [])
} else
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, next) => {
let tx_hash = req.params.tx_hash.toLowerCase()
if (tx_hash) {
const query = {
text: '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 = $1;',
values: [tx_hash]
}
let result = await db.query(query)
if (result && result.rowCount > 0) res.json(result.rows[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.status({ status: 500 }).json({
message: `/get_tx_details/:tx_hash ${req.params}`
})
}
}
}
})
)
app.get(
'/get_out_info/:amount/:i',
exceptionHandler(async (req, res, next) => {
let amount = req.params.amount
let i = parseInt(req.params.i)
if (!!amount && !!i) {
const query = {
text: `SELECT * FROM out_info WHERE amount = $1 AND i = $2`,
values: [amount, i]
}
let result = await db.query(query)
if (result === undefined || result.rowCount === 0) {
let response = await get_out_info(amount, i)
res.json({ tx_id: response.data.result.tx_id })
} else {
res.json(result.rows[0])
}
} else {
res.status({ status: 500 }).json({
message: `/get_out_info/:amount/:i ${req.params}`
})
}
})
)
// Aliases
app.get(
'/get_aliases/:offset/:count/:search',
exceptionHandler(async (req, res, next) => {
let offset = parseInt(req.params.offset)
let count = parseInt(req.params.count)
if (count > maxCount) {
count = maxCount
}
let search = req.params.search.toLowerCase()
if (search === 'all' && offset !== undefined && count !== undefined) {
const query = {
text: 'SELECT * FROM aliases WHERE enabled = 1 ORDER BY block DESC limit $1 offset $2;',
values: [count, offset]
}
let result = await db.query(query)
res.json(result && result.rowCount > 0 ? result.rows : [])
} else if (
search !== undefined &&
offset !== undefined &&
count !== undefined
) {
let result = await db.query(
`SELECT * FROM aliases WHERE enabled = 1 AND (alias LIKE '%${search}%' OR address LIKE '%${search}%' OR comment LIKE '%${search}%') ORDER BY block DESC limit ${count} offset ${offset};`
)
res.json(result && result.rowCount > 0 ? result.rows : [])
}
})
)
// Charts
app.get(
'/get_chart/:chart/:period',
exceptionHandler(async (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') {
//convert me into a sp or view[sqllite3] please!!
let arrayAll = await db.query(
`SELECT actual_timestamp::bigint as at, block_cumulative_size::real as bcs, tr_count::real as trc, difficulty::real as d, type as t FROM charts WHERE actual_timestamp > ${period} ORDER BY at;`
)
let rows0 = await db.query(
`SELECT extract(epoch from date_trunc('day', to_timestamp(actual_timestamp))) as at, SUM(tr_count)::real as sum_trc FROM charts GROUP BY at ORDER BY at;`
)
let rows1 = await db.query(
`SELECT actual_timestamp as at, difficulty120::real as d120, hashrate100::real as h100, hashrate400::real as h400 FROM charts WHERE type=1 AND actual_timestamp > ${period2} ORDER BY at;`
)
arrayAll.rows[0] = rows0.rows
arrayAll.rows[1] = rows1.rows
res.json(arrayAll.rows)
} else if (chart === 'AvgBlockSize') {
result = await db.query(
`SELECT extract(epoch from date_trunc('hour', to_timestamp(actual_timestamp))) as at, avg(block_cumulative_size)::real as bcs FROM charts GROUP BY at ORDER BY at;`
)
res.json(result && result.rowCount > 0 ? result.rows : [])
} else if (chart === 'AvgTransPerBlock') {
result = await db.query(
`SELECT extract(epoch from date_trunc('hour', to_timestamp(actual_timestamp))) as at, avg(tr_count)::real as trc FROM charts GROUP BY at ORDER BY at;`
)
res.json(result && result.rowCount > 0 ? result.rows : [])
} else if (chart === 'hashRate') {
result = await db.query(
`SELECT extract(epoch from date_trunc('hour', to_timestamp(actual_timestamp))) as at, avg(difficulty120) as d120, avg(hashrate100) as h100, avg(hashrate400) as h400 FROM charts WHERE type=1 GROUP BY at ORDER BY at;`
)
res.json(result && result.rowCount > 0 ? result.rows : [])
} else if (chart === 'pos-difficulty') {
let result = await db.query(
`SELECT extract(epoch from date_trunc('hour', to_timestamp(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 at ORDER BY at;`
)
let result1 = await db.query(
'SELECT actual_timestamp as at, difficulty as d FROM charts WHERE type=0 ORDER BY at;'
)
res.json({
aggregated: result.rows,
detailed: result1.rows
})
} else if (chart === 'pow-difficulty') {
let result = await db.query(
`SELECT extract(epoch from date_trunc('hour', to_timestamp(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 at ORDER BY at;`
)
let result1 = await db.query(
'SELECT actual_timestamp as at, difficulty as d FROM charts WHERE type=1 ORDER BY at;'
)
res.json({
aggregated: result.rows,
detailed: result1.rows
})
} else if (chart === 'ConfirmTransactPerDay') {
let result = await db.query(
`SELECT extract(epoch from date_trunc('day', to_timestamp(actual_timestamp)))::integer as at, SUM(tr_count)::integer as sum_trc FROM charts GROUP BY at ORDER BY at;`
)
res.json(result && result.rowCount > 0 ? result.rows : [])
}
}
})
)
// Search
app.get(
'/search_by_id/:id',
exceptionHandler(async (req, res, next) => {
let id = req.params.id.toLowerCase()
if (!!id) {
let result = await db.query(
`SELECT * FROM blocks WHERE id = '${id}' ;`
)
if (!result || result.rowCount === 0) {
result = await db.query(
`SELECT * FROM alt_blocks WHERE hash = '${id}' ;`
)
if (!result || result.rowCount === 0) {
result = await db.query(
`SELECT * FROM transactions WHERE id = '${id}' ;`
)
if (!result || result.rowCount === 0) {
try {
let response = await get_tx_details(id)
if (response.data.result) {
res.json({ result: 'tx' })
} else {
let result = await db.query(
`SELECT * FROM aliases WHERE enabled = 1 AND (alias LIKE '%${id}%' OR address LIKE '%${id}%' OR comment LIKE '%${id}%') ORDER BY block DESC limit 1 offset 0;`
)
if (result.rowCount > 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' })
}
}
})
)
const start = async () => {
try {
await db.query('DELETE FROM alt_blocks;')
let result = await db.query(
'SELECT * FROM blocks WHERE height=(SELECT MAX(height) FROM blocks);'
)
if (result && result.rowCount === 1) {
lastBlock = result.rows[0]
}
result = await db.query(
'SELECT COUNT(*)::integer AS alias FROM aliases;'
)
if (result) countAliasesDB = result.rows[0].alias
result = await db.query(
'SELECT COUNT(*)::integer AS height FROM alt_blocks;'
)
if (result) countAltBlocksDB = result.rows[0].height
getInfoTimer()
} catch (error) {
log(`Start ERROR: ${error}`)
}
}
start()
const syncPool = async () => {
try {
statusSyncPool = true
countTrPoolServer = blockInfo.tx_pool_size
if (countTrPoolServer === 0) {
await db.query('DELETE FROM pool;')
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 {
await db.query(
`DELETE FROM pool WHERE id NOT IN ( '${pools_array.join(
"','"
)}' )`
)
} catch (error) {
log(`Delete From Pool ERROR: ${error}`)
}
try {
let result = await db.query('SELECT id FROM pool')
let new_ids = []
for (let j = 0; j < pools_array.length; j++) {
let find = false
for (let i = 0; i < result.rows.length; i++) {
if (pools_array[j] === result.rows[i].id) {
find = true
break
}
}
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
) {
let txInserts = []
for (let tx of response.data.result.txs) {
txInserts.push(
`(${tx.blob_size},` +
`${tx.fee},` +
`'${tx.id}',` +
`${tx.timestamp}` +
` )`
)
}
if (txInserts.length > 0) {
await db.query('BEGIN')
let sql =
'INSERT INTO POOL (blob_size, fee, id, timestamp) VALUES ' +
txInserts.join(',')
await db.query(sql)
await db.query('COMMIT')
}
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: ${error}`)
}
} else {
statusSyncPool = false
}
}
} catch (error) {
await db.query('DELETE FROM pool')
statusSyncPool = false
}
}
const parseComment = (comment) => {
let splitComment = comment.split(/\s*,\s*/).filter((el) => !!el)
let splitResult = splitComment[4]
if (splitResult) {
let result = splitResult.split(/\s*"\s*/)
let input = result[3].toString()
if (input) {
let output = Buffer.from(input, 'hex')
return output.toString()
} else {
return ''
}
} else {
return ''
}
}
const parseTrackingKey = (trackingKey) => {
let splitKey = trackingKey.split(/\s*,\s*/)
let resultKey = splitKey[5]
if (resultKey) {
let key = resultKey.split(':')
let keyValue = key[1].replace(/\[|\]/g, '')
if (keyValue) {
return keyValue.toString().replace(/\s+/g, '')
} else {
return ''
}
} else {
return ''
}
}
const decodeString = (str) => {
if (!!str) {
str = str.replace(/'/g, "''")
return str.replace(/\u0000/g, '', (unicode) => {
return String.fromCharCode(
parseInt(unicode.replace(/\\u/g, ''), 16)
)
})
}
return str
}
const syncTransactions = async () => {
if (block_array.length > 0) {
let blockInserts = []
let transactionInserts = []
let chartInserts = []
let outInfoInserts = []
for (const bl of block_array) {
//build transaction inserts
{
try {
if (bl.tr_count === undefined)
bl.tr_count = bl.transactions_details.length
if (bl.tr_out === undefined) bl.tr_out = []
while (
!!(localTr = bl.transactions_details.splice(0, 1)[0])
) {
let response = await get_tx_details(localTr.id)
let tx_info = response.data.result.tx_info
for (let item of tx_info.extra) {
if (item.type === 'alias_info') {
let arr = item.short_view.split('-->')
let aliasName = arr[0]
let aliasAddress = arr[1]
let aliasComment = parseComment(
item.datails_view
)
let aliasTrackingKey = parseTrackingKey(
item.datails_view
)
let aliasBlock = bl.height
let aliasTransaction = localTr.id
await db.query(
`UPDATE aliases SET enabled=0 WHERE alias = '${aliasName}';`
)
let sql = ''
try {
sql =
`INSERT INTO aliases VALUES ('${decodeString(
aliasName
)}',` +
`'${aliasAddress}',` +
`'${decodeString(aliasComment)}',` +
`'${decodeString(aliasTrackingKey)}',` +
`${aliasBlock},` +
`'${aliasTransaction}',` +
`${1}` +
`) ON CONFLICT (alias) ` +
`DO UPDATE SET ` +
`alias='${decodeString(aliasName)}',` +
`address='${aliasAddress}',` +
`comment='${decodeString(
aliasComment
)}',` +
`tracking_key='${decodeString(
aliasTrackingKey
)}',` +
`block='${aliasBlock}',` +
`transact='${aliasTransaction}',` +
`enabled=${1};`
await db.query(sql)
} catch (error) {
log(`SyncTransactions() Insert into aliases ERROR: ${error}\nsql: ${sql}`)
}
}
}
for (let item of tx_info.ins) {
if (item.global_indexes) {
bl.tr_out.push({
amount: item.amount,
i: item.global_indexes[0]
})
}
}
transactionInserts.push(
`('${tx_info.keeper_block}',` +
`'${tx_info.id}',` +
`'${tx_info.amount.toString()}',` +
`${tx_info.blob_size},` +
`'${decodeString(
JSON.stringify(tx_info.extra)
)}',` +
`${tx_info.fee},` +
`'${decodeString(
JSON.stringify(tx_info.ins)
)}',` +
`'${decodeString(
JSON.stringify(tx_info.outs)
)}',` +
`'${tx_info.pub_key}',` +
`${tx_info.timestamp},` +
`'${decodeString(
JSON.stringify(
!!tx_info.attachments
? tx_info.attachments
: {}
)
)}')`
)
}
} catch (error) {
log(`SyncTransactions() Inserting aliases ERROR: ${error}`)
}
}
chartInserts.push(
`(${bl.height},` +
`${bl.actual_timestamp},` +
`${bl.block_cumulative_size},` +
`${bl.cumulative_diff_precise},` +
`${bl.difficulty},` +
`${bl.tr_count ? bl.tr_count : 0},` +
`${bl.type},` +
`0,` +
`0,` +
`0)`
)
// }
//build out_info inserts
if (bl.tr_out && bl.tr_out.length > 0) {
for (let localOut of bl.tr_out) {
let localOutAmount = new BigNumber(
localOut.amount
).toNumber()
let response = await get_out_info(
localOutAmount,
localOut.i
)
outInfoInserts.push(
`(${localOut.amount},` +
`${localOut.i}, ` +
`'${response.data.result.tx_id}', ` +
`${bl.height})`
)
}
await db.query('begin')
//save out_info
{
try {
if (outInfoInserts.length > 0) {
let sql =
`INSERT INTO out_info VALUES ` +
outInfoInserts.join(',') +
`ON CONFLICT(amount, i, tx_id) DO NOTHING;`
await db.query(sql)
}
} catch (error) {
log(`SyncTransactions() Insert Into out_info ERROR: ${error}`)
}
}
await db.query('end')
}
//build block inserts
{
blockInserts.push(
`(${bl.height},` +
`${bl.actual_timestamp},` +
`${bl.base_reward},` +
`'${bl.blob}',` +
`${bl.block_cumulative_size},` +
`${bl.block_tself_size},` +
`${bl.cumulative_diff_adjusted},` +
`${bl.cumulative_diff_precise},` +
`${bl.difficulty},` +
`${bl.effective_fee_median},` +
`'${bl.id}',` +
`${bl.is_orphan},` +
`${bl.penalty},` +
`'${bl.prev_id}',` +
`${bl.summary_reward},` +
`${bl.this_block_fee_median},` +
`${bl.timestamp},` +
`${bl.total_fee},` +
`${bl.total_txs_size},` +
`${bl.tr_count ? bl.tr_count : 0},` +
`${bl.type},` +
"'" + decodeString(bl.miner_text_info) + "'," +
`'${bl.pow_seed}')`
)
}
}
await db.query('begin')
//save transactions
{
try {
if (transactionInserts.length > 0) {
let sql =
`INSERT INTO transactions VALUES ` +
transactionInserts.join(',') +
' ON CONFLICT (id) DO NOTHING;'
await db.query(sql)
}
} catch (error) {
log(`SyncTransactions() Insert Into transaction ERROR: ${error}`)
}
}
//save charts
{
try {
if (chartInserts.length > 0) {
let sql =
`INSERT INTO charts VALUES ` +
chartInserts.join(',') +
';'
await db.query(sql)
}
} catch (error) {
log(`SyncTransactions() Insert Into charts ERROR: ${error}`)
}
}
//save blocks
{
let sql = ''
if (blockInserts.length > 0) {
sql =
'INSERT INTO blocks (height,' +
'actual_timestamp,' +
'base_reward,' +
'blob,' +
'block_cumulative_size,' +
'block_tself_size,' +
'cumulative_diff_adjusted,' +
'cumulative_diff_precise,' +
'difficulty,' +
'effective_fee_median,' +
'id,' +
'is_orphan,' +
'penalty,' +
'prev_id,' +
'summary_reward,' +
'this_block_fee_median,' +
'timestamp,' +
'total_fee,' +
'total_txs_size,' +
'tr_count,' +
'type,' +
'miner_text_info,' +
'pow_seed) VALUES ' +
blockInserts.join(',') +
';'
await db.query(sql)
}
}
try {
await db.query('commit')
elementOne = block_array[0]
lastBlock = block_array.pop()
log(
`BLOCKS: db = ${lastBlock.height}/ server = ${blockInfo.height}`
)
await db.query(
`call update_statistics(${Math.min(
elementOne.height,
lastBlock.height
)})`
)
block_array = []
} catch (error) {
log(`SyncTransactions() Update_Statistics Store Proc ERROR: ${error}`)
}
}
}
const syncBlocks = async () => {
try {
let count = blockInfo.height - lastBlock.height + 1
if (count > 100) {
count = 100
}
if (count < 0) {
count = 1
}
let response = await get_blocks_details(lastBlock.height + 1, count)
let localBlocks =
response.data.result && response.data.result.blocks
? response.data.result.blocks
: []
if (localBlocks.length && lastBlock.id === localBlocks[0].prev_id) {
block_array = localBlocks
await syncTransactions()
if (lastBlock.height >= blockInfo.height - 1) {
now_blocks_sync = false
enabled_during_sync = true
await emitSocketInfo()
} else {
await pause(serverTimeout)
await syncBlocks()
}
} else {
const deleteCount = 100
await db.query(
`CALL purgeAboveHeight(${lastBlock.height - deleteCount})`
)
const result = await db.query(
'SELECT * FROM blocks WHERE height=(SELECT MAX(height) FROM blocks);'
)
if (result) {
lastBlock = result.rows[0]
} else {
lastBlock = {
height: -1,
id: '0000000000000000000000000000000000000000000000000000000000000000'
}
}
await pause(serverTimeout)
await syncBlocks()
}
} catch (error) {
log(`SyncBlocks() get_blocks_details ERROR: ${error}`)
now_blocks_sync = false
}
}
const syncAltBlocks = async () => {
try {
statusSyncAltBlocks = true