diff --git a/vochain/indexer/db/blocks.sql.go b/vochain/indexer/db/blocks.sql.go index 01e6ba54a..c45e0bf6a 100644 --- a/vochain/indexer/db/blocks.sql.go +++ b/vochain/indexer/db/blocks.sql.go @@ -17,6 +17,12 @@ INSERT INTO blocks( ) VALUES ( ?, ?, ?, ?, ?, ? ) +ON CONFLICT(height) DO UPDATE +SET chain_id = excluded.chain_id, + time = excluded.time, + hash = excluded.hash, + proposer_address = excluded.proposer_address, + last_block_hash = excluded.last_block_hash ` type CreateBlockParams struct { diff --git a/vochain/indexer/indexer.go b/vochain/indexer/indexer.go index d66ce1f07..21821c10b 100644 --- a/vochain/indexer/indexer.go +++ b/vochain/indexer/indexer.go @@ -402,6 +402,31 @@ func (idx *Indexer) AfterSyncBootstrap(inTest bool) { log.Infof("live results recovery computation finished, took %s", time.Since(startTime)) } +func (idx *Indexer) ReindexBlocks() { + queries := idx.blockTxQueries() + + for i := idx.App.Node.BlockStore().Base(); i <= idx.App.Node.BlockStore().Height(); i++ { + if b := idx.App.GetBlockByHeight(int64(i)); b != nil { + idxBlock, err := idx.readOnlyQuery.GetBlockByHeight(context.TODO(), i) + if err == nil && idxBlock.Time != b.Time { + log.Errorf("while reindexing blocks, block %d timestamp in db (%s) differs from blockstore (%s), leaving untouched", i, idxBlock.Time, b.Time) + continue + } + // if we got here, the block doesn't exist + if _, err := queries.CreateBlock(context.TODO(), indexerdb.CreateBlockParams{ + ChainID: b.ChainID, + Height: b.Height, + Time: b.Time, + Hash: nonNullBytes(b.Hash()), + ProposerAddress: nonNullBytes(b.ProposerAddress), + LastBlockHash: nonNullBytes(b.LastBlockID.Hash), + }); err != nil { + log.Errorw(err, "cannot index new block") + } + } + } +} + // Commit is called by the APP when a block is confirmed and included into the chain func (idx *Indexer) Commit(height uint32) error { idx.blockMu.Lock() diff --git a/vochain/indexer/queries/blocks.sql b/vochain/indexer/queries/blocks.sql index 38380967b..a00af5ca7 100644 --- a/vochain/indexer/queries/blocks.sql +++ b/vochain/indexer/queries/blocks.sql @@ -3,7 +3,13 @@ INSERT INTO blocks( chain_id, height, time, hash, proposer_address, last_block_hash ) VALUES ( ?, ?, ?, ?, ?, ? -); +) +ON CONFLICT(height) DO UPDATE +SET chain_id = excluded.chain_id, + time = excluded.time, + hash = excluded.hash, + proposer_address = excluded.proposer_address, + last_block_hash = excluded.last_block_hash; -- name: GetBlockByHeight :one SELECT * FROM blocks