-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
865 lines (784 loc) · 34.9 KB
/
index.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
// to run: node --max-old-space-size=8192 .\index.js
// NOTE: there is a possibility that if json contains \u0000, it'll be saved into text_content not content (jsonb)
require('dotenv').config();
const util = require("util");
// const { Pool } = require('pg')
const mysql = require('mysql');
var fs = require('fs');
var bitcoin = require('bitcoinjs-lib');
var qtumjs = require('qtumjs-lib');
var ecc = require('tiny-secp256k1');
const process = require('process');
const {execSync} = require("child_process");
const readline = require('readline');
bitcoin.initEccLib(ecc)
console.log("VERSION V0.3.0")
// for self-signed cert of postgres
process.env["NODE_TLS_REJECT_UNAUTHORIZED"] = 0;
const promise_limit = 50000
const db_pool = mysql.createPool({
user: process.env.DB_USER || '',
host: process.env.DB_HOST || '',
database: process.env.DB_DATABASE || '',
password: process.env.DB_PASSWD || '',
connectionLimit: 50, // 连接池中的最大连接数
connectTimeout: 30000,
});
var chain_folder = process.env.BITCOIN_CHAIN_FOLDER || "~/.qtum"
var bitcoin_rpc_user = process.env.BITCOIN_RPC_USER || "qtumtest"
var bitcoin_rpc_password = process.env.BITCOIN_RPC_PASSWD || "qtumtest"
var ord_binary = process.env.ORD_BINARY || "./qord"
var ord_folder = process.env.ORD_FOLDER || ""
var ord_datadir = process.env.ORD_DATADIR || "."
var rpc_url = process.env.RPC_URL || "http://127.0.0.1:13889"
const network_type = process.env.NETWORK_TYPE || "testnet"
var network = null
var network_folder = ""
if (network_type == "mainnet") {
network = qtumjs.networks.qtum
network_folder = ""
} else if (network_type == "testnet") {
network = qtumjs.networks.qtum_testnet
network_folder = "testnet3/"
} else {
console.error("Unknown network type: " + network_type)
process.exit(1)
}
const first_inscription_heights = {
'mainnet': 767430,
'testnet': 3547171,
'signet': 112402,
'regtest': 0,
}
const first_inscription_height = first_inscription_heights[network_type]
const fast_index_below = first_inscription_height + 7000
const DB_VERSION = 4
const RECOVERABLE_DB_VERSIONS = [3]
// eslint-disable-next-line no-unused-vars
const INDEXER_VERSION = 'OPI V0.3.1'
const ORD_VERSION = 'ord 0.15.0-qtum'
function delay(sec) {
return new Promise(resolve => setTimeout(resolve, sec * 1000));
}
function save_error_log(log) {
console.error(log)
fs.appendFileSync("log_file_error.txt", log + "\n")
}
async function main_index() {
await check_db()
console.log("start");
let first = true;
// eslint-disable-next-line no-constant-condition
while (true) {
if (first) first = false
else await delay(2)
let start_tm = +(new Date())
if (!fs.existsSync(ord_folder + network_folder + "log_file.txt")) {
console.error("log_file.txt not found, creating")
fs.writeFileSync(ord_folder + network_folder + "log_file.txt", '')
}
if (!fs.existsSync(ord_folder + network_folder + "log_file_index.txt")) {
console.error("log_file_index.txt not found, creating")
fs.writeFileSync(ord_folder + network_folder + "log_file_index.txt", '')
}
let ord_last_block_height_q = await new Promise((resolve, reject) => {
db_pool.query(`SELECT coalesce(max(block_height), -1) as max_height
from block_hashes;`, (error, results, fields) => {
if (error) {
console.error(error.message);
reject(error);
} else {
resolve(results);
}
});
});
let ord_last_block_height = ord_last_block_height_q[0].max_height
if (ord_last_block_height < first_inscription_height) { // first inscription
ord_last_block_height = first_inscription_height
}
let ord_index_st_tm = +(new Date())
let ord_end_block_height = ord_last_block_height + 500
if (ord_last_block_height < fast_index_below) { // a random point where blocks start to get more inscription
ord_end_block_height = ord_last_block_height + 1000
}
let current_directory = process.cwd()
process.chdir(ord_folder);
let ord_version_cmd = ord_binary + " --version"
let rpc_argument = ""
if (bitcoin_rpc_user != "") {
rpc_argument = " --bitcoin-rpc-user " + bitcoin_rpc_user + " --bitcoin-rpc-pass " + bitcoin_rpc_password
}
let network_argument = ""
if (network == qtumjs.networks.qtum_testnet) {
network_argument = " --chain testnet"
}
let ord_index_cmd = ord_binary + network_argument + " --bitcoin-data-dir " +
chain_folder + " --data-dir " + ord_datadir + " --rpc-url " + rpc_url + " --height-limit " +
(ord_end_block_height) + " " + rpc_argument + " index run"
try {
let version_string = execSync(ord_version_cmd).toString()
console.log("ord version: " + version_string)
if (!version_string.includes(ORD_VERSION)) {
console.error("ord version mismatch, please recompile ord via 'cargo build --release'.")
process.exit(1)
}
execSync(ord_index_cmd, {stdio: 'inherit'})
} catch (err) {
console.error("ERROR ON ORD!!!")
console.error(err)
process.chdir(current_directory);
continue
}
process.chdir(current_directory);
let ord_index_tm = +(new Date()) - ord_index_st_tm
const fileStream = fs.createReadStream(ord_folder + network_folder + "log_file.txt", {encoding: 'UTF-8'});
const rl = readline.createInterface({
input: fileStream,
crlfDelay: Infinity
});
let lines = []
for await (const line of rl) {
lines.push(line)
}
let lines_index = fs.readFileSync(ord_folder + network_folder + "log_file_index.txt", "utf8").split('\n')
if (lines_index.length == 1) {
console.log("Nothing new, waiting!!")
continue
}
let current_height_q = await new Promise((resolve, reject) => {
db_pool.query(`SELECT coalesce(max(block_height), -1) as max_height
from block_hashes;`, (error, results, fields) => {
if (error) {
console.error(error.message);
reject(error);
} else {
resolve(results);
}
});
});
let current_height = current_height_q[0].max_height
console.log("Checking for possible reorg start")
for (const l of lines_index) {
if (l.trim() == "") continue
let parts = l.split(';')
if (parts[2].trim() == "new_block") {
let block_height = parseInt(parts[1].trim())
if (block_height % 10000 == 0) console.log("Checking for possible reorg, height: " + block_height)
if (block_height > current_height || block_height < first_inscription_height) continue
console.warn("Block repeating, possible reorg!!")
let blockhash = parts[3].trim()
let blockhash_db_q = await new Promise((resolve, reject) => {
db_pool.query("select block_hash from block_hashes where block_height = ?;", [block_height], (error, results, fields) => {
if (error) {
console.error(error.message);
reject(error);
} else {
resolve(results);
}
});
});
if (current_height_q.length > 0 && blockhash_db_q[0].block_hash != blockhash) {
let reorg_st_tm = +(new Date())
console.error("Reorg detected at block_height " + block_height)
await handle_reorg(block_height)
console.log("Reverted to block_height " + (block_height - 1))
let reorg_tm = +(new Date()) - reorg_st_tm
reorg_tm = Math.round(reorg_tm)
await new Promise((resolve, reject) => {
db_pool.query(`INSERT into ord_indexer_reorg_stats
(reorg_tm, old_block_height, new_block_height)
values (?, ?, ?);`,
[reorg_tm, current_height, block_height - 1], (error, results, fields) => {
if (error) {
console.error(error.message);
reject(error);
} else {
resolve(results);
}
})
});
current_height = Math.min(current_height, block_height - 1)
}
}
}
console.log("Checking for possible reorg end")
// some sanity checks and checks for possible early exit of ord
let last_start_idx = null
let last_start_block = null
let last_end_idx = null
let block_start_idxes = {}
let next_expected_start = true
let lenlines = lines.length
let ioffset = 0
for (let i = 0; i < lenlines; i++) {
let l = lines[i + ioffset]
if (l.trim() == "") {
continue
}
let parts = l.split(';')
if (parts[0] != "cmd") {
continue
}
if (parts[2] == "block_start") {
if (last_start_idx == null && i != 0) {
console.error("Faulty block_start position: " + l)
process.exit(1)
}
let block_height = parseInt(parts[1])
if ((last_start_block != null) && (block_height <= last_start_block)) {
// repeating block_start, remove early entries
console.error("start with less or equal block_height in latter: " + l)
lines.splice(block_start_idxes[block_height] + ioffset, i + ioffset)
ioffset -= i - block_start_idxes[block_height]
let temp_i = 0
while ((block_height + temp_i) in block_start_idxes) {
delete block_start_idxes[block_height + temp_i]
temp_i += 1
}
} else if (!next_expected_start) {
console.error("two start but bigger block_height in latter: " + l)
process.exit(1)
} else if (i != ioffset && i - 1 != last_end_idx) {
console.error("block_start not right after block_end: " + l)
process.exit(1)
}
last_start_idx = i
last_start_block = block_height
next_expected_start = false
block_start_idxes[block_height] = i
} else if (parts[2] == "block_end") {
if (next_expected_start) {
console.error("NOT expected block_end: " + l)
process.exit(1)
}
let block_height = parseInt(parts[1])
if (block_height != last_start_block) {
console.error("block_end block_height != block_start block_height: " + l)
process.exit(1)
}
last_end_idx = i
next_expected_start = true
} else {
}
}
if (!next_expected_start) {
console.error("logs didn't end with block_end - did ord crash?")
let all_tm = +(new Date()) - start_tm
ord_index_tm = Math.round(ord_index_tm)
all_tm = Math.round(all_tm)
await new Promise((resolve, reject) => {
db_pool.query(`INSERT into ord_indexer_work_stats
(ord_index_tm, all_tm)
values (?, ?);`,
[ord_index_tm, all_tm], (error, results, fields) => {
if (error) {
console.error(error.message);
reject(error);
} else {
resolve(results);
}
})
});
continue
}
let ord_sql_st_tm = +(new Date())
let sql_query_insert_ord_number_to_id = `INSERT into ord_number_to_id (inscription_number, inscription_id, cursed_for_brc20, block_height)
values (?, ?, ?, ?);`
let sql_query_insert_transfer = `INSERT into ord_transfers (id, inscription_id, block_height, old_satpoint,
new_satpoint, new_pkScript, new_wallet, sent_as_fee,
new_output_value)
values (?, ?, ?, ?, ?, ?, ?, ?, ?);`
let sql_query_insert_content = `INSERT into ord_content (inscription_id, content, content_type, metaprotocol, block_height)
values (?, ?, ?, ?, ?);`
let sql_query_insert_text_content = `INSERT into ord_content (inscription_id, text_content, content_type,
metaprotocol, block_height)
values (?, ?, ?, ?, ?);`
let ord_sql_query_count = 0
let new_inscription_count = 0
let transfer_count = 0
let max_height = -1
for (const l of lines_index) {
if (l.trim() == '') {
continue
}
let parts = l.split(';')
if (parts[0] != "cmd") {
continue
}
if (parts[2] != "new_block") {
continue
}
if (parseInt(parts[1]) > max_height) max_height = parseInt(parts[1])
}
console.log("db_height: " + current_height + " -> " + max_height)
let main_min_block_height = current_height + 1
let main_max_block_height = max_height
let current_transfer_id_q = await new Promise((resolve, reject) => {
db_pool.query(`SELECT coalesce(max(id), -1) as maxid
from ord_transfers;`, (error, results, fields) => {
if (error) {
console.error(error.message);
reject(error);
} else {
resolve(results);
}
});
});
let current_transfer_id = parseInt(current_transfer_id_q[0].maxid) + 1
let future_sent_as_fee_transfer_id = {}
let running_promises = []
let idx = 0
console.log("db_height: " + current_height + " -> " + max_height)
for (const l of lines) {
if (l.trim() == '') {
continue
}
idx += 1
if (idx % 10000 == 0) console.log(idx + " / " + lines.length)
let parts = l.split(';')
if (parts[0] != "cmd") {
continue
}
if (running_promises.length > promise_limit) {
await Promise.all(running_promises)
running_promises = []
}
let block_height = parseInt(parts[1])
if (block_height <= current_height) continue
if (parts[2] == "block_start")
else if (parts[2] == "block_end")
else if (parts[2] == "insert") {
if (parts[3] == "number_to_id") {
if (block_height > current_height) {
running_promises.push(execute_on_db(sql_query_insert_ord_number_to_id, [parseInt(parts[4]), parts[5], parts[6] == "1", block_height]))
new_inscription_count += 1
ord_sql_query_count += 1
}
} else if (parts[3] == "early_transfer_sent_as_fee") {
if (block_height > current_height) {
future_sent_as_fee_transfer_id[parts[4]] = [current_transfer_id, false, block_height]
current_transfer_id += 1
}
} else if (parts[3] == "transfer") {
if (block_height > current_height) {
if ((parts[4] in future_sent_as_fee_transfer_id) && (future_sent_as_fee_transfer_id[parts[4]][2] == block_height)) {
//这个if分支本质上没有使用当前的current_transfer_id,而是使用的之前的一个交易的transfer_id,所以current_transfer_id不需要递增
let pair = future_sent_as_fee_transfer_id[parts[4]]
let transfer_id = pair[0]
if (pair[1]) {
save_error_log("--------------------------------")
save_error_log("ERROR: early transfer sent as fee already used")
save_error_log("On inscription: " + parts[4])
save_error_log("Transfer: " + l)
delay(10)
process.exit(1)
}
future_sent_as_fee_transfer_id[parts[4]][1] = true
running_promises.push(execute_on_db(sql_query_insert_transfer, [transfer_id, parts[4], block_height, parts[5], parts[6], parts[8], wallet_from_pkscript(parts[8], network), parts[7] == "true" ? true : false, parseInt(parts[9])]))
transfer_count += 1
ord_sql_query_count += 1
} else {
running_promises.push(execute_on_db(sql_query_insert_transfer, [current_transfer_id, parts[4], block_height, parts[5], parts[6], parts[8], wallet_from_pkscript(parts[8], network), parts[7] == "true" ? true : false, parseInt(parts[9])]))
current_transfer_id += 1
transfer_count += 1
ord_sql_query_count += 1
}
}
} else if (parts[3] == "content") {
if (block_height > current_height) {
// get string after 7th semicolon
let content = parts.slice(8).join(';')
if (parts[5] == 'true') { // JSON
if (!content.includes('\\u0000')) {
running_promises.push(execute_on_db(sql_query_insert_content, [parts[4], content, parts[6], parts[7], block_height]))
ord_sql_query_count += 1
} else {
running_promises.push(execute_on_db(sql_query_insert_text_content, [parts[4], content, parts[6], parts[7], block_height]))
ord_sql_query_count += 1
save_error_log("--------------------------------")
save_error_log("Error parsing JSON: " + content)
save_error_log("On inscription: " + parts[4])
}
} else {
running_promises.push(execute_on_db(sql_query_insert_text_content, [parts[4], content, parts[6], parts[7], block_height]))
ord_sql_query_count += 1
}
}
}
}
}
await Promise.all(running_promises)
running_promises = []
console.log("Updating block_hashes")
for (const l of lines_index) {
if (l.trim() == '') {
continue
}
let parts = l.split(';')
if (parts[0] != "cmd") {
continue
}
if (parts[2] != "new_block") {
continue
}
let block_height = parseInt(parts[1])
if (block_height < current_height) {
continue
}
let blockhash = parts[3].trim()
await new Promise((resolve, reject) => {
db_pool.query(`INSERT
IGNORE INTO block_hashes (block_height, block_hash) values (?, ?);`,
[block_height, blockhash], (error, results, fields) => {
if (error) {
console.error(error.message);
reject(error);
} else {
resolve(results);
}
})
});
console.log("height " + block_height + " block_hash updated");
}
let ord_sql_tm = +(new Date()) - ord_sql_st_tm
console.log("Updating Log Files")
let update_log_st_tm = +(new Date())
fs.writeFileSync(ord_folder + network_folder + "log_file.txt", '')
fs.writeFileSync(ord_folder + network_folder + "log_file_index.txt", '')
let update_log_tm = +(new Date()) - update_log_st_tm
ord_index_tm = Math.round(ord_index_tm)
ord_sql_tm = Math.round(ord_sql_tm)
update_log_tm = Math.round(update_log_tm)
let all_tm = +(new Date()) - start_tm
all_tm = Math.round(all_tm)
await new Promise((resolve, reject) => {
db_pool.query(`INSERT into ord_indexer_work_stats
(main_min_block_height, main_max_block_height, ord_sql_query_count, new_inscription_count,
transfer_count, ord_index_tm, ord_sql_tm, update_log_tm, all_tm)
values (?, ?, ?, ?, ?, ?, ?, ?, ?);`,
[main_min_block_height, main_max_block_height, ord_sql_query_count, new_inscription_count,
transfer_count, ord_index_tm, ord_sql_tm, update_log_tm, all_tm], (error, results, fields) => {
if (error) {
console.error(error.message);
reject(error);
} else {
resolve(results);
}
})
});
console.log("ALL DONE")
}
}
async function execute_on_db(query, params) {
try {
await new Promise((resolve, reject) => {
db_pool.query(query,
params, (error, results, fields) => {
if (error) {
reject(error);
} else {
resolve(results);
}
})
});
} catch (err) {
console.error("ERROR ON DB!!!")
console.error(err)
console.error(query)
console.error(params)
process.exit(1)
}
}
/*
NOTE: removed following from node_modules/bitcoinjs-lib/src/payments/p2tr.js
//if (pubkey && pubkey.length) {
// if (!(0, ecc_lib_1.getEccLib)().isXOnlyPoint(pubkey))
// throw new TypeError('Invalid pubkey for p2tr');
//}
o.w. it cannot decode 512057cd4cfa03f27f7b18c2fe45fe2c2e0f7b5ccb034af4dec098977c28562be7a2
*/
function wallet_from_pkscript(pkscript) {
try {
let address = bitcoin.payments.p2tr({output: Buffer.from(pkscript, 'hex'), network: network})
return address.address
} catch { /* try others */
}
try {
let address = bitcoin.payments.p2wsh({output: Buffer.from(pkscript, 'hex'), network: network})
return address.address
} catch { /* try others */
}
try {
let address = bitcoin.payments.p2wpkh({output: Buffer.from(pkscript, 'hex'), network: network})
return address.address
} catch { /* try others */
}
try {
let address = bitcoin.payments.p2sh({output: Buffer.from(pkscript, 'hex'), network: network})
return address.address
} catch { /* try others */
}
try {
let address = bitcoin.payments.p2pkh({output: Buffer.from(pkscript, 'hex'), network: network})
return address.address
} catch { /* end */
}
return null
}
async function handle_reorg(block_height) {
let last_correct_blockheight = block_height - 1
await new Promise((resolve, reject) => {
db_pool.query(`DELETE
from ord_transfers
where block_height > ?;`, [last_correct_blockheight], (error, results, fields) => {
if (error) {
reject(error);
}
})
db_pool.query(`DELETE
from ord_number_to_id
where block_height > ?;`, [last_correct_blockheight], (error, results, fields) => {
if (error) {
reject(error);
}
})
db_pool.query(`DELETE
from ord_content
where block_height > ?;`, [last_correct_blockheight], (error, results, fields) => {
if (error) {
reject(error);
}
})
db_pool.query(`DELETE
from block_hashes
where block_height > ?;`, [last_correct_blockheight], (error, results, fields) => {
if (error) {
reject(error);
}
})
db_pool.query(`SELECT setval('ord_transfers_id_seq', max(id))
from ord_transfers;`, (error, results, fields) => {
if (error) {
reject(error);
}
})
db_pool.query(`SELECT setval('ord_number_to_id_id_seq', max(id))
from ord_number_to_id;`, (error, results, fields) => {
if (error) {
reject(error);
}
})
db_pool.query(`SELECT setval('ord_content_id_seq', max(id))
from ord_content;`, (error, results, fields) => {
if (error) {
reject(error);
}
})
db_pool.query(`SELECT setval('block_hashes_id_seq', max(id))
from block_hashes;`, (error, results, fields) => {
if (error) {
reject(error);
}
})
});
}
async function fix_db_from_version(db_version) {
if (db_version == 3) {
await new Promise((resolve, reject) => {
db_pool.query(`CREATE TABLE public.ord_network_type
(
id bigserial NOT NULL,
network_type text NOT NULL,
CONSTRAINT ord_network_type_pk PRIMARY KEY (id)
);`, (error, results, fields) => {
if (error) {
console.log(error)
reject(error);
}
});
// v3 only supported mainnet
db_pool.query(`INSERT INTO ord_network_type (network_type)
VALUES (?);`, ['mainnet'],
(error, results, fields) => {
if (error) {
console.log(error)
reject(error);
}
})
resolve()
});
} else {
console.error("Unknown db_version: " + db_version)
process.exit(1)
}
}
async function check_db() {
console.log("checking db")
try {
let sqlString = 'SELECT db_version from ord_indexer_version;'
let db_version = await new Promise((resolve, reject) => {
db_pool.query(sqlString, (error, results, fields) => {
if (error) {
console.error(error.message);
reject(error);
} else {
console.log(results[0].db_version);
resolve(results[0].db_version);
}
});
});
if (db_version != DB_VERSION) {
if (RECOVERABLE_DB_VERSIONS.includes(db_version)) {
console.error("db_version mismatch, will be automatically fixed")
await fix_db_from_version(db_version)
await new Promise((resolve, reject) => {
db_pool.query(`UPDATE ord_indexer_version
SET db_version = ?,
indexer_version = ?;`,
[DB_VERSION, INDEXER_VERSION], (error, results, fields) => {
if (error) {
reject(error);
} else {
resolve(results);
}
})
});
} else {
console.error("db_version mismatch, db needs to be recreated from scratch, please run reset_init.py")
process.exit(1)
}
}
} catch (err) {
console.error(err)
console.error("db_version not found, db needs to be recreated from scratch, please run reset_init.py")
process.exit(1)
}
let res_q = await new Promise((resolve, reject) => {
db_pool.query(`SELECT *
from ord_network_type LIMIT 1;`, (error, results, fields) => {
if (error) {
console.error(error.message);
reject(error);
} else {
resolve(results);
}
});
});
if (res_q.length == 0) {
console.error("ord_network_type not found, db needs to be recreated from scratch, please run reset_init.py")
process.exit(1)
}
let network_type_db = res_q[0].network_type
if (network_type_db != network_type) {
console.error("network_type mismatch, db needs to be recreated from scratch, please run reset_init.py")
process.exit(1)
}
let current_height_q = await new Promise((resolve, reject) => {
db_pool.query(`SELECT coalesce(max(block_height), -1) as max_height
from block_hashes;`, (error, results, fields) => {
if (error) {
console.error(error.message);
reject(error);
} else {
resolve(results);
}
});
});
let current_height = current_height_q[0].max_height
console.log("current_height: " + current_height)
let current_transfer_height_q = await new Promise((resolve, reject) => {
db_pool.query(`SELECT coalesce(max(block_height), -1) as max_height
from ord_transfers;`, (error, results, fields) => {
if (error) {
console.error(error.message);
reject(error);
} else {
resolve(results);
}
});
});
let current_transfer_height = current_transfer_height_q[0].max_height
console.log("current_transfer_height: " + current_transfer_height)
let current_ord_number_to_id_height_q = await new Promise((resolve, reject) => {
db_pool.query(`SELECT coalesce(max(block_height), -1) as max_height
from ord_number_to_id;`, (error, results, fields) => {
if (error) {
console.error(error.message);
reject(error);
} else {
resolve(results);
}
});
});
let current_ord_number_to_id_height = current_ord_number_to_id_height_q[0].max_height
console.log("current_ord_number_to_id_height: " + current_ord_number_to_id_height)
let current_content_height_q = await new Promise((resolve, reject) => {
db_pool.query(`SELECT coalesce(max(block_height), -1) as max_height
from ord_content;`, (error, results, fields) => {
if (error) {
console.error(error.message);
reject(error);
} else {
resolve(results);
}
});
});
let current_content_height = current_content_height_q[0].max_height
console.log("current_content_height: " + current_content_height)
await new Promise((resolve, reject) => {
if (current_height < current_transfer_height) {
console.error("current_height < current_transfer_height")
db_pool.query(`DELETE
from ord_transfers
where block_height > ?;`, [current_height], (error, results, fields) => {
if (error) {
console.error(error.message);
reject(error);
} else {
resolve(results);
}
})
}
if (current_height < current_ord_number_to_id_height) {
console.error("current_height < current_ord_number_to_id_height")
db_pool.query(`DELETE
from ord_number_to_id
where block_height > ?;`, [current_height], (error, results, fields) => {
if (error) {
console.error(error.message);
reject(error);
} else {
resolve(results);
}
})
}
if (current_height < current_content_height) {
console.error("current_height < current_content_height")
db_pool.query(`DELETE
from ord_content
where block_height > ?;`, [current_height], (error, results, fields) => {
if (error) {
console.error(error.message);
reject(error);
} else {
resolve(results);
}
})
}
resolve()
//
// db_pool.query(`INSERT into ord_indexer_version
// (id, indexer_version, db_version)
// values (3, ?, ?);`, ["123", 3],(error, results, fields) => {
// if (error) {
// console.error(error.message);
// reject(error);
// } else {
// console.log("success");
// resolve(results);
// }
// });
});
console.log("checking db end")
}
main_index()