-
Notifications
You must be signed in to change notification settings - Fork 5
/
syncer.js
1859 lines (1757 loc) · 57.1 KB
/
syncer.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
/*@flow*/
/* global BigInt */
// SPDX-License-Identifier: MIT
'use strict';
const Util = require('util');
const nThen = require('nthen');
const RpcClient = require('bitcoind-rpc');
const ClickHouse2 = require('./lib/clickhouse.js');
const Log = require('./lib/log.js');
const Config = require('./config.js');
/*::
import type { Nthen_WaitFor_t } from 'nthen';
import type {
ClickHouse_t,
Table_t
} from './lib/clickhouse.js';
import type { Log_t } from './lib/log.js';
export type Rpc_Client_Res_t<T> = {
result: T,
error: Object|null,
id: string
};
export type Rpc_Client_Request_t = {
jsonrpc: "1.0"|"2.0",
id: string,
method: string,
params: Array<any>
}
export type Rpc_BlockchainInfo_t = {
chain: string,
blocks: number,
headers: number,
bestblockhash: string,
difficulty: number,
mediantime: number,
verificationprogress: number,
initialblockdownload: bool,
chainwork: string,
size_on_disk: number,
pruned: bool,
softforks: Array<any>
};
export type Rpc_Client_Rpc_t<T> = (err: ?Error, ret: ?Rpc_Client_Res_t<T>) => void;
export type Rpc_Client_t = {
getBlockchainInfo: (Rpc_Client_Rpc_t<Rpc_BlockchainInfo_t>)=>void,
submitBlock: (blk: string, cb:Rpc_Client_Rpc_t<any>)=>void,
getBlock: (hash: string, number, number, cb:Rpc_Client_Rpc_t<any>)=>void,
getBlockHash: (num: number, cb:Rpc_Client_Rpc_t<string>)=>void,
configureMiningPayouts: (po:{[string]:number}, cb:Rpc_Client_Rpc_t<any>)=>void,
getRawTransaction: (hash: string, verbose: number, cb:Rpc_Client_Rpc_t<any>)=>void,
batch: (()=>void, (err: ?Error, ret: ?Rpc_Client_Res_t<any>)=>void)=>void,
batchedCalls: ?Rpc_Client_Request_t
};
type BlockList_t = {
add: (RpcBlock_t)=>void,
blocks: ()=>Array<RpcBlock_t>,
txio: ()=>number,
};
type Context_t = {
ch: ClickHouse_t,
btc: Rpc_Client_t,
snclog: Log_t,
rpclog: Log_t,
chain: string,
recompute: bool,
lw: Nthen_WaitFor_t, // not the same thing but same function signature
mut: {
mempool: Array<string>,
tip: Tables.chain_t,
gettingBlocks: bool,
blockList: ?BlockList_t,
}
};
type BigInt_t = number;
type BigIntConstructor_t = (number|string)=>BigInt_t;
const BigInt = (({}:any):BigIntConstructor_t);
type RpcVote_t = {
for?: string,
against?: string,
};
type RpcTxout_t = {
value: number,
svalue: string,
n: number,
address: string,
vote?: RpcVote_t,
};
type RpcTxinCoinbase_t = {
coinbase: string,
sequence: number
};
type RpcTxinNormal_t = {
txid: string,
vout: number,
scriptSig: {
asm: string,
hex: string
},
txinwitness?: Array<string>,
prevOut: {
address: string,
value: number,
svalue: string,
},
"sequence": number
};
type RpcTxin_t = RpcTxinCoinbase_t | RpcTxinNormal_t;
type RpcTx_t = {
hex: string,
txid: string,
hash: string,
size: number,
vsize: number,
version: number,
locktime: number,
vin: Array<RpcTxin_t>,
vout: Array<RpcTxout_t>
};
type RpcBlock_t = {
hash: string,
confirmations: number,
strippedsize: number,
size: number,
weight: number,
height: number,
version: number,
versionHex: string,
merkleroot: string,
rawtx: Array<RpcTx_t>,
time: number,
nonce: number,
bits: string,
difficulty: number,
previousblockhash: string,
nextblockhash: string,
packetcryptversion?: number,
packetcryptanncount?: number,
packetcryptannbits?: string,
packetcryptanndifficulty?: number,
packetcryptblkdifficulty?: number,
sblockreward: string,
networksteward?: string,
blocksuntilretarget: number,
retargetestimate: ?number,
};
type TxBlock_t = {
tx: RpcTx_t,
block: RpcBlock_t|null
};
// generated table types
import * as Tables from './lib/types_gen.js';
*/
const types = ClickHouse2.types;
const engines = ClickHouse2.engines;
const DATABASE = ClickHouse2.database();
const TABLES = {};
TABLES.blocks = DATABASE.add('blocks', ClickHouse2.table/*::<Tables.blocks_t>*/({
hash: types.FixedString(64),
height: types.Int32,
version: types.Int32,
size: types.Int32,
merkleRoot: types.FixedString(64),
time: types.DateTime_number('UTC'),
nonce: types.UInt32,
bits: types.UInt32,
difficulty: types.Float64,
previousBlockHash: types.FixedString(64),
transactionCount: types.Int32,
pcAnnCount: types.Int64,
pcAnnDifficulty: types.Float64,
pcBlkDifficulty: types.Float64,
pcVersion: types.Int8,
dateMs: types.UInt64,
networkSteward: types.String,
blocksUntilRetarget: types.Int32,
retargetEstimate: types.Float64,
}).withEngine((fields) => engines.ReplacingMergeTree(fields.dateMs)
).withOrder((fields) => [fields.hash]));
TABLES.blocktx = DATABASE.add('blocktx', ClickHouse2.table/*::<Tables.blocktx_t>*/({
blockHash: types.FixedString(64),
txid: types.FixedString(64),
dateMs: types.UInt64
}).withEngine((fields) => engines.ReplacingMergeTree(fields.dateMs)
).withOrder((fields) => [fields.blockHash, fields.txid]));
TABLES.txns = DATABASE.add('txns', ClickHouse2.table/*::<Tables.txns_t>*/({
txid: types.FixedString(64),
size: types.Int32,
vsize: types.Int32,
version: types.Int32,
locktime: types.UInt32,
inputCount: types.Int32,
outputCount: types.Int32,
value: types.Int64_string,
coinbase: types.String,
firstSeen: types.DateTime_number('UTC'),
dateMs: types.UInt64
}).withEngine((fields) => engines.ReplacingMergeTree(fields.dateMs)
).withOrder((fields) => [fields.txid]));
TABLES.chain = DATABASE.add('chain', ClickHouse2.table/*::<Tables.chain_t>*/({
hash: types.FixedString(64),
height: types.Int32,
dateMs: types.UInt64,
state: types.Enum({
uncommitted: 1,
complete: 2,
reverted: 3,
}),
}).withEngine((fields) => engines.ReplacingMergeTree(fields.dateMs)
).withOrder((fields) => [fields.height]));
// Each state is represented by a 3 bit number, the 'state' field contains both current
// and previous state, the previous state is at bit index zero and the current state is
// at bit index 3. This allows for quick filtering of state sets using a Uint64.
// 3 bits will only support a maximum of 8 states, and transitioning to 4 bits would
// require masking with a 256 bit number.
const STATE_BITS = 3;
const PREV_STATE_MASK = (1 << STATE_BITS) - 1;
const CURRENT_STATE_MASK = PREV_STATE_MASK << STATE_BITS;
// These are all of the states of a transaction output which we consider worth tracking.
// States are represented here as numbers shifted left by STATE_BITS.
const COIN_STATE = [
// We have not heard anything about this txout
'nothing',
// This txout is currently discovered and in the mempool
'mempool',
// This txout is confirmed in a block
'block',
// This txout is confirmed but there is a valid transaction in the mempool to spend it.
'spending',
// This txout has been confirmed in a block and a spend has also been confirmed
'spent',
// This txout has burned (network steward payments only)
'burned',
].reduce((x, e, i) => { x[e] = i << STATE_BITS; return x; }, {});
// MASK is a set of bitmasks for each of the fields which apply the rules for
// state transitions. In order to determine whether a given state transition
// increases the balance, take: ((1 << stateTr) | MASK.balance.add)
// to determine if it decreases the balance, take: ((1 << stateTr) | MASK.balance.sub])
/*::
type Mask_t = { add: number, sub: number };
*/
const MASK /*:{ [string]: Mask_t }*/ = (() => {
const list = [];
const states = Object.keys(COIN_STATE);
for (let sFrom in COIN_STATE) {
const from = COIN_STATE[sFrom];
for (let sTo in COIN_STATE) {
const to = COIN_STATE[sTo];
const grid = new Array(states.length).fill(0);
grid[states.indexOf(sTo)] += 1;
grid[states.indexOf(sFrom)] -= 1;
list.push({ name: sFrom + '|' + sTo, from, to, grid });
}
}
// console.log(states);
// list.forEach((x)=>console.log(x.name,new Array(20-x.name.length).join(' '),x.grid));
const mask = {};
for (const el of list) {
const number = BigInt(1) << BigInt(el.to | (el.from >> STATE_BITS));
el.grid.forEach((n, i) => {
const x = mask[states[i]] = (mask[states[i]] || { add: BigInt(0), sub: BigInt(0) });
if (n === 1) {
x.add |= number;
} else if (n === -1) {
x.sub |= number;
}
});
}
return mask;
})();
// Generate an sql clause to test whether the state transition field matches any of
// a set of states. The following example will return 1 if the spending or spent fields
// should be incremented, -1 if they should be deincremented (rollback) or 0 otherwise.
// matchStateTrClause('stateTr', [MASK.spending, MASK.spent])
const matchStateTrClause = (sTr, masks /*:Array<Mask_t>*/) => `(
(bitAnd( bitShiftLeft(toUInt64(1), ${sTr}),
0x${masks.map((m) => m.add).reduce((out, n) => (out | n), BigInt(0)).toString(16)
} ) != 0) -
(bitAnd( bitShiftLeft(toUInt64(1), ${sTr}),
0x${masks.map((m) => m.sub).reduce((out, n) => (out | n), BigInt(0)).toString(16)}
) != 0)
)`;
const coins = DATABASE.add('coins', ClickHouse2.table/*::<Tables.coins_t>*/({
// Key
address: types.String,
mintTxid: types.FixedString(64),
mintIndex: types.Int32,
// This value is special, it is merged by bit-shifting the old value and adding the new.
stateTr: types.Int8,
currentState: types.Alias(
types.Enum(COIN_STATE),
`bitAnd(stateTr, ${((1 << STATE_BITS) - 1) << STATE_BITS})`
),
prevState: types.Alias(
types.Enum(COIN_STATE),
`bitShiftLeft(bitAnd(stateTr, ${(1 << STATE_BITS) - 1}), ${STATE_BITS})`
),
dateMs: types.UInt64,
// Seen information (filled when it hits mempool)
value: types.Int64_string,
coinbase: types.Int8,
voteFor: types.String,
voteAgainst: types.String,
// This value is special, it is merged using min()
seenTime: types.DateTime_number('UTC'),
// Mint information (filled when it enters a block)
mintBlockHash: types.FixedString(64),
mintHeight: types.Int32,
mintTime: types.DateTime_number('UTC'),
// Spent information (filled when the relevant spend hits a block)
spentTxid: types.FixedString(64),
spentTxinNum: types.Int32,
spentBlockHash: types.FixedString(64),
spentHeight: types.Int32,
spentTime: types.DateTime_number('UTC'),
spentSequence: types.UInt32,
}).withEngine((fields) => engines.ReplacingMergeTree(fields.dateMs)
).withOrder((fields) => [fields.address, fields.mintTxid, fields.mintIndex]));
// Temporary tables for merge-updates
const Table_TxSeen = DATABASE.addTemp('TxSeen', ClickHouse2.table/*::<Tables.TxSeen_t>*/({
// Key
address: types.String,
mintTxid: types.FixedString(64),
mintIndex: types.Int32,
stateTr: types.Int8,
dateMs: types.UInt64,
// Seen information (filled when it hits mempool)
value: types.Int64_string,
voteFor: types.String,
voteAgainst: types.String,
coinbase: types.Int8,
seenTime: types.DateTime_number('UTC'),
}));
// We re-enter the tx-seen data because many times the first time
// we have seen the tx is when it's minted in a block.
const Table_TxMinted = DATABASE.addTemp('TxMinted', ClickHouse2.table/*::<Tables.TxMinted_t>*/({
// Key
address: types.String,
mintTxid: types.FixedString(64),
mintIndex: types.Int32,
stateTr: types.Int8,
dateMs: types.UInt64,
// Seen information (filled when it hits mempool)
value: types.Int64_string,
voteFor: types.String,
voteAgainst: types.String,
coinbase: types.Int8,
seenTime: types.DateTime_number('UTC'),
// Mint information (filled when it enters a block)
mintBlockHash: types.FixedString(64),
mintHeight: types.Int32,
mintTime: types.DateTime_number('UTC'),
}));
const Table_TxUnMinted = DATABASE.addTemp('TxUnMinted', ClickHouse2.table/*::<Tables.TxUnMinted_t>*/({
address: types.String,
mintTxid: types.FixedString(64),
mintIndex: types.Int32,
stateTr: types.Int8,
dateMs: types.UInt64,
mintBlockHash: types.FixedString(64),
mintHeight: types.Int32,
}));
// This serves also as the unspent table
const Table_TxSpent = DATABASE.addTemp('TxSpent', ClickHouse2.table/*::<Tables.TxSpent_t>*/({
address: types.String,
mintTxid: types.FixedString(64),
mintIndex: types.Int32,
stateTr: types.Int8,
dateMs: types.UInt64,
// Spent information (filled when the relevant spend hits a block)
spentTxid: types.FixedString(64),
spentTxinNum: types.Int32,
spentBlockHash: types.FixedString(64),
spentHeight: types.Int32,
spentTime: types.DateTime_number('UTC'),
spentSequence: types.UInt32,
}));
const Table_Hashes = DATABASE.addTemp('Hashes', ClickHouse2.table/*::<Tables.Hashes_t>*/({
hash: types.FixedString(64)
}));
const makeE = (done /*:(?Error)=>void*/) => (w /*:Nthen_WaitFor_t*/) => w((err) => {
if (err) {
w.abort();
return void done(err);
}
});
const error = (err /*:?Error*/, w /*:Nthen_WaitFor_t*/, done /*:(?Error)=>void*/) => {
w.abort();
done(err);
};
const eexistTable = (err) => {
if (!err) { return false; }
if (err.message.indexOf("doesn't exist") > -1) { return true; }
if (err.message.indexOf("Table is dropped") > -1) { return true; }
return false;
};
const dbCreateVotes = (ctx, done) => {
const e = makeE(done);
const selectClause = (s, voteType) => `SELECT
'${voteType === 'voteFor' ? 'for' : 'against'}' AS type,
${voteType} AS candidate,
value * ${matchStateTrClause(s, [MASK.block])} AS votes
`;
nThen((w) => {
if (!ctx.recompute) { return; }
ctx.snclog.info('--recompute recomputing votes table');
nThen((w) => {
ctx.ch.modify(`DROP TABLE IF EXISTS votes`, e(w));
}).nThen((w) => {
ctx.ch.modify(`DROP TABLE IF EXISTS votes_for_mv`, e(w));
}).nThen((w) => {
ctx.ch.modify(`DROP TABLE IF EXISTS votes_against_mv`, e(w));
}).nThen(w());
}).nThen((w) => {
ctx.ch.query(`SELECT * FROM votes LIMIT 1`, w((err, _) => {
if (eexistTable(err)) {
return;
}
// err or already exists
w.abort();
return void done(err);
}));
}).nThen((w) => {
ctx.ch.modify(`CREATE TABLE votes (
type Enum('for' = 0, 'against' = 1),
candidate String,
votes SimpleAggregateFunction(sum, Int64)
) ENGINE AggregatingMergeTree()
ORDER BY (type, candidate)
`, e(w));
}).nThen((w) => {
ctx.ch.modify(`INSERT INTO votes ${selectClause(`bitAnd(${CURRENT_STATE_MASK}, stateTr)`, 'voteFor')}
FROM ${coins.name()}
FINAL
`, e(w));
}).nThen((w) => {
ctx.ch.modify(`INSERT INTO votes ${selectClause(`bitAnd(${CURRENT_STATE_MASK}, stateTr)`, 'voteAgainst')}
FROM ${coins.name()}
FINAL
`, e(w));
}).nThen((w) => {
ctx.ch.modify(`CREATE MATERIALIZED VIEW IF NOT EXISTS votes_for_mv TO votes AS
${selectClause('stateTr', 'voteFor')} FROM ${coins.name()}
`, e(w));
}).nThen((w) => {
ctx.ch.modify(`CREATE MATERIALIZED VIEW IF NOT EXISTS votes_against_mv TO votes AS
${selectClause('stateTr', 'voteAgainst')} FROM ${coins.name()}
`, e(w));
}).nThen((_) => {
if (ctx.recompute) {
ctx.snclog.info('--recompute recomputing votes table COMPLETE');
}
done();
});
};
const dbCreateBalances = (ctx, done) => {
const e = makeE(done);
const selectClause = (s) => `SELECT
address,
value * ${matchStateTrClause(s, [MASK.mempool])} AS mempool,
value * ${matchStateTrClause(s, [MASK.block])} AS balance,
value * ${matchStateTrClause(s, [MASK.spending])} AS spending,
value * ${matchStateTrClause(s, [MASK.spent])} AS spent,
value * ${matchStateTrClause(s, [MASK.burned])} AS burned,
(coinbase == 0) AS recvCount,
(coinbase == 1) AS mineCount,
1 * ${matchStateTrClause(s, [MASK.spent])} AS spentCount,
1 * ${matchStateTrClause(s, [MASK.block])} AS balanceCount,
seenTime AS firstSeen
`;
nThen((w) => {
if (!ctx.recompute) { return; }
ctx.snclog.info('--recompute recomputing balances2 table');
nThen((w) => {
ctx.ch.modify(`DROP TABLE IF EXISTS balances2`, e(w));
}).nThen((w) => {
ctx.ch.modify(`DROP TABLE IF EXISTS balances2_mv`, e(w));
}).nThen(w());
}).nThen((w) => {
// old balances table, drop it
nThen((w) => {
ctx.ch.modify(`DROP TABLE IF EXISTS balances`, e(w));
}).nThen((w) => {
ctx.ch.modify(`DROP TABLE IF EXISTS balances_mv`, e(w));
}).nThen(w());
ctx.ch.query(`SELECT * FROM balances2 LIMIT 1`, w((err, _) => {
if (eexistTable(err)) {
return;
}
// err or already exists
w.abort();
return void done(err);
}));
}).nThen((w) => {
ctx.ch.modify(`CREATE TABLE balances2 (
address String,
mempool SimpleAggregateFunction(sum, Int64),
balance SimpleAggregateFunction(sum, Int64),
spending SimpleAggregateFunction(sum, Int64),
spent SimpleAggregateFunction(sum, Int64),
burned SimpleAggregateFunction(sum, Int64),
recvCount SimpleAggregateFunction(sum, Int64),
mineCount SimpleAggregateFunction(sum, Int64),
spentCount SimpleAggregateFunction(sum, Int64),
balanceCount SimpleAggregateFunction(sum, Int64),
firstSeen SimpleAggregateFunction(min, DateTime('UTC'))
) ENGINE AggregatingMergeTree()
ORDER BY address
`, e(w));
}).nThen((w) => {
// We mask the state here so that all states are from previous "nothing"
// because this is the first time this has ever been seen.
ctx.ch.modify(`INSERT INTO balances2 ${selectClause(`bitAnd(${CURRENT_STATE_MASK}, stateTr)`)}
FROM ${coins.name()}
FINAL
`, e(w));
}).nThen((w) => {
ctx.ch.modify(`CREATE MATERIALIZED VIEW IF NOT EXISTS balances2_mv TO balances2 AS
${selectClause('stateTr')} FROM ${coins.name()}
`, e(w));
}).nThen((w) => {
if (ctx.recompute) {
ctx.snclog.info('--recompute recomputing balances2 table COMPLETE');
}
done();
});
};
const dbCreateAddrIncome = (ctx, done) => {
const e = makeE(done);
const selectClause = (s) => `SELECT
address,
toDate(mintTime) AS date,
coinbase,
value * ${matchStateTrClause(s, [
MASK.block, MASK.spending, MASK.spent, MASK.burned])} AS received
`;
nThen((w) => {
if (!ctx.recompute) { return; }
ctx.snclog.info('--recompute recomputing addrincome table');
nThen((w) => {
ctx.ch.modify(`DROP TABLE IF EXISTS addrincome`, e(w));
}).nThen((w) => {
ctx.ch.modify(`DROP TABLE IF EXISTS addrincome_mv`, e(w));
}).nThen(w());
}).nThen((w) => {
ctx.ch.query(`SELECT * FROM addrincome LIMIT 1`, w((err, _) => {
if (eexistTable(err)) {
return;
}
// err or already exists
w.abort();
return void done(err);
}));
}).nThen((w) => {
ctx.ch.modify(`CREATE TABLE addrincome (
address String,
date Date,
coinbase Int8,
received SimpleAggregateFunction(sum, Int64)
) ENGINE AggregatingMergeTree()
ORDER BY (address, date, coinbase)
`, e(w));
}).nThen((w) => {
// We mask the state here so that all states are from previous "nothing"
// because this is the first time this has ever been seen.
ctx.ch.modify(`INSERT INTO addrincome ${selectClause(`bitAnd(${CURRENT_STATE_MASK}, stateTr)`)}
FROM ${coins.name()}
FINAL
`, e(w));
}).nThen((w) => {
ctx.ch.modify(`CREATE MATERIALIZED VIEW IF NOT EXISTS addrincome_mv TO addrincome AS
${selectClause('stateTr')} FROM ${coins.name()}
`, e(w));
}).nThen((_) => {
if (ctx.recompute) {
ctx.snclog.info('--recompute recomputing balances table COMPLETE');
}
done();
});
};
const dbCreateTxview = (ctx, done) => {
const fields = {
unconfirmed: [MASK.mempool],
received: [MASK.block, MASK.spending, MASK.spent, MASK.burned],
spending: [MASK.spending],
spent: [MASK.spent],
burned: [MASK.burned],
};
const e = makeE(done);
const select = (txid, io, s) => `SELECT
${txid} AS txid,
'${io}' AS type,
address AS address,
coinbase,
${matchStateTrClause(s, [MASK.spent, MASK.spending])} AS spentcount,
${Object.keys(fields).map((k) =>
`value * ${matchStateTrClause(s, fields[k])} AS ${k}`).join(',')}
`;
nThen((w) => {
if (!ctx.recompute) { return; }
ctx.snclog.info('--recompute recomputing txview table');
nThen((w) => {
ctx.ch.modify(`DROP TABLE IF EXISTS txview`, e(w));
}).nThen((w) => {
ctx.ch.modify(`DROP TABLE IF EXISTS txview_mv_out`, e(w));
}).nThen((w) => {
ctx.ch.modify(`DROP TABLE IF EXISTS txview_mv_in`, e(w));
}).nThen(w());
}).nThen((w) => {
ctx.ch.query(`SELECT * FROM txview LIMIT 1`, w((err, _) => {
if (eexistTable(err)) {
return;
}
// err or already exists
w.abort();
return void done(err);
}));
}).nThen((w) => {
ctx.ch.modify(`CREATE TABLE txview (
txid FixedString(64),
type Enum('input' = 0, 'output' = 1),
address String,
coinbase Int8,
spentcount SimpleAggregateFunction(sum, Int64),
${Object.keys(fields).map((f) => (
`${f} SimpleAggregateFunction(sum, Int64)`
)).join(', ')}
) ENGINE AggregatingMergeTree()
ORDER BY (txid, type, address, coinbase)
`, w((err, _) => {
if (err) { return void error(err, w, done); }
}));
}).nThen((w) => {
ctx.ch.modify(`INSERT INTO txview
${select('mintTxid', 'output', `bitAnd(${CURRENT_STATE_MASK}, stateTr)`)}
FROM ${coins.name()}
FINAL
`, w((err, _) => {
if (err) {
w.abort();
return void done(err);
}
}));
}).nThen((w) => {
ctx.ch.modify(`CREATE MATERIALIZED VIEW IF NOT EXISTS txview_mv_out TO txview AS
${select('mintTxid', 'output', 'stateTr')}
FROM ${coins.name()}
`, w((err, _) => {
if (err) {
w.abort();
return void done(err);
}
}));
}).nThen((w) => {
ctx.ch.modify(`INSERT INTO txview
${select('spentTxid', 'input', `bitAnd(${CURRENT_STATE_MASK}, stateTr)`)}
FROM ${coins.name()}
FINAL
WHERE spentTxid != toFixedString('',64)
`, w((err, _) => {
if (err) {
w.abort();
return void done(err);
}
}));
}).nThen((w) => {
ctx.ch.modify(`CREATE MATERIALIZED VIEW IF NOT EXISTS txview_mv_in TO txview AS
${select('spentTxid', 'input', 'stateTr')}
FROM ${coins.name()}
WHERE spentTxid != toFixedString('',64)
`, w((err, _) => {
if (err) {
w.abort();
return void done(err);
}
}));
}).nThen((_) => {
if (ctx.recompute) {
ctx.snclog.info('--recompute recomputing txview table COMPLETE');
}
done();
});
};
const createChainView = (ctx, done) => {
const e = makeE(done);
nThen((w) => {
if (!ctx.recompute) { return; }
ctx.snclog.info('--recompute recomputing chain view');
nThen((w) => {
ctx.ch.modify(`DROP TABLE IF EXISTS chain_v`, e(w));
}).nThen(w());
}).nThen((w) => {
ctx.ch.modify(`CREATE VIEW IF NOT EXISTS chain_v AS SELECT
*
FROM chain
WHERE height >= 0
ORDER BY
height DESC,
dateMs DESC
LIMIT 1 BY height
`, e(w));
}).nThen((_) => {
if (ctx.recompute) {
ctx.snclog.info('--recompute recomputing chain view COMPLETE');
}
done();
});
};
const dbOptimize = (ctx, done) => {
let nt = nThen;
// filter so we don't get any materialized views
const tables0 = DATABASE.tables();
const tables = Object.keys(tables0).filter((t) => ('fields' in tables0[t]));
tables.forEach((t) => {
nt = nt((w) => {
ctx.ch.modify(`OPTIMIZE TABLE ${t}`, w((err, _) => {
if (err) {
w.abort();
return void done(err);
}
}));
}).nThen;
});
nt((_) => {
done();
});
};
// This block must be present in the chain table order to be able to load the genesis block
const phonyBlock = () => ({
hash: '0000000000000000000000000000000000000000000000000000000000000000',
height: -1,
state: 'complete',
dateMs: +new Date(),
});
const createTables = (ctx, done) => {
const defaultDb = ctx.ch.withDb('default');
const e = makeE(done);
nThen((w) => {
defaultDb.query('SELECT 1', w((err, ret) => {
if (err || !ret) { return void error(err, w, done); }
if (JSON.stringify(ret) !== '[{"1":1}]') {
return void error(new Error("Unexpected result: " + JSON.stringify(ret)), w, done);
}
}));
}).nThen((w) => {
defaultDb.modify(`CREATE DATABASE IF NOT EXISTS ${ctx.ch.opts.db}`, w((err, ret) => {
if (!ret || ret.length) { return void error(err, w, done); }
}));
}).nThen((w) => {
DATABASE.create(ctx.ch, [ClickHouse2.IF_NOT_EXISTS], e(w));
}).nThen((w) => {
// Always make sure we have the phony block in the chain table, otherwise it's impossible
// to load the genesis because it doesn't link to anything.
ctx.ch.insert(TABLES.chain, [phonyBlock()], e(w));
}).nThen((w) => {
if (!ctx.recompute) { return; }
ctx.snclog.info('--recompute OPTIMIZE all tables');
dbOptimize(ctx, e(w));
}).nThen((w) => {
createChainView(ctx, e(w));
}).nThen((w) => {
dbCreateBalances(ctx, e(w));
}).nThen((w) => {
dbCreateTxview(ctx, e(w));
}).nThen((w) => {
dbCreateAddrIncome(ctx, e(w));
}).nThen((w) => {
dbCreateVotes(ctx, e(w));
}).nThen((_) => {
done();
});
};
const rpcRes = /*::<X>*/(
done/*:(err:?Error,x:?X)=>void*/
) /*:Rpc_Client_Rpc_t<X>*/ => {
return (err, ret) => {
if (err) {
done(err);
} else if (!ret) {
done(new Error("no result"));
} else if (ret.error) {
done(ret.error);
} else if (!ret.result) {
done(new Error("no ret.result"));
} else {
done(null, ret.result);
}
};
};
const rpcGetBlockByHash = (ctx, hash /*:string*/, inclTxns, done) => {
ctx.btc.getBlock(hash, +true, +inclTxns, rpcRes((err, ret) => {
if (!ret) { return void done(err); }
done(null, (ret /*:RpcBlock_t*/));
}));
};
const rpcGetBlockByHeight = (ctx, height /*:number*/, inclTxns, done) => {
ctx.btc.getBlockHash(height, rpcRes((err, hash) => {
if (!hash) { return void done(err); }
rpcGetBlockByHash(ctx, hash, inclTxns, done);
}));
};
// getrawmempool
const rpcGetMempool = (ctx, done) => {
ctx.btc.batch(() => {
ctx.btc.batchedCalls = {
jsonrpc: "1.0",
id: "pkt-explorer-backend",
method: "getrawmempool",
params: []
};
}, rpcRes((err, ret) => {
if (!ret) { return void done(err); }
done(null, (ret /*:Array<string>*/));
}));
};
const rpcGetTransaction = (ctx, hash /*:string*/, done) => {
ctx.btc.getRawTransaction(hash, 1, rpcRes((err, ret) => {
if (!ret) { return void done(err); }
done(null, ret);
}));
};
const getTransactionsForHashes = (ctx, hashes, done) => {
const transactions = [];
let nt = nThen;
ctx.snclog.debug(`Getting [${hashes.length}] transactions`);
hashes.forEach((th) => {
nt = nt((w) => {
rpcGetTransaction(ctx, th, w((err, tx) => {
if (!tx) {
ctx.snclog.error(`Failed to get transaction [${th}] ` +
`[${Util.inspect(err)}] will retry later...`);
return;
}
transactions.push(tx);
}));
}).nThen;
});
nt(() => {
done(transactions);
});
};
const convertTxin = (
txBlock /*:TxBlock_t*/,
txin /*:RpcTxin_t*/,
dateMs /*:number*/
) /*:Tables.TxSpent_t*/ => {
const { tx, block } = txBlock;
const txinNum = tx.vin.indexOf(txin);
if (txinNum < 0) { throw new Error(); }
if (!txin.txid) {
throw new Error("I can't understand this txin " + JSON.stringify(txin));
}
const normaltxin = ((txin /*:any*/) /*:RpcTxinNormal_t*/);
const address = normaltxin.prevOut.address;
const out = {
mintTxid: normaltxin.txid,
mintIndex: normaltxin.vout,
address,
stateTr: (block) ? COIN_STATE.spent : COIN_STATE.spending,
spentTxid: tx.txid,
spentTxinNum: txinNum,
spentBlockHash: block ? block.hash : "",
spentHeight: block ? block.height : 0,
spentTime: block ? block.time : 0,
spentSequence: txin.sequence,
dateMs: dateMs,
};
return out;
};
const getCoinbase = (ctx, txBlock, txout, value) => {
if (!('coinbase' in txBlock.tx.vin[0])) { return 0; }
if (ctx.chain !== 'PKT') { return 1; }
const block = txBlock.block;
if (!block) { throw new Error("free coinbase transaction is not allowed"); }
// special network steward payout stuff for PKT
// detection of a network steward payment is done by looking for any
// coinbase payment of precisely 51/256ths of the computed block reward.
const period = Math.floor(block.height / 144000);
let a = BigInt(1);
let b = BigInt(1);
for (let i = 0; i < period; i++) {
a *= BigInt(9);
b *= BigInt(10);
}
const reward = a * BigInt(4166) * BigInt(0x40000000) / b;
const nspayout = reward * BigInt(51) / BigInt(256);
if (value === nspayout) {
return 2;
}
return 1;
};
const convertTxout = (ctx, txBlock /*:TxBlock_t*/, txout /*:RpcTxout_t*/, dateMs) /*:Tables.TxMinted_t*/ => {
const { tx, block } = txBlock;
const value = BigInt(txout.svalue);
const vote = typeof (txout.vote) !== 'undefined' ? txout.vote : {};
const out = {
address: txout.address,
mintTxid: tx.txid,
mintIndex: txout.n,
stateTr: (block) ? COIN_STATE.block : COIN_STATE.mempool,
dateMs: dateMs,
seenTime: (block) ? block.time : Math.floor(dateMs / 1000),
value: value.toString(),
voteFor: vote.for || '',
voteAgainst: vote.against || '',
coinbase: getCoinbase(ctx, txBlock, txout, value),
mintBlockHash: (block) ? block.hash : "",
mintHeight: (block) ? block.height : -1,
mintTime: (block) ? block.time : Math.floor(dateMs / 1000),
};
return out;
};
/*::
type Tx_t = {
meta: Tables.txns_t,
vin: Array<Tables.TxSpent_t>,
vout: Array<Tables.TxMinted_t>
};
*/
const convertTx = (ctx, txBlock /*:TxBlock_t*/, dateMs) /*:Tx_t*/ => {
let value = BigInt(0);
const { tx, block } = txBlock;
tx.vout.forEach((x) => { value += BigInt(x.svalue); });
let coinbase = "";
if (typeof (tx.vin[0].coinbase) === 'string') {
coinbase = tx.vin[0].coinbase;
}
const out = {
meta: {