-
Notifications
You must be signed in to change notification settings - Fork 123
/
Copy pathpg-store.ts
4538 lines (4392 loc) · 161 KB
/
pg-store.ts
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
import { ClarityAbi } from '@stacks/transactions';
import { getTxTypeId, getTxTypeString, TransactionType } from '../api/controllers/db-controller';
import {
unwrapNotNullish,
FoundOrNot,
unwrapOptional,
bnsHexValueToName,
bnsNameCV,
getBnsSmartContractId,
bnsNameFromSubdomain,
ChainID,
REPO_DIR,
} from '../helpers';
import { PgStoreEventEmitter } from './pg-store-event-emitter';
import {
BlockIdentifier,
BlockQueryResult,
BlocksWithMetadata,
ContractTxQueryResult,
DbAssetEventTypeId,
DbBlock,
DbBnsName,
DbBnsNamespace,
DbBnsSubdomain,
DbBnsZoneFile,
DbBurnchainReward,
DbChainTip,
DbEvent,
DbEventTypeId,
DbFtBalance,
DbFtEvent,
DbGetBlockWithMetadataOpts,
DbGetBlockWithMetadataResponse,
DbInboundStxTransfer,
DbMempoolFeePriority,
DbMempoolStats,
DbMempoolTx,
DbMicroblock,
DbMinerReward,
DbNftEvent,
DbRewardSlotHolder,
DbSearchResult,
DbSmartContract,
DbSmartContractEvent,
DbStxBalance,
DbStxEvent,
DbStxLockEvent,
DbTokenOfferingLocked,
DbTx,
DbTxGlobalStatus,
DbTxStatus,
DbTxTypeId,
DbTxWithAssetTransfers,
FaucetRequestQueryResult,
MempoolTxQueryResult,
MicroblockQueryResult,
NftEventWithTxMetadata,
NftHoldingInfo,
NftHoldingInfoWithTxMetadata,
PoxSyntheticEventQueryResult,
RawTxQueryResult,
StxUnlockEvent,
TransferQueryResult,
PoxSyntheticEventTable,
DbPoxStacker,
DbPoxSyntheticEvent,
} from './common';
import {
abiColumn,
BLOCK_COLUMNS,
MEMPOOL_TX_COLUMNS,
MICROBLOCK_COLUMNS,
parseBlockQueryResult,
parseDbEvents,
parseDbPoxSyntheticEvent,
parseFaucetRequestQueryResult,
parseMempoolTxQueryResult,
parseMicroblockQueryResult,
parseQueryResultToSmartContract,
parseTxQueryResult,
parseTxsWithAssetTransfers,
POX4_SYNTHETIC_EVENT_COLUMNS,
POX_SYNTHETIC_EVENT_COLUMNS,
prefixedCols,
TX_COLUMNS,
validateZonefileHash,
} from './helpers';
import { PgNotifier } from './pg-notifier';
import { SyntheticPoxEventName } from '../pox-helpers';
import { BasePgStore, PgSqlClient, connectPostgres } from '@hirosystems/api-toolkit';
import {
PgServer,
getConnectionArgs,
getConnectionConfig,
getPgConnectionEnvValue,
} from './connection';
import * as path from 'path';
import { PgStoreV2 } from './pg-store-v2';
import { Fragment } from 'postgres';
import { parseBlockParam } from '../api/routes/v2/schemas';
export const MIGRATIONS_DIR = path.join(REPO_DIR, 'migrations');
const TRGM_SIMILARITY_THRESHOLD = 0.3;
/**
* This is the main interface between the API and the Postgres database. It contains all methods that
* query the DB in search for blockchain data to be returned via endpoints or WebSockets/Socket.IO.
* It also provides an `EventEmitter` to notify the rest of the API whenever an important DB write has
* happened in the `PgServer.primary` server (see `.env`).
*/
export class PgStore extends BasePgStore {
readonly v2: PgStoreV2;
readonly eventEmitter: PgStoreEventEmitter;
readonly notifier?: PgNotifier;
constructor(sql: PgSqlClient, notifier: PgNotifier | undefined = undefined) {
super(sql);
this.notifier = notifier;
this.eventEmitter = new PgStoreEventEmitter();
this.v2 = new PgStoreV2(this);
}
static async connect({
usageName,
withNotifier = true,
}: {
usageName: string;
withNotifier?: boolean;
}): Promise<PgStore> {
const sql = await connectPostgres({
usageName: usageName,
connectionArgs: getConnectionArgs(),
connectionConfig: getConnectionConfig(),
});
const notifier = withNotifier ? await PgNotifier.create(usageName) : undefined;
const store = new PgStore(sql, notifier);
await store.connectPgNotifier();
return store;
}
async close(args?: { timeout?: number }): Promise<void> {
await this.notifier?.close();
await super.close({
timeout:
args?.timeout ??
parseInt(getPgConnectionEnvValue('CLOSE_TIMEOUT', PgServer.default) ?? '5'),
});
}
/**
* Connects to the `PgNotifier`. Its messages will be forwarded to the rest of the API components
* though the EventEmitter.
*/
async connectPgNotifier() {
await this.notifier?.connect(notification => {
switch (notification.type) {
case 'blockUpdate':
this.eventEmitter.emit('blockUpdate', notification.payload.blockHash);
break;
case 'microblockUpdate':
this.eventEmitter.emit('microblockUpdate', notification.payload.microblockHash);
break;
case 'txUpdate':
this.eventEmitter.emit('txUpdate', notification.payload.txId);
break;
case 'addressUpdate':
this.eventEmitter.emit(
'addressUpdate',
notification.payload.address,
notification.payload.blockHeight
);
break;
case 'tokensUpdate':
this.eventEmitter.emit('tokensUpdate', notification.payload.contractID);
break;
case 'nameUpdate':
this.eventEmitter.emit('nameUpdate', notification.payload.nameInfo);
break;
case 'tokenMetadataUpdateQueued':
this.eventEmitter.emit('tokenMetadataUpdateQueued', notification.payload.queueId);
break;
case 'nftEventUpdate':
this.eventEmitter.emit(
'nftEventUpdate',
notification.payload.txId,
notification.payload.eventIndex
);
break;
case 'smartContractUpdate':
this.eventEmitter.emit('smartContractUpdate', notification.payload.contractId);
break;
case 'smartContractLogUpdate':
this.eventEmitter.emit(
'smartContractLogUpdate',
notification.payload.txId,
notification.payload.eventIndex
);
break;
case 'configStateUpdate':
this.eventEmitter.emit('configStateUpdate', notification.payload);
break;
}
});
}
async getChainTip(sql: PgSqlClient): Promise<DbChainTip> {
const tipResult = await sql<DbChainTip[]>`SELECT * FROM chain_tip`;
const tip = tipResult[0];
return {
block_height: tip?.block_height ?? 0,
block_count: tip?.block_count ?? 0,
block_hash: tip?.block_hash ?? '',
index_block_hash: tip?.index_block_hash ?? '',
burn_block_height: tip?.burn_block_height ?? 0,
microblock_hash: tip?.microblock_hash ?? undefined,
microblock_sequence: tip?.microblock_sequence ?? undefined,
microblock_count: tip?.microblock_count ?? 0,
tx_count: tip?.tx_count ?? 0,
tx_count_unanchored: tip?.tx_count_unanchored ?? 0,
mempool_tx_count: tip?.mempool_tx_count ?? 0,
};
}
async getBlockWithMetadata<TWithTxs extends boolean, TWithMicroblocks extends boolean>(
blockIdentifier: BlockIdentifier,
metadata?: DbGetBlockWithMetadataOpts<TWithTxs, TWithMicroblocks>
): Promise<FoundOrNot<DbGetBlockWithMetadataResponse<TWithTxs, TWithMicroblocks>>> {
return await this.sqlTransaction(async sql => {
const block = await this.getBlockInternal(sql, blockIdentifier);
if (!block.found) {
return { found: false };
}
let txs: DbTx[] | null = null;
const microblocksAccepted: DbMicroblock[] = [];
const microblocksStreamed: DbMicroblock[] = [];
const microblock_tx_count: Record<string, number> = {};
if (metadata?.txs) {
const txQuery = await sql<ContractTxQueryResult[]>`
SELECT ${sql(TX_COLUMNS)}, ${abiColumn(sql)}
FROM txs
WHERE index_block_hash = ${block.result.index_block_hash}
AND canonical = true AND microblock_canonical = true
ORDER BY microblock_sequence DESC, tx_index DESC
`;
txs = txQuery.map(r => parseTxQueryResult(r));
}
if (metadata?.microblocks) {
const microblocksQuery = await sql<
(MicroblockQueryResult & { transaction_count: number })[]
>`
SELECT ${sql(MICROBLOCK_COLUMNS)}, (
SELECT COUNT(tx_id)::integer as transaction_count
FROM txs
WHERE txs.microblock_hash = microblocks.microblock_hash
AND canonical = true AND microblock_canonical = true
)
FROM microblocks
WHERE parent_index_block_hash
IN ${sql([block.result.index_block_hash, block.result.parent_index_block_hash])}
AND microblock_canonical = true
ORDER BY microblock_sequence ASC
`;
for (const mb of microblocksQuery) {
const parsedMicroblock = parseMicroblockQueryResult(mb);
const count = mb.transaction_count;
if (parsedMicroblock.parent_index_block_hash === block.result.parent_index_block_hash) {
microblocksAccepted.push(parsedMicroblock);
microblock_tx_count[parsedMicroblock.microblock_hash] = count;
}
if (parsedMicroblock.parent_index_block_hash === block.result.index_block_hash) {
microblocksStreamed.push(parsedMicroblock);
}
}
}
type ResultType = DbGetBlockWithMetadataResponse<TWithTxs, TWithMicroblocks>;
const result: ResultType = {
block: block.result,
txs: txs as ResultType['txs'],
microblocks: {
accepted: microblocksAccepted,
streamed: microblocksStreamed,
} as ResultType['microblocks'],
microblock_tx_count,
};
return {
found: true,
result: result,
};
});
}
async getPoxForcedUnlockHeightsInternal(sql: PgSqlClient): Promise<
FoundOrNot<{
pox1UnlockHeight: number | null;
pox2UnlockHeight: number | null;
pox3UnlockHeight: number | null;
}>
> {
const query = await sql<
{ pox_v1_unlock_height: string; pox_v2_unlock_height: string; pox_v3_unlock_height: string }[]
>`
SELECT pox_v1_unlock_height, pox_v2_unlock_height, pox_v3_unlock_height
FROM pox_state
LIMIt 1
`;
if (query.length === 0) {
return { found: false };
}
const pox1UnlockHeight = parseInt(query[0].pox_v1_unlock_height) || null;
const pox2UnlockHeight = parseInt(query[0].pox_v2_unlock_height) || null;
const pox3UnlockHeight = parseInt(query[0].pox_v3_unlock_height) || null;
if (pox2UnlockHeight === 0) {
return { found: false };
}
return { found: true, result: { pox1UnlockHeight, pox2UnlockHeight, pox3UnlockHeight } };
}
async getPoxForceUnlockHeights() {
return this.getPoxForcedUnlockHeightsInternal(this.sql);
}
async getBlock(blockIdentifer: BlockIdentifier): Promise<FoundOrNot<DbBlock>> {
return this.getBlockInternal(this.sql, blockIdentifer);
}
async getBlockInternal(
sql: PgSqlClient,
blockIdentifer: BlockIdentifier
): Promise<FoundOrNot<DbBlock>> {
const result = await sql<BlockQueryResult[]>`
SELECT ${sql(BLOCK_COLUMNS)}
FROM blocks
WHERE ${
'hash' in blockIdentifer
? sql`block_hash = ${blockIdentifer.hash}`
: 'height' in blockIdentifer
? sql`block_height = ${blockIdentifer.height}`
: 'burnBlockHash' in blockIdentifer
? sql`burn_block_hash = ${blockIdentifer.burnBlockHash}`
: sql`burn_block_height = ${blockIdentifer.burnBlockHeight}`
}
ORDER BY canonical DESC, block_height DESC
LIMIT 1
`;
if (result.length === 0) {
return { found: false } as const;
}
const row = result[0];
const block = parseBlockQueryResult(row);
return { found: true, result: block } as const;
}
async getBlockByHeightInternal(
sql: PgSqlClient,
blockHeight: number
): Promise<FoundOrNot<DbBlock>> {
const result = await sql<BlockQueryResult[]>`
SELECT ${sql(BLOCK_COLUMNS)}
FROM blocks
WHERE block_height = ${blockHeight} AND canonical = true
`;
if (result.length === 0) {
return { found: false } as const;
}
const row = result[0];
const block = parseBlockQueryResult(row);
return { found: true, result: block } as const;
}
async getCurrentBlock(): Promise<FoundOrNot<DbBlock>> {
return this.getCurrentBlockInternal(this.sql);
}
async getCurrentBlockHeight(): Promise<FoundOrNot<number>> {
const result = await this.sql<{ block_height: number }[]>`SELECT block_height FROM chain_tip`;
if (result.length === 0) {
return { found: false } as const;
}
const row = result[0];
return { found: true, result: row.block_height } as const;
}
async getCurrentBlockInternal(sql: PgSqlClient): Promise<FoundOrNot<DbBlock>> {
const result = await sql<BlockQueryResult[]>`
SELECT ${sql(BLOCK_COLUMNS.map(c => `b.${c}`))}
FROM blocks b
INNER JOIN chain_tip t USING (index_block_hash, block_hash, block_height, burn_block_height)
LIMIT 1
`;
if (result.length === 0) {
return { found: false } as const;
}
const row = result[0];
const block = parseBlockQueryResult(row);
return { found: true, result: block } as const;
}
/**
* Returns Block information with metadata, including accepted and streamed microblocks hash
* @returns `BlocksWithMetadata` object including list of Blocks with metadata and total count.
* @deprecated use `getV2Blocks`
*/
async getBlocksWithMetadata({
limit,
offset,
}: {
limit: number;
offset: number;
}): Promise<BlocksWithMetadata> {
return await this.sqlTransaction(async sql => {
// Get blocks with count.
const countQuery = await sql<{ count: number }[]>`
SELECT block_count AS count FROM chain_tip
`;
const block_count = countQuery[0].count;
const blocksQuery = await sql<BlockQueryResult[]>`
SELECT ${sql(BLOCK_COLUMNS)}
FROM blocks
WHERE canonical = true
ORDER BY block_height DESC
LIMIT ${limit}
OFFSET ${offset}
`;
const blocks = blocksQuery.map(r => parseBlockQueryResult(r));
const blockHashValues: string[] = [];
const indexBlockHashValues: string[] = [];
blocks.forEach(block => {
const indexBytea = block.index_block_hash;
const parentBytea = block.parent_index_block_hash;
indexBlockHashValues.push(indexBytea, parentBytea);
blockHashValues.push(indexBytea);
});
if (blockHashValues.length === 0) {
return {
results: [],
total: block_count,
};
}
// get txs in those blocks
const txs = await sql<{ tx_id: string; index_block_hash: string }[]>`
SELECT tx_id, index_block_hash
FROM txs
WHERE index_block_hash IN ${sql(blockHashValues)}
AND canonical = true AND microblock_canonical = true
ORDER BY microblock_sequence DESC, tx_index DESC
`;
// get microblocks in those blocks
const microblocksQuery = await sql<
{
parent_index_block_hash: string;
index_block_hash: string;
microblock_hash: string;
transaction_count: number;
}[]
>`
SELECT parent_index_block_hash, index_block_hash, microblock_hash, (
SELECT COUNT(tx_id)::integer as transaction_count
FROM txs
WHERE txs.microblock_hash = microblocks.microblock_hash
AND canonical = true AND microblock_canonical = true
)
FROM microblocks
WHERE parent_index_block_hash IN ${sql(indexBlockHashValues)}
AND microblock_canonical = true
ORDER BY microblock_sequence DESC
`;
// parse data to return
const blocksMetadata = blocks.map(block => {
const transactions = txs
.filter(tx => tx.index_block_hash === block.index_block_hash)
.map(tx => tx.tx_id);
const microblocksAccepted = microblocksQuery
.filter(
microblock => block.parent_index_block_hash === microblock.parent_index_block_hash
)
.map(mb => {
return {
microblock_hash: mb.microblock_hash,
transaction_count: mb.transaction_count,
};
});
const microblocksStreamed = microblocksQuery
.filter(microblock => block.parent_index_block_hash === microblock.index_block_hash)
.map(mb => mb.microblock_hash);
const microblock_tx_count: Record<string, number> = {};
microblocksAccepted.forEach(mb => {
microblock_tx_count[mb.microblock_hash] = mb.transaction_count;
});
return {
block,
txs: transactions,
microblocks_accepted: microblocksAccepted.map(mb => mb.microblock_hash),
microblocks_streamed: microblocksStreamed,
microblock_tx_count,
};
});
const results: BlocksWithMetadata = {
results: blocksMetadata,
total: block_count,
};
return results;
});
}
/**
* @deprecated Only used in tests
*/
async getBlockTxs(indexBlockHash: string) {
const result = await this.sql<{ tx_id: string; tx_index: number }[]>`
SELECT tx_id, tx_index
FROM txs
WHERE index_block_hash = ${indexBlockHash} AND canonical = true AND microblock_canonical = true
`;
const txIds = result.sort(tx => tx.tx_index).map(tx => tx.tx_id);
return { results: txIds };
}
async getBlockTxsRows(blockHash: string): Promise<FoundOrNot<DbTx[]>> {
return await this.sqlTransaction(async sql => {
const blockQuery = await this.getBlockInternal(sql, { hash: blockHash });
if (!blockQuery.found) {
throw new Error(`Could not find block by hash ${blockHash}`);
}
const result = await sql<ContractTxQueryResult[]>`
SELECT ${sql(TX_COLUMNS)}, ${abiColumn(sql)}
FROM txs
WHERE index_block_hash = ${blockQuery.result.index_block_hash}
AND canonical = true AND microblock_canonical = true
ORDER BY microblock_sequence ASC, tx_index ASC
`;
if (result.length === 0) {
return { found: false } as const;
}
const parsed = result.map(r => parseTxQueryResult(r));
return { found: true, result: parsed };
});
}
async getMicroblock(args: {
microblockHash: string;
}): Promise<FoundOrNot<{ microblock: DbMicroblock; txs: string[] }>> {
return await this.sqlTransaction(async sql => {
const result = await sql<MicroblockQueryResult[]>`
SELECT ${sql(MICROBLOCK_COLUMNS)}
FROM microblocks
WHERE microblock_hash = ${args.microblockHash}
ORDER BY canonical DESC, microblock_canonical DESC
LIMIT 1
`;
if (result.length === 0) {
return { found: false } as const;
}
const txQuery = await sql<{ tx_id: string }[]>`
SELECT tx_id
FROM txs
WHERE microblock_hash = ${args.microblockHash} AND canonical = true AND microblock_canonical = true
ORDER BY tx_index DESC
`;
const microblock = parseMicroblockQueryResult(result[0]);
const txs = txQuery.map(row => row.tx_id);
return { found: true, result: { microblock, txs } };
});
}
async getMicroblocks(args: {
limit: number;
offset: number;
}): Promise<{ result: { microblock: DbMicroblock; txs: string[] }[]; total: number }> {
return await this.sqlTransaction(async sql => {
const countQuery = await sql<
{ total: number }[]
>`SELECT microblock_count AS total FROM chain_tip`;
const microblockQuery = await sql<
(MicroblockQueryResult & { tx_id?: string | null; tx_index?: number | null })[]
>`
SELECT microblocks.*, txs.tx_id
FROM microblocks LEFT JOIN txs USING(microblock_hash)
WHERE microblocks.canonical = true AND microblocks.microblock_canonical = true AND
txs.canonical = true AND txs.microblock_canonical = true
ORDER BY microblocks.block_height DESC, microblocks.microblock_sequence DESC, txs.tx_index DESC
LIMIT ${args.limit}
OFFSET ${args.offset};
`;
const microblocks: { microblock: DbMicroblock; txs: string[] }[] = [];
microblockQuery.forEach(row => {
const mb = parseMicroblockQueryResult(row);
let existing = microblocks.find(
item => item.microblock.microblock_hash === mb.microblock_hash
);
if (!existing) {
existing = { microblock: mb, txs: [] };
microblocks.push(existing);
}
if (row.tx_id) {
existing.txs.push(row.tx_id);
}
});
return {
result: microblocks,
total: countQuery[0].total,
};
});
}
async getUnanchoredTxsInternal(sql: PgSqlClient): Promise<{ txs: DbTx[] }> {
// Get transactions that have been streamed in microblocks but not yet accepted or rejected in an anchor block.
const { block_height } = await this.getChainTip(sql);
const unanchoredBlockHeight = block_height + 1;
const query = await sql<ContractTxQueryResult[]>`
SELECT ${sql(TX_COLUMNS)}, ${abiColumn(sql)}
FROM txs
WHERE canonical = true AND microblock_canonical = true AND block_height = ${unanchoredBlockHeight}
ORDER BY block_height DESC, microblock_sequence DESC, tx_index DESC
`;
const txs = query.map(row => parseTxQueryResult(row));
return { txs: txs };
}
async getUnanchoredTxs(): Promise<{ txs: DbTx[] }> {
return await this.sqlTransaction(async sql => {
return this.getUnanchoredTxsInternal(sql);
});
}
async getAddressNonceAtBlock(args: {
stxAddress: string;
blockIdentifier: BlockIdentifier;
}): Promise<FoundOrNot<{ lastExecutedTxNonce: number | null; possibleNextNonce: number }>> {
return await this.sqlTransaction(async sql => {
const dbBlock = await this.getBlockInternal(sql, args.blockIdentifier);
if (!dbBlock.found) {
return { found: false };
}
const nonceQuery = await sql<{ nonce: number | null }[]>`
SELECT MAX(nonce) nonce
FROM txs
WHERE ((sender_address = ${args.stxAddress} AND sponsored = false) OR (sponsor_address = ${args.stxAddress} AND sponsored = true))
AND canonical = true AND microblock_canonical = true
AND block_height <= ${dbBlock.result.block_height}
`;
let lastExecutedTxNonce: number | null = null;
let possibleNextNonce = 0;
if (nonceQuery.length > 0 && typeof nonceQuery[0].nonce === 'number') {
lastExecutedTxNonce = nonceQuery[0].nonce;
possibleNextNonce = lastExecutedTxNonce + 1;
} else {
possibleNextNonce = 0;
}
return { found: true, result: { lastExecutedTxNonce, possibleNextNonce } };
});
}
async getAddressNonces(args: { stxAddress: string }): Promise<{
lastExecutedTxNonce: number | null;
lastMempoolTxNonce: number | null;
possibleNextNonce: number;
detectedMissingNonces: number[];
detectedMempoolNonces: number[];
}> {
return await this.sqlTransaction(async sql => {
const executedTxNonce = await sql<{ nonce: number | null }[]>`
SELECT MAX(nonce) nonce
FROM txs
WHERE sender_address = ${args.stxAddress}
AND canonical = true AND microblock_canonical = true
`;
const executedTxSponsorNonce = await sql<{ nonce: number | null }[]>`
SELECT MAX(sponsor_nonce) nonce
FROM txs
WHERE sponsor_address = ${args.stxAddress} AND sponsored = true
AND canonical = true AND microblock_canonical = true
`;
const mempoolTxNonce = await sql<{ nonce: number | null }[]>`
SELECT MAX(nonce) nonce
FROM mempool_txs
WHERE sender_address = ${args.stxAddress}
AND pruned = false
`;
const mempoolTxSponsorNonce = await sql<{ nonce: number | null }[]>`
SELECT MAX(sponsor_nonce) nonce
FROM mempool_txs
WHERE sponsor_address = ${args.stxAddress} AND sponsored= true
AND pruned = false
`;
let lastExecutedTxNonce = executedTxNonce[0]?.nonce ?? null;
const lastExecutedTxSponsorNonce = executedTxSponsorNonce[0]?.nonce ?? null;
if (lastExecutedTxNonce != null || lastExecutedTxSponsorNonce != null) {
lastExecutedTxNonce = Math.max(lastExecutedTxNonce ?? 0, lastExecutedTxSponsorNonce ?? 0);
}
let lastMempoolTxNonce = mempoolTxNonce[0]?.nonce ?? null;
const lastMempoolTxSponsorNonce = mempoolTxSponsorNonce[0]?.nonce ?? null;
if (lastMempoolTxNonce != null || lastMempoolTxSponsorNonce != null) {
lastMempoolTxNonce = Math.max(lastMempoolTxNonce ?? 0, lastMempoolTxSponsorNonce ?? 0);
}
let possibleNextNonce = 0;
if (lastExecutedTxNonce !== null || lastMempoolTxNonce !== null) {
possibleNextNonce = Math.max(lastExecutedTxNonce ?? 0, lastMempoolTxNonce ?? 0) + 1;
}
const detectedMissingNonces: number[] = [];
let detectedMempoolNonces: number[] = [];
if (lastExecutedTxNonce !== null && lastMempoolTxNonce !== null) {
// There's a greater than one difference in the last mempool tx nonce and last executed tx nonce.
// Check if there are any expected intermediate nonces missing from from the mempool.
if (lastMempoolTxNonce - lastExecutedTxNonce > 1) {
const expectedNonces: number[] = [];
for (let i = lastMempoolTxNonce - 1; i > lastExecutedTxNonce; i--) {
expectedNonces.push(i);
}
const mempoolNonces = await sql<{ nonce: number }[]>`
SELECT nonce
FROM mempool_txs
WHERE sender_address = ${args.stxAddress}
AND nonce IN ${sql(expectedNonces)}
AND pruned = false
UNION
SELECT sponsor_nonce as nonce
FROM mempool_txs
WHERE sponsor_address = ${args.stxAddress}
AND sponsored = true
AND sponsor_nonce IN ${sql(expectedNonces)}
AND pruned = false
`;
detectedMempoolNonces = mempoolNonces.map(r => r.nonce);
expectedNonces.forEach(nonce => {
if (!detectedMempoolNonces.includes(nonce)) {
detectedMissingNonces.push(nonce);
}
});
}
}
return {
lastExecutedTxNonce: lastExecutedTxNonce,
lastMempoolTxNonce: lastMempoolTxNonce,
possibleNextNonce: possibleNextNonce,
detectedMissingNonces: detectedMissingNonces,
detectedMempoolNonces: detectedMempoolNonces,
};
});
}
async getNameCanonical(txId: string, indexBlockHash: string): Promise<FoundOrNot<boolean>> {
const queryResult = await this.sql<{ canonical: boolean }[]>`
SELECT canonical FROM names
WHERE tx_id = ${txId} AND index_block_hash = ${indexBlockHash}
`;
if (queryResult.length > 0) {
return {
found: true,
result: queryResult[0].canonical,
};
}
return { found: false } as const;
}
async getBurnchainRewardSlotHolders({
burnchainAddress,
limit,
offset,
}: {
burnchainAddress?: string;
limit: number;
offset: number;
}): Promise<{ total: number; slotHolders: DbRewardSlotHolder[] }> {
const queryResults = await this.sql<
{
burn_block_hash: string;
burn_block_height: number;
address: string;
slot_index: number;
count: number;
}[]
>`
SELECT
burn_block_hash, burn_block_height, address, slot_index, (COUNT(*) OVER())::INTEGER AS count
FROM reward_slot_holders
WHERE canonical = true
${burnchainAddress ? this.sql`AND address = ${burnchainAddress}` : this.sql``}
ORDER BY burn_block_height DESC, slot_index DESC
LIMIT ${limit}
OFFSET ${offset}
`;
const count = queryResults[0]?.count ?? 0;
const slotHolders = queryResults.map(r => {
const parsed: DbRewardSlotHolder = {
canonical: true,
burn_block_hash: r.burn_block_hash,
burn_block_height: r.burn_block_height,
address: r.address,
slot_index: r.slot_index,
};
return parsed;
});
return {
total: count,
slotHolders,
};
}
async getTxsFromBlock(
blockIdentifer: BlockIdentifier,
limit: number,
offset: number
): Promise<FoundOrNot<{ results: DbTx[]; total: number }>> {
return await this.sqlTransaction(async sql => {
const blockQuery = await this.getBlockInternal(sql, blockIdentifer);
if (!blockQuery.found) {
return { found: false };
}
const totalQuery = await sql<{ count: number }[]>`
SELECT COUNT(*)::integer
FROM txs
WHERE canonical = true AND microblock_canonical = true
AND index_block_hash = ${blockQuery.result.index_block_hash}
`;
const result = await sql<ContractTxQueryResult[]>`
SELECT ${sql(TX_COLUMNS)}, ${abiColumn(sql)}
FROM txs
WHERE canonical = true AND microblock_canonical = true
AND index_block_hash = ${blockQuery.result.index_block_hash}
ORDER BY microblock_sequence DESC, tx_index DESC
LIMIT ${limit}
OFFSET ${offset}
`;
const total = totalQuery.length > 0 ? totalQuery[0].count : 0;
const parsed = result.map(r => parseTxQueryResult(r));
return { found: true, result: { results: parsed, total } };
});
}
async getBurnchainRewards({
burnchainRecipient,
limit,
offset,
}: {
burnchainRecipient?: string;
limit: number;
offset: number;
}): Promise<DbBurnchainReward[]> {
const queryResults = await this.sql<
{
burn_block_hash: string;
burn_block_height: number;
burn_amount: string;
reward_recipient: string;
reward_amount: string;
reward_index: number;
}[]
>`
SELECT burn_block_hash, burn_block_height, burn_amount, reward_recipient, reward_amount, reward_index
FROM burnchain_rewards
WHERE canonical = true
${burnchainRecipient ? this.sql`AND reward_recipient = ${burnchainRecipient}` : this.sql``}
ORDER BY burn_block_height DESC, reward_index DESC
LIMIT ${limit}
OFFSET ${offset}
`;
return queryResults.map(r => {
const parsed: DbBurnchainReward = {
canonical: true,
burn_block_hash: r.burn_block_hash,
burn_block_height: r.burn_block_height,
burn_amount: BigInt(r.burn_amount),
reward_recipient: r.reward_recipient,
reward_amount: BigInt(r.reward_amount),
reward_index: r.reward_index,
};
return parsed;
});
}
async getMinersRewardsAtHeight({
blockHeight,
}: {
blockHeight: number;
}): Promise<DbMinerReward[]> {
const queryResults = await this.sql<
{
block_hash: string;
from_index_block_hash: string;
index_block_hash: string;
mature_block_height: number;
recipient: string;
miner_address: string | null;
coinbase_amount: number;
tx_fees_anchored: number;
tx_fees_streamed_confirmed: number;
tx_fees_streamed_produced: number;
}[]
>`
SELECT id, mature_block_height, recipient, miner_address, block_hash, index_block_hash, from_index_block_hash,
canonical, coinbase_amount, tx_fees_anchored, tx_fees_streamed_confirmed, tx_fees_streamed_produced
FROM miner_rewards
WHERE canonical = true AND mature_block_height = ${blockHeight}
ORDER BY id DESC
`;
return queryResults.map(r => {
const parsed: DbMinerReward = {
block_hash: r.block_hash,
from_index_block_hash: r.from_index_block_hash,
index_block_hash: r.index_block_hash,
canonical: true,
mature_block_height: r.mature_block_height,
recipient: r.recipient,
// If `miner_address` is null then it means pre-Stacks2.1 data, and the `recipient` can be accurately used
miner_address: r.miner_address ?? r.recipient,
coinbase_amount: BigInt(r.coinbase_amount),
tx_fees_anchored: BigInt(r.tx_fees_anchored),
tx_fees_streamed_confirmed: BigInt(r.tx_fees_streamed_confirmed),
tx_fees_streamed_produced: BigInt(r.tx_fees_streamed_produced),
};
return parsed;
});
}
async getBurnchainRewardsTotal(
burnchainRecipient: string
): Promise<{ reward_recipient: string; reward_amount: bigint }> {
const queryResults = await this.sql<{ amount: string }[]>`
SELECT sum(reward_amount) amount
FROM burnchain_rewards
WHERE canonical = true AND reward_recipient = ${burnchainRecipient}
`;
const resultAmount = BigInt(queryResults[0]?.amount ?? 0);
return { reward_recipient: burnchainRecipient, reward_amount: resultAmount };
}
private async parseMempoolTransactions(
result: MempoolTxQueryResult[],
sql: PgSqlClient,
includeUnanchored: boolean
) {
if (result.length === 0) {
return [];
}
const pruned = result.filter(memTx => memTx.pruned && !includeUnanchored);
if (pruned.length !== 0) {
const unanchoredBlockHeight = await this.getMaxBlockHeight(sql, {
includeUnanchored: true,
});
const notPrunedTxIds = pruned.map(tx => tx.tx_id);
const query = await sql<{ tx_id: string }[]>`
SELECT tx_id
FROM txs
WHERE canonical = true AND microblock_canonical = true
AND tx_id IN ${sql(notPrunedTxIds)}
AND block_height = ${unanchoredBlockHeight}
`;
// The tx is marked as pruned because it's in an unanchored microblock
query.forEach(tran => {
const transaction = result.find(tx => tx.tx_id === tran.tx_id);
if (transaction) {
transaction.pruned = false;
transaction.status = DbTxStatus.Pending;
}
});
}
return result.map(transaction => parseMempoolTxQueryResult(transaction));
}
async getMempoolTxs(args: {
txIds: string[];
includeUnanchored: boolean;
includePruned?: boolean;
}): Promise<DbMempoolTx[]> {
if (args.txIds.length === 0) {
return [];
}
return await this.sqlTransaction(async sql => {
const result = await sql<MempoolTxQueryResult[]>`
SELECT ${sql(MEMPOOL_TX_COLUMNS)}, ${abiColumn(sql, 'mempool_txs')}
FROM mempool_txs
WHERE tx_id IN ${sql(args.txIds)}
`;
return await this.parseMempoolTransactions(result, sql, args.includeUnanchored);
});
}
async getMempoolTx({
txId,
includePruned,
includeUnanchored,
}: {
txId: string;
includeUnanchored: boolean;
includePruned?: boolean;
}): Promise<FoundOrNot<DbMempoolTx>> {
return await this.sqlTransaction(async sql => {
const result = await sql<MempoolTxQueryResult[]>`
SELECT ${sql(MEMPOOL_TX_COLUMNS)}, ${abiColumn(sql, 'mempool_txs')}
FROM mempool_txs
WHERE tx_id = ${txId}
`;
// Treat the tx as "not pruned" if it's in an unconfirmed microblock and the caller is has not opted-in to unanchored data.