-
Notifications
You must be signed in to change notification settings - Fork 123
/
Copy pathpg-write-store.ts
3181 lines (3020 loc) · 123 KB
/
pg-write-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 { getOrAdd, batchIterate, I32_MAX, getIbdBlockHeight } from '../helpers';
import {
DbBlock,
DbTx,
DbStxEvent,
DbFtEvent,
DbNftEvent,
DbTxTypeId,
DbSmartContractEvent,
DbSmartContract,
DataStoreBlockUpdateData,
DbStxLockEvent,
DbMinerReward,
DbBurnchainReward,
DbTxStatus,
DbRewardSlotHolder,
DbBnsName,
DbBnsNamespace,
DbBnsSubdomain,
DbConfigState,
DbTokenOfferingLocked,
DataStoreMicroblockUpdateData,
DbMicroblock,
DataStoreTxEventData,
DbFaucetRequest,
MinerRewardInsertValues,
BlockInsertValues,
RewardSlotHolderInsertValues,
StxLockEventInsertValues,
StxEventInsertValues,
PrincipalStxTxsInsertValues,
BnsSubdomainInsertValues,
BnsZonefileInsertValues,
FtEventInsertValues,
NftEventInsertValues,
SmartContractEventInsertValues,
MicroblockQueryResult,
BurnchainRewardInsertValues,
TxInsertValues,
MempoolTxInsertValues,
MempoolTxQueryResult,
SmartContractInsertValues,
BnsNameInsertValues,
BnsNamespaceInsertValues,
FaucetRequestInsertValues,
MicroblockInsertValues,
TxQueryResult,
UpdatedEntities,
BlockQueryResult,
DataStoreAttachmentData,
DataStoreAttachmentSubdomainData,
DataStoreBnsBlockData,
PoxSyntheticEventInsertValues,
DbTxRaw,
DbMempoolTxRaw,
DbChainTip,
RawEventRequestInsertValues,
IndexesState,
NftCustodyInsertValues,
DbPoxSyntheticEvent,
PoxSyntheticEventTable,
} from './common';
import {
BLOCK_COLUMNS,
convertTxQueryResultToDbMempoolTx,
MEMPOOL_TX_COLUMNS,
MICROBLOCK_COLUMNS,
parseBlockQueryResult,
parseMempoolTxQueryResult,
parseMicroblockQueryResult,
parseTxQueryResult,
TX_COLUMNS,
TX_METADATA_TABLES,
validateZonefileHash,
} from './helpers';
import { PgNotifier } from './pg-notifier';
import { MIGRATIONS_DIR, PgStore } from './pg-store';
import * as zoneFileParser from 'zone-file';
import { parseResolver, parseZoneFileTxt } from '../event-stream/bns/bns-helpers';
import { SyntheticPoxEventName } from '../pox-helpers';
import { logger } from '../logger';
import {
PgJsonb,
PgSqlClient,
connectPostgres,
isProdEnv,
runMigrations,
} from '@hirosystems/api-toolkit';
import { PgServer, getConnectionArgs, getConnectionConfig } from './connection';
const MIGRATIONS_TABLE = 'pgmigrations';
class MicroblockGapError extends Error {
constructor(message: string) {
super(message);
this.message = message;
this.name = this.constructor.name;
}
}
/**
* Extends `PgStore` to provide data insertion functions. These added features are usually called by
* the `EventServer` upon receiving blockchain events from a Stacks node. It also deals with chain data
* re-orgs and Postgres NOTIFY message broadcasts when important data is written into the DB.
*/
export class PgWriteStore extends PgStore {
readonly isEventReplay: boolean;
protected isIbdBlockHeightReached = false;
constructor(
sql: PgSqlClient,
notifier: PgNotifier | undefined = undefined,
isEventReplay: boolean = false
) {
super(sql, notifier);
this.isEventReplay = isEventReplay;
}
static async connect({
usageName,
skipMigrations = false,
withNotifier = true,
isEventReplay = false,
}: {
usageName: string;
skipMigrations?: boolean;
withNotifier?: boolean;
isEventReplay?: boolean;
}): Promise<PgWriteStore> {
const sql = await connectPostgres({
usageName: usageName,
connectionArgs: getConnectionArgs(PgServer.primary),
connectionConfig: getConnectionConfig(PgServer.primary),
});
if (!skipMigrations) {
await runMigrations(MIGRATIONS_DIR, 'up', getConnectionArgs(PgServer.primary));
}
const notifier = withNotifier ? await PgNotifier.create(usageName) : undefined;
const store = new PgWriteStore(sql, notifier, isEventReplay);
await store.connectPgNotifier();
return store;
}
async storeRawEventRequest(eventPath: string, payload: PgJsonb): Promise<void> {
// To avoid depending on the DB more than once and to allow the query transaction to settle,
// we'll take the complete insert result and move that to the output TSV file instead of taking
// only the `id` and performing a `COPY` of that row later.
const insertResult = await this.sql<
{
id: string;
receive_timestamp: string;
event_path: string;
payload: string;
}[]
>`INSERT INTO event_observer_requests(
event_path, payload
) values(${eventPath}, ${payload})
RETURNING id, receive_timestamp::text, event_path, payload::text
`;
if (insertResult.length !== 1) {
throw new Error(
`Unexpected row count ${insertResult.length} when storing event_observer_requests entry`
);
}
}
async update(data: DataStoreBlockUpdateData): Promise<void> {
let garbageCollectedMempoolTxs: string[] = [];
let batchedTxData: DataStoreTxEventData[] = [];
const deployedSmartContracts: DbSmartContract[] = [];
const contractLogEvents: DbSmartContractEvent[] = [];
await this.sqlWriteTransaction(async sql => {
const chainTip = await this.getChainTip();
await this.handleReorg(sql, data.block, chainTip.block_height);
// If the incoming block is not of greater height than current chain tip, then store data as non-canonical.
const isCanonical = data.block.block_height > chainTip.block_height;
if (!isCanonical) {
data.block = { ...data.block, canonical: false };
data.microblocks = data.microblocks.map(mb => ({ ...mb, canonical: false }));
data.txs = data.txs.map(tx => ({
tx: { ...tx.tx, canonical: false },
stxLockEvents: tx.stxLockEvents.map(e => ({ ...e, canonical: false })),
stxEvents: tx.stxEvents.map(e => ({ ...e, canonical: false })),
ftEvents: tx.ftEvents.map(e => ({ ...e, canonical: false })),
nftEvents: tx.nftEvents.map(e => ({ ...e, canonical: false })),
contractLogEvents: tx.contractLogEvents.map(e => ({ ...e, canonical: false })),
smartContracts: tx.smartContracts.map(e => ({ ...e, canonical: false })),
names: tx.names.map(e => ({ ...e, canonical: false })),
namespaces: tx.namespaces.map(e => ({ ...e, canonical: false })),
pox2Events: tx.pox2Events.map(e => ({ ...e, canonical: false })),
pox3Events: tx.pox3Events.map(e => ({ ...e, canonical: false })),
pox4Events: tx.pox4Events.map(e => ({ ...e, canonical: false })),
}));
data.minerRewards = data.minerRewards.map(mr => ({ ...mr, canonical: false }));
} else {
// When storing newly mined canonical txs, remove them from the mempool table.
const candidateTxIds = data.txs.map(d => d.tx.tx_id);
const removedTxsResult = await this.pruneMempoolTxs(sql, candidateTxIds);
if (removedTxsResult.removedTxs.length > 0) {
logger.debug(
`Removed ${removedTxsResult.removedTxs.length} txs from mempool table during new block ingestion`
);
}
}
//calculate total execution cost of the block
const totalCost = data.txs.reduce(
(previousValue, currentValue) => {
const {
execution_cost_read_count,
execution_cost_read_length,
execution_cost_runtime,
execution_cost_write_count,
execution_cost_write_length,
} = previousValue;
return {
execution_cost_read_count:
execution_cost_read_count + currentValue.tx.execution_cost_read_count,
execution_cost_read_length:
execution_cost_read_length + currentValue.tx.execution_cost_read_length,
execution_cost_runtime: execution_cost_runtime + currentValue.tx.execution_cost_runtime,
execution_cost_write_count:
execution_cost_write_count + currentValue.tx.execution_cost_write_count,
execution_cost_write_length:
execution_cost_write_length + currentValue.tx.execution_cost_write_length,
};
},
{
execution_cost_read_count: 0,
execution_cost_read_length: 0,
execution_cost_runtime: 0,
execution_cost_write_count: 0,
execution_cost_write_length: 0,
}
);
data.block.execution_cost_read_count = totalCost.execution_cost_read_count;
data.block.execution_cost_read_length = totalCost.execution_cost_read_length;
data.block.execution_cost_runtime = totalCost.execution_cost_runtime;
data.block.execution_cost_write_count = totalCost.execution_cost_write_count;
data.block.execution_cost_write_length = totalCost.execution_cost_write_length;
batchedTxData = data.txs;
// Find microblocks that weren't already inserted via the unconfirmed microblock event.
// This happens when a stacks-node is syncing and receives confirmed microblocks with their anchor block at the same time.
if (data.microblocks.length > 0) {
const existingMicroblocksQuery = await sql<{ microblock_hash: string }[]>`
SELECT microblock_hash
FROM microblocks
WHERE parent_index_block_hash = ${data.block.parent_index_block_hash}
AND microblock_hash IN ${sql(data.microblocks.map(mb => mb.microblock_hash))}
`;
const existingMicroblockHashes = new Set(
existingMicroblocksQuery.map(r => r.microblock_hash)
);
const missingMicroblocks = data.microblocks.filter(
mb => !existingMicroblockHashes.has(mb.microblock_hash)
);
if (missingMicroblocks.length > 0) {
const missingMicroblockHashes = new Set(missingMicroblocks.map(mb => mb.microblock_hash));
const missingTxs = data.txs.filter(entry =>
missingMicroblockHashes.has(entry.tx.microblock_hash)
);
await this.insertMicroblockData(sql, missingMicroblocks, missingTxs);
// Clear already inserted microblock txs from the anchor-block update data to avoid duplicate inserts.
batchedTxData = batchedTxData.filter(entry => {
return !missingMicroblockHashes.has(entry.tx.microblock_hash);
});
}
}
// When processing an immediately-non-canonical block, do not orphan and possible existing microblocks
// which may be still considered canonical by the canonical block at this height.
if (isCanonical) {
const { acceptedMicroblockTxs, orphanedMicroblockTxs } = await this.updateMicroCanonical(
sql,
{
isCanonical: isCanonical,
blockHeight: data.block.block_height,
blockHash: data.block.block_hash,
indexBlockHash: data.block.index_block_hash,
parentIndexBlockHash: data.block.parent_index_block_hash,
parentMicroblockHash: data.block.parent_microblock_hash,
parentMicroblockSequence: data.block.parent_microblock_sequence,
burnBlockTime: data.block.burn_block_time,
}
);
// Identify any micro-orphaned txs that also didn't make it into this anchor block, and restore them into the mempool
const orphanedAndMissingTxs = orphanedMicroblockTxs.filter(
tx => !data.txs.find(r => tx.tx_id === r.tx.tx_id)
);
const restoredMempoolTxs = await this.restoreMempoolTxs(
sql,
orphanedAndMissingTxs.map(tx => tx.tx_id)
);
restoredMempoolTxs.restoredTxs.forEach(txId => {
logger.info(`Restored micro-orphaned tx to mempool ${txId}`);
});
// Clear accepted microblock txs from the anchor-block update data to avoid duplicate inserts.
batchedTxData = batchedTxData.filter(entry => {
const matchingTx = acceptedMicroblockTxs.find(tx => tx.tx_id === entry.tx.tx_id);
return !matchingTx;
});
}
if (isCanonical && data.pox_v1_unlock_height !== undefined) {
// update the pox_state.pox_v1_unlock_height singleton
await sql`
UPDATE pox_state
SET pox_v1_unlock_height = ${data.pox_v1_unlock_height}
WHERE pox_v1_unlock_height != ${data.pox_v1_unlock_height}
`;
}
if (isCanonical && data.pox_v2_unlock_height !== undefined) {
// update the pox_state.pox_v2_unlock_height singleton
await sql`
UPDATE pox_state
SET pox_v2_unlock_height = ${data.pox_v2_unlock_height}
WHERE pox_v2_unlock_height != ${data.pox_v2_unlock_height}
`;
}
if (isCanonical && data.pox_v3_unlock_height !== undefined) {
// update the pox_state.pox_v3_unlock_height singleton
await sql`
UPDATE pox_state
SET pox_v3_unlock_height = ${data.pox_v3_unlock_height}
WHERE pox_v3_unlock_height != ${data.pox_v3_unlock_height}
`;
}
// When receiving first block, check if "block 0" boot data was received,
// if so, update their properties to correspond to "block 1", since we treat
// the "block 0" concept as an internal implementation detail.
if (data.block.block_height === 1) {
const blockZero = await this.getBlockInternal(sql, { height: 0 });
if (blockZero.found) {
await this.fixBlockZeroData(sql, data.block);
}
}
// TODO(mb): sanity tests on tx_index on batchedTxData, re-normalize if necessary
// TODO(mb): copy the batchedTxData to outside the sql transaction fn so they can be emitted in txUpdate event below
const blocksUpdated = await this.updateBlock(sql, data.block);
if (blocksUpdated !== 0) {
for (const minerRewards of data.minerRewards) {
await this.updateMinerReward(sql, minerRewards);
}
for (const entry of batchedTxData) {
await this.updateTx(sql, entry.tx);
await this.updateBatchStxEvents(sql, entry.tx, entry.stxEvents);
await this.updatePrincipalStxTxs(sql, entry.tx, entry.stxEvents);
contractLogEvents.push(...entry.contractLogEvents);
await this.updateBatchSmartContractEvent(sql, entry.tx, entry.contractLogEvents);
for (const pox2Event of entry.pox2Events) {
await this.updatePoxSyntheticEvent(sql, entry.tx, 'pox2_events', pox2Event);
}
for (const pox3Event of entry.pox3Events) {
await this.updatePoxSyntheticEvent(sql, entry.tx, 'pox3_events', pox3Event);
}
for (const pox4Event of entry.pox4Events) {
await this.updatePoxSyntheticEvent(sql, entry.tx, 'pox4_events', pox4Event);
}
for (const stxLockEvent of entry.stxLockEvents) {
await this.updateStxLockEvent(sql, entry.tx, stxLockEvent);
}
for (const ftEvent of entry.ftEvents) {
await this.updateFtEvent(sql, entry.tx, ftEvent);
}
for (const nftEvent of entry.nftEvents) {
await this.updateNftEvent(sql, entry.tx, nftEvent, false);
}
deployedSmartContracts.push(...entry.smartContracts);
for (const smartContract of entry.smartContracts) {
await this.updateSmartContract(sql, entry.tx, smartContract);
}
for (const namespace of entry.namespaces) {
await this.updateNamespaces(sql, entry.tx, namespace);
}
for (const bnsName of entry.names) {
await this.updateNames(sql, entry.tx, bnsName);
}
}
const mempoolGarbageResults = await this.deleteGarbageCollectedMempoolTxs(sql);
if (mempoolGarbageResults.deletedTxs.length > 0) {
logger.debug(`Garbage collected ${mempoolGarbageResults.deletedTxs.length} mempool txs`);
}
garbageCollectedMempoolTxs = mempoolGarbageResults.deletedTxs;
}
if (!this.isEventReplay) {
await this.reconcileMempoolStatus(sql);
const mempoolStats = await this.getMempoolStatsInternal({ sql });
this.eventEmitter.emit('mempoolStatsUpdate', mempoolStats);
}
if (isCanonical)
await sql`
WITH new_tx_count AS (
SELECT tx_count + ${data.txs.length} AS tx_count FROM chain_tip
)
UPDATE chain_tip SET
block_height = ${data.block.block_height},
block_hash = ${data.block.block_hash},
index_block_hash = ${data.block.index_block_hash},
burn_block_height = ${data.block.burn_block_height},
microblock_hash = NULL,
microblock_sequence = NULL,
block_count = ${data.block.block_height},
tx_count = (SELECT tx_count FROM new_tx_count),
tx_count_unanchored = (SELECT tx_count FROM new_tx_count)
`;
});
// Do we have an IBD height defined in ENV? If so, check if this block update reached it.
const ibdHeight = getIbdBlockHeight();
this.isIbdBlockHeightReached = ibdHeight ? data.block.block_height > ibdHeight : true;
await this.refreshMaterializedView('mempool_digest');
// Skip sending `PgNotifier` updates altogether if we're in the genesis block since this block is the
// event replay of the v1 blockchain.
if ((data.block.block_height > 1 || !isProdEnv) && this.notifier) {
await this.notifier.sendBlock({ blockHash: data.block.block_hash });
for (const tx of data.txs) {
await this.notifier.sendTx({ txId: tx.tx.tx_id });
}
for (const txId of garbageCollectedMempoolTxs) {
await this.notifier.sendTx({ txId: txId });
}
for (const smartContract of deployedSmartContracts) {
await this.notifier.sendSmartContract({
contractId: smartContract.contract_id,
});
}
for (const logEvent of contractLogEvents) {
await this.notifier.sendSmartContractLog({
txId: logEvent.tx_id,
eventIndex: logEvent.event_index,
});
}
await this.emitAddressTxUpdates(data.txs);
for (const nftEvent of data.txs.map(tx => tx.nftEvents).flat()) {
await this.notifier.sendNftEvent({
txId: nftEvent.tx_id,
eventIndex: nftEvent.event_index,
});
}
}
}
async updateMinerReward(sql: PgSqlClient, minerReward: DbMinerReward): Promise<number> {
const values: MinerRewardInsertValues = {
block_hash: minerReward.block_hash,
index_block_hash: minerReward.index_block_hash,
from_index_block_hash: minerReward.from_index_block_hash,
mature_block_height: minerReward.mature_block_height,
canonical: minerReward.canonical,
recipient: minerReward.recipient,
// If `miner_address` is null then it means pre-Stacks2.1 data, and the `recipient` can be accurately used
miner_address: minerReward.miner_address ?? minerReward.recipient,
coinbase_amount: minerReward.coinbase_amount.toString(),
tx_fees_anchored: minerReward.tx_fees_anchored.toString(),
tx_fees_streamed_confirmed: minerReward.tx_fees_streamed_confirmed.toString(),
tx_fees_streamed_produced: minerReward.tx_fees_streamed_produced.toString(),
};
const result = await sql`
INSERT INTO miner_rewards ${sql(values)}
`;
return result.count;
}
async updateBlock(sql: PgSqlClient, block: DbBlock): Promise<number> {
const values: BlockInsertValues = {
block_hash: block.block_hash,
index_block_hash: block.index_block_hash,
parent_index_block_hash: block.parent_index_block_hash,
parent_block_hash: block.parent_block_hash,
parent_microblock_hash: block.parent_microblock_hash,
parent_microblock_sequence: block.parent_microblock_sequence,
block_height: block.block_height,
burn_block_time: block.burn_block_time,
burn_block_hash: block.burn_block_hash,
burn_block_height: block.burn_block_height,
miner_txid: block.miner_txid,
canonical: block.canonical,
execution_cost_read_count: block.execution_cost_read_count,
execution_cost_read_length: block.execution_cost_read_length,
execution_cost_runtime: block.execution_cost_runtime,
execution_cost_write_count: block.execution_cost_write_count,
execution_cost_write_length: block.execution_cost_write_length,
};
const result = await sql`
INSERT INTO blocks ${sql(values)}
ON CONFLICT (index_block_hash) DO NOTHING
`;
return result.count;
}
async insertStxEventBatch(sql: PgSqlClient, stxEvents: StxEventInsertValues[]) {
const values = stxEvents.map(s => {
const value: StxEventInsertValues = {
event_index: s.event_index,
tx_id: s.tx_id,
tx_index: s.tx_index,
block_height: s.block_height,
index_block_hash: s.index_block_hash,
parent_index_block_hash: s.parent_index_block_hash,
microblock_hash: s.microblock_hash,
microblock_sequence: s.microblock_sequence,
microblock_canonical: s.microblock_canonical,
canonical: s.canonical,
asset_event_type_id: s.asset_event_type_id,
sender: s.sender,
recipient: s.recipient,
amount: s.amount,
memo: s.memo ?? null,
};
return value;
});
await sql`
INSERT INTO stx_events ${sql(values)}
`;
}
async updateBurnchainRewardSlotHolders({
burnchainBlockHash,
burnchainBlockHeight,
slotHolders,
}: {
burnchainBlockHash: string;
burnchainBlockHeight: number;
slotHolders: DbRewardSlotHolder[];
}): Promise<void> {
await this.sqlWriteTransaction(async sql => {
const existingSlotHolders = await sql<{ address: string }[]>`
UPDATE reward_slot_holders
SET canonical = false
WHERE canonical = true
AND (burn_block_hash = ${burnchainBlockHash}
OR burn_block_height >= ${burnchainBlockHeight})
`;
if (existingSlotHolders.count > 0) {
logger.warn(
`Invalidated ${existingSlotHolders.count} burnchain reward slot holders after fork detected at burnchain block ${burnchainBlockHash}`
);
}
if (slotHolders.length === 0) {
return;
}
const values: RewardSlotHolderInsertValues[] = slotHolders.map(val => ({
canonical: val.canonical,
burn_block_hash: val.burn_block_hash,
burn_block_height: val.burn_block_height,
address: val.address,
slot_index: val.slot_index,
}));
const result = await sql`
INSERT INTO reward_slot_holders ${sql(values)}
`;
if (result.count !== slotHolders.length) {
throw new Error(
`Unexpected row count after inserting reward slot holders: ${result.count} vs ${slotHolders.length}`
);
}
});
}
async updateMicroblocks(data: DataStoreMicroblockUpdateData): Promise<void> {
try {
await this.updateMicroblocksInternal(data);
} catch (error) {
if (error instanceof MicroblockGapError) {
// Log and ignore this error for now, see https://github.com/blockstack/stacks-blockchain/issues/2850
// for more details.
// In theory it would be possible for the API to cache out-of-order microblock data and use it to
// restore data in this condition, but it would require several changes to sensitive re-org code,
// as well as introduce a new kind of statefulness and responsibility to the API.
logger.warn(error.message);
} else {
throw error;
}
}
}
async updateMicroblocksInternal(data: DataStoreMicroblockUpdateData): Promise<void> {
const txData: DataStoreTxEventData[] = [];
let dbMicroblocks: DbMicroblock[] = [];
const deployedSmartContracts: DbSmartContract[] = [];
const contractLogEvents: DbSmartContractEvent[] = [];
await this.sqlWriteTransaction(async sql => {
// Sanity check: ensure incoming microblocks have a `parent_index_block_hash` that matches the
// API's current known canonical chain tip. We assume this holds true so incoming microblock
// data is always treated as being built off the current canonical anchor block.
const chainTip = await this.getChainTip();
const nonCanonicalMicroblock = data.microblocks.find(
mb => mb.parent_index_block_hash !== chainTip.index_block_hash
);
// Note: the stacks-node event emitter can send old microblocks that have already been processed by a previous anchor block.
// Log warning and return, nothing to do.
if (nonCanonicalMicroblock) {
logger.info(
`Failure in microblock ingestion, microblock ${nonCanonicalMicroblock.microblock_hash} ` +
`points to parent index block hash ${nonCanonicalMicroblock.parent_index_block_hash} rather ` +
`than the current canonical tip's index block hash ${chainTip.index_block_hash}.`
);
return;
}
// The block height is just one after the current chain tip height
const blockHeight = chainTip.block_height + 1;
dbMicroblocks = data.microblocks.map(mb => {
const dbMicroBlock: DbMicroblock = {
canonical: true,
microblock_canonical: true,
microblock_hash: mb.microblock_hash,
microblock_sequence: mb.microblock_sequence,
microblock_parent_hash: mb.microblock_parent_hash,
parent_index_block_hash: mb.parent_index_block_hash,
parent_burn_block_height: mb.parent_burn_block_height,
parent_burn_block_hash: mb.parent_burn_block_hash,
parent_burn_block_time: mb.parent_burn_block_time,
block_height: blockHeight,
parent_block_height: chainTip.block_height,
parent_block_hash: chainTip.block_hash,
index_block_hash: '', // Empty until microblock is confirmed in an anchor block
block_hash: '', // Empty until microblock is confirmed in an anchor block
};
return dbMicroBlock;
});
for (const entry of data.txs) {
// Note: the properties block_hash and burn_block_time are empty here because the anchor
// block with that data doesn't yet exist.
const dbTx: DbTxRaw = {
...entry.tx,
parent_block_hash: chainTip.block_hash,
block_height: blockHeight,
};
// Set all the `block_height` properties for the related tx objects, since it wasn't known
// when creating the objects using only the stacks-node message payload.
txData.push({
tx: dbTx,
stxEvents: entry.stxEvents.map(e => ({ ...e, block_height: blockHeight })),
contractLogEvents: entry.contractLogEvents.map(e => ({
...e,
block_height: blockHeight,
})),
stxLockEvents: entry.stxLockEvents.map(e => ({ ...e, block_height: blockHeight })),
ftEvents: entry.ftEvents.map(e => ({ ...e, block_height: blockHeight })),
nftEvents: entry.nftEvents.map(e => ({ ...e, block_height: blockHeight })),
smartContracts: entry.smartContracts.map(e => ({ ...e, block_height: blockHeight })),
names: entry.names.map(e => ({ ...e, registered_at: blockHeight })),
namespaces: entry.namespaces.map(e => ({ ...e, ready_block: blockHeight })),
pox2Events: entry.pox2Events.map(e => ({ ...e, block_height: blockHeight })),
pox3Events: entry.pox3Events.map(e => ({ ...e, block_height: blockHeight })),
pox4Events: entry.pox4Events.map(e => ({ ...e, block_height: blockHeight })),
});
deployedSmartContracts.push(...entry.smartContracts);
contractLogEvents.push(...entry.contractLogEvents);
}
await this.insertMicroblockData(sql, dbMicroblocks, txData);
// Find any microblocks that have been orphaned by this latest microblock chain tip.
// This function also checks that each microblock parent hash points to an existing microblock in the db.
const currentMicroblockTip = dbMicroblocks[dbMicroblocks.length - 1];
const unanchoredMicroblocksAtTip = await this.findUnanchoredMicroblocksAtChainTip(
sql,
currentMicroblockTip.parent_index_block_hash,
blockHeight,
currentMicroblockTip
);
if ('microblockGap' in unanchoredMicroblocksAtTip) {
// Throw in order to trigger a SQL tx rollback to undo and db writes so far, but catch, log, and ignore this specific error.
throw new MicroblockGapError(
`Gap in parent microblock stream for ${currentMicroblockTip.microblock_hash}, missing microblock ${unanchoredMicroblocksAtTip.missingMicroblockHash}, the oldest microblock ${unanchoredMicroblocksAtTip.oldestParentMicroblockHash} found in the chain has sequence ${unanchoredMicroblocksAtTip.oldestParentMicroblockSequence} rather than 0`
);
}
const { orphanedMicroblocks } = unanchoredMicroblocksAtTip;
if (orphanedMicroblocks.length > 0) {
// Handle microblocks reorgs here, these _should_ only be micro-forks off the same same
// unanchored chain tip, e.g. a leader orphaning it's own unconfirmed microblocks
const microOrphanResult = await this.handleMicroReorg(sql, {
isCanonical: true,
isMicroCanonical: false,
indexBlockHash: '',
blockHash: '',
burnBlockTime: -1,
microblocks: orphanedMicroblocks,
});
const microOrphanedTxs = microOrphanResult.updatedTxs;
// Restore any micro-orphaned txs into the mempool
const restoredMempoolTxs = await this.restoreMempoolTxs(
sql,
microOrphanedTxs.map(tx => tx.tx_id)
);
restoredMempoolTxs.restoredTxs.forEach(txId => {
logger.info(`Restored micro-orphaned tx to mempool ${txId}`);
});
}
const candidateTxIds = data.txs.map(d => d.tx.tx_id);
const removedTxsResult = await this.pruneMempoolTxs(sql, candidateTxIds);
if (removedTxsResult.removedTxs.length > 0) {
logger.debug(
`Removed ${removedTxsResult.removedTxs.length} microblock-txs from mempool table during microblock ingestion`
);
}
if (!this.isEventReplay) {
await this.reconcileMempoolStatus(sql);
const mempoolStats = await this.getMempoolStatsInternal({ sql });
this.eventEmitter.emit('mempoolStatsUpdate', mempoolStats);
}
if (currentMicroblockTip.microblock_canonical)
await sql`
UPDATE chain_tip SET
microblock_hash = ${currentMicroblockTip.microblock_hash},
microblock_sequence = ${currentMicroblockTip.microblock_sequence},
microblock_count = microblock_count + ${data.microblocks.length},
tx_count_unanchored = ${
currentMicroblockTip.microblock_sequence === 0
? sql`tx_count + ${data.txs.length}`
: sql`tx_count_unanchored + ${data.txs.length}`
}
`;
});
await this.refreshMaterializedView('mempool_digest');
if (this.notifier) {
for (const microblock of dbMicroblocks) {
await this.notifier.sendMicroblock({ microblockHash: microblock.microblock_hash });
}
for (const tx of txData) {
await this.notifier.sendTx({ txId: tx.tx.tx_id });
}
for (const smartContract of deployedSmartContracts) {
await this.notifier.sendSmartContract({
contractId: smartContract.contract_id,
});
}
for (const logEvent of contractLogEvents) {
await this.notifier.sendSmartContractLog({
txId: logEvent.tx_id,
eventIndex: logEvent.event_index,
});
}
await this.emitAddressTxUpdates(txData);
}
}
// Find any transactions that are erroneously still marked as both `pending` in the mempool table
// and also confirmed in the mined txs table. Mark these as pruned in the mempool and log warning.
// This must be called _after_ any writes to txs/mempool tables during block and microblock ingestion,
// but _before_ any reads or view refreshes that depend on the mempool table.
// NOTE: this is essentially a work-around for whatever bug is causing the underlying problem.
async reconcileMempoolStatus(sql: PgSqlClient): Promise<void> {
const txsResult = await sql<{ tx_id: string }[]>`
UPDATE mempool_txs
SET pruned = true
FROM txs
WHERE
mempool_txs.tx_id = txs.tx_id AND
mempool_txs.pruned = false AND
txs.canonical = true AND
txs.microblock_canonical = true AND
txs.status IN ${sql([
DbTxStatus.Success,
DbTxStatus.AbortByResponse,
DbTxStatus.AbortByPostCondition,
])}
RETURNING mempool_txs.tx_id
`;
if (txsResult.length > 0) {
const txs = txsResult.map(tx => tx.tx_id);
logger.warn(`Reconciled mempool txs as pruned for ${txsResult.length} txs`, { txs });
}
}
async fixBlockZeroData(sql: PgSqlClient, blockOne: DbBlock): Promise<void> {
const tablesUpdates: Record<string, number> = {};
const txsResult = await sql<TxQueryResult[]>`
UPDATE txs
SET
canonical = true,
block_height = 1,
tx_index = tx_index + 1,
block_hash = ${blockOne.block_hash},
index_block_hash = ${blockOne.index_block_hash},
burn_block_time = ${blockOne.burn_block_time},
parent_block_hash = ${blockOne.parent_block_hash}
WHERE block_height = 0
`;
tablesUpdates['txs'] = txsResult.count;
for (const table of TX_METADATA_TABLES) {
// a couple tables have a different name for the 'block_height' column
const heightCol =
table === 'names'
? sql('registered_at')
: table === 'namespaces'
? sql('ready_block')
: sql('block_height');
// The smart_contracts table does not have a tx_index column
const txIndexBump = table === 'smart_contracts' ? sql`` : sql`tx_index = tx_index + 1,`;
const metadataResult = await sql`
UPDATE ${sql(table)}
SET
canonical = true,
${heightCol} = 1,
${txIndexBump}
index_block_hash = ${blockOne.index_block_hash}
WHERE ${heightCol} = 0
`;
tablesUpdates[table] = metadataResult.count;
}
logger.info('Updated block zero boot data', tablesUpdates);
}
async updatePoxSyntheticEvent(
sql: PgSqlClient,
tx: DbTx,
poxTable: PoxSyntheticEventTable,
event: DbPoxSyntheticEvent
) {
const values: PoxSyntheticEventInsertValues = {
event_index: event.event_index,
tx_id: event.tx_id,
tx_index: event.tx_index,
block_height: event.block_height,
index_block_hash: tx.index_block_hash,
parent_index_block_hash: tx.parent_index_block_hash,
microblock_hash: tx.microblock_hash,
microblock_sequence: tx.microblock_sequence,
microblock_canonical: tx.microblock_canonical,
canonical: event.canonical,
stacker: event.stacker,
locked: event.locked.toString(),
balance: event.balance.toString(),
burnchain_unlock_height: event.burnchain_unlock_height.toString(),
name: event.name,
pox_addr: event.pox_addr,
pox_addr_raw: event.pox_addr_raw,
first_cycle_locked: null,
first_unlocked_cycle: null,
delegate_to: null,
lock_period: null,
lock_amount: null,
start_burn_height: null,
unlock_burn_height: null,
delegator: null,
increase_by: null,
total_locked: null,
extend_count: null,
reward_cycle: null,
amount_ustx: null,
};
// Set event-specific columns
switch (event.name) {
case SyntheticPoxEventName.HandleUnlock: {
values.first_cycle_locked = event.data.first_cycle_locked.toString();
values.first_unlocked_cycle = event.data.first_unlocked_cycle.toString();
break;
}
case SyntheticPoxEventName.StackStx: {
values.lock_period = event.data.lock_period.toString();
values.lock_amount = event.data.lock_amount.toString();
values.start_burn_height = event.data.start_burn_height.toString();
values.unlock_burn_height = event.data.unlock_burn_height.toString();
break;
}
case SyntheticPoxEventName.StackIncrease: {
values.increase_by = event.data.increase_by.toString();
values.total_locked = event.data.total_locked.toString();
break;
}
case SyntheticPoxEventName.StackExtend: {
values.extend_count = event.data.extend_count.toString();
values.unlock_burn_height = event.data.unlock_burn_height.toString();
break;
}
case SyntheticPoxEventName.DelegateStx: {
values.amount_ustx = event.data.amount_ustx.toString();
values.delegate_to = event.data.delegate_to;
values.unlock_burn_height = event.data.unlock_burn_height?.toString() ?? null;
break;
}
case SyntheticPoxEventName.DelegateStackStx: {
values.lock_period = event.data.lock_period.toString();
values.lock_amount = event.data.lock_amount.toString();
values.start_burn_height = event.data.start_burn_height.toString();
values.unlock_burn_height = event.data.unlock_burn_height.toString();
values.delegator = event.data.delegator;
break;
}
case SyntheticPoxEventName.DelegateStackIncrease: {
values.increase_by = event.data.increase_by.toString();
values.total_locked = event.data.total_locked.toString();
values.delegator = event.data.delegator;
break;
}
case SyntheticPoxEventName.DelegateStackExtend: {
values.extend_count = event.data.extend_count.toString();
values.unlock_burn_height = event.data.unlock_burn_height.toString();
values.delegator = event.data.delegator;
break;
}
case SyntheticPoxEventName.StackAggregationCommit: {
values.reward_cycle = event.data.reward_cycle.toString();
values.amount_ustx = event.data.amount_ustx.toString();
break;
}
case SyntheticPoxEventName.StackAggregationCommitIndexed: {
values.reward_cycle = event.data.reward_cycle.toString();
values.amount_ustx = event.data.amount_ustx.toString();
break;
}
case SyntheticPoxEventName.StackAggregationIncrease: {
values.reward_cycle = event.data.reward_cycle.toString();
values.amount_ustx = event.data.amount_ustx.toString();
break;
}
case SyntheticPoxEventName.RevokeDelegateStx: {
values.amount_ustx = event.data.amount_ustx.toString();
values.delegate_to = event.data.delegate_to;
break;
}
default: {
throw new Error(
`Unexpected Pox synthetic event name: ${(event as DbPoxSyntheticEvent).name}`
);
}
}
await sql`
INSERT INTO ${sql(poxTable)} ${sql(values)}
`;
}
async updateStxLockEvent(sql: PgSqlClient, tx: DbTx, event: DbStxLockEvent) {
const values: StxLockEventInsertValues = {
event_index: event.event_index,
tx_id: event.tx_id,
tx_index: event.tx_index,
block_height: event.block_height,
index_block_hash: tx.index_block_hash,
parent_index_block_hash: tx.parent_index_block_hash,
microblock_hash: tx.microblock_hash,
microblock_sequence: tx.microblock_sequence,
microblock_canonical: tx.microblock_canonical,
canonical: event.canonical,
locked_amount: event.locked_amount.toString(),
unlock_height: event.unlock_height,
locked_address: event.locked_address,
contract_name: event.contract_name,
};
await sql`
INSERT INTO stx_lock_events ${sql(values)}
`;
}
async updateBatchStxEvents(sql: PgSqlClient, tx: DbTx, events: DbStxEvent[]) {
const batchSize = 500; // (matt) benchmark: 21283 per second (15 seconds)
for (const eventBatch of batchIterate(events, batchSize)) {
const values: StxEventInsertValues[] = eventBatch.map(event => ({
event_index: event.event_index,
tx_id: event.tx_id,
tx_index: event.tx_index,
block_height: event.block_height,
index_block_hash: tx.index_block_hash,
parent_index_block_hash: tx.parent_index_block_hash,
microblock_hash: tx.microblock_hash,
microblock_sequence: tx.microblock_sequence,
microblock_canonical: tx.microblock_canonical,
canonical: event.canonical,
asset_event_type_id: event.asset_event_type_id,
sender: event.sender ?? null,
recipient: event.recipient ?? null,
amount: event.amount,
memo: event.memo ?? null,
}));
const res = await sql`
INSERT INTO stx_events ${sql(values)}
`;
if (res.count !== eventBatch.length) {
throw new Error(`Expected ${eventBatch.length} inserts, got ${res.count}`);
}
}
}