core: refactor read and write valid sections (#1808)

This commit is contained in:
Daniel Liu 2025-12-08 17:37:33 +08:00 committed by GitHub
parent 348b7fa68f
commit bc5794cdf5
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 27 additions and 8 deletions

View file

@ -18,7 +18,6 @@ package core
import (
"context"
"encoding/binary"
"errors"
"fmt"
"sync"
@ -410,18 +409,15 @@ func (c *ChainIndexer) AddChildIndexer(indexer *ChainIndexer) {
// loadValidSections reads the number of valid sections from the index database
// and caches is into the local state.
func (c *ChainIndexer) loadValidSections() {
data, _ := c.indexDb.Get([]byte("count"))
if len(data) == 8 {
c.storedSections = binary.BigEndian.Uint64(data[:])
storedSections := rawdb.ReadValidSections(c.indexDb)
if storedSections != nil {
c.storedSections = *storedSections
}
}
// setValidSections writes the number of valid sections to the index database
func (c *ChainIndexer) setValidSections(sections uint64) {
// Set the current number of valid sections in the database
var data [8]byte
binary.BigEndian.PutUint64(data[:], sections)
c.indexDb.Put([]byte("count"), data[:])
rawdb.WriteValidSections(c.indexDb, sections)
// Remove any reorged sections, caching the valids in the mean time
for c.storedSections > sections {

View file

@ -17,6 +17,8 @@
package rawdb
import (
"encoding/binary"
"github.com/XinFinOrg/XDPoSChain/common"
"github.com/XinFinOrg/XDPoSChain/ethdb"
"github.com/XinFinOrg/XDPoSChain/log"
@ -79,3 +81,23 @@ func DeleteectionHead(db ethdb.KeyValueWriter, section uint64) {
log.Crit("Failed to delete section head", "err", err)
}
}
// ReadValidSections retrieves the number of valid sections from database.
func ReadValidSections(db ethdb.KeyValueReader) *uint64 {
data, err := db.Get(validSectionsKey)
if err != nil || len(data) != 8 {
return nil
}
storedSections := binary.BigEndian.Uint64(data[:])
return &storedSections
}
// WriteValidSections writes the number of valid sections into database
func WriteValidSections(db ethdb.KeyValueWriter, sections uint64) {
// Set the current number of valid sections in the database
var data [8]byte
binary.BigEndian.PutUint64(data[:], sections)
if err := db.Put(validSectionsKey, data[:]); err != nil {
log.Crit("Failed to store valid sections", "err", err)
}
}

View file

@ -83,6 +83,7 @@ var (
xdposV2Prefix = []byte("XDPoS-V2-")
sectionHeadKeyPrefix = []byte("shead")
validSectionsKey = []byte("count")
preimageCounter = metrics.NewRegisteredCounter("db/preimage/total", nil)
preimageHitCounter = metrics.NewRegisteredCounter("db/preimage/hits", nil)