Validate block hash chain after indexing and for new blocks

This commit is contained in:
nymkappa
2022-04-18 17:49:22 +09:00
parent 653ce3e40c
commit 900e02d9a5
4 changed files with 68 additions and 17 deletions

View File

@@ -13,6 +13,8 @@ import blocksRepository from '../repositories/BlocksRepository';
import loadingIndicators from './loading-indicators';
import BitcoinApi from './bitcoin/bitcoin-api';
import { prepareBlock } from '../utils/blocks-utils';
import BlocksRepository from '../repositories/BlocksRepository';
import HashratesRepository from '../repositories/HashratesRepository';
class Blocks {
private blocks: BlockExtended[] = [];
@@ -23,7 +25,7 @@ class Blocks {
private newBlockCallbacks: ((block: BlockExtended, txIds: string[], transactions: TransactionExtended[]) => void)[] = [];
private blockIndexingStarted = false;
public blockIndexingCompleted = false;
public reindexFlag = true; // Always re-index the latest indexed data in case the node went offline with an invalid block tip (reorg)
public reindexFlag = false;
constructor() { }
@@ -272,10 +274,13 @@ class Blocks {
return;
}
this.blockIndexingCompleted = true;
const chainValid = await BlocksRepository.$validateChain();
this.reindexFlag = !chainValid;
this.blockIndexingCompleted = chainValid;
}
public async $updateBlocks() {
let fastForwarded = false;
const blockHeightTip = await bitcoinApi.$getBlockHeightTip();
if (this.blocks.length === 0) {
@@ -287,6 +292,7 @@ class Blocks {
if (blockHeightTip - this.currentBlockHeight > config.MEMPOOL.INITIAL_BLOCKS_AMOUNT * 2) {
logger.info(`${blockHeightTip - this.currentBlockHeight} blocks since tip. Fast forwarding to the ${config.MEMPOOL.INITIAL_BLOCKS_AMOUNT} recent blocks`);
this.currentBlockHeight = blockHeightTip - config.MEMPOOL.INITIAL_BLOCKS_AMOUNT;
fastForwarded = true;
}
if (!this.lastDifficultyAdjustmentTime) {
@@ -324,12 +330,16 @@ class Blocks {
const blockExtended: BlockExtended = await this.$getBlockExtended(block, transactions);
if (Common.indexingEnabled()) {
await blocksRepository.$saveBlockInDatabase(blockExtended);
// If the last 10 blocks chain is not valid, re-index them (reorg)
const chainValid = await blocksRepository.$validateRecentBlocks();
if (!chainValid) {
this.reindexFlag = true;
if (!fastForwarded) {
const lastBlock = await blocksRepository.$getBlockByHeight(blockExtended.height - 1);
if (lastBlock !== null && blockExtended.id !== lastBlock['previousblockhash']) {
logger.warn(`Chain divergence detected at block ${lastBlock['height']}, re-indexing most recent data`);
await BlocksRepository.$deleteBlocksFrom(lastBlock['height'] - 2);
await HashratesRepository.$deleteLastEntries();
this.reindexFlag = true;
} else {
await blocksRepository.$saveBlockInDatabase(blockExtended);
}
}
}