From 611668c237fdd13b2240ecdbe1b8f2a1ce886ce1 Mon Sep 17 00:00:00 2001 From: Daniel Liu <139250065@qq.com> Date: Tue, 4 Nov 2025 13:47:40 +0800 Subject: [PATCH] internal/ethapi: improve `ChaindbCompact()` and `ChaindbProperty()` #19021 #19856 #28207, fix XFN-139 (#1722) * internal/ethapi: clean up and properly abstract database accesses #19021 * internal/ethapi: fix debug.chaindbProperty #19856 * internal/ethapi: compact db missing key starts with 0xff #28207 --- internal/ethapi/api.go | 35 +++++++++++++++-------------------- 1 file changed, 15 insertions(+), 20 deletions(-) diff --git a/internal/ethapi/api.go b/internal/ethapi/api.go index 3423d18abd..31464a9b7a 100644 --- a/internal/ethapi/api.go +++ b/internal/ethapi/api.go @@ -53,8 +53,6 @@ import ( "github.com/XinFinOrg/XDPoSChain/params" "github.com/XinFinOrg/XDPoSChain/rlp" "github.com/XinFinOrg/XDPoSChain/rpc" - "github.com/syndtr/goleveldb/leveldb" - "github.com/syndtr/goleveldb/leveldb/util" ) const ( @@ -3080,33 +3078,30 @@ func (api *DebugAPI) PrintBlock(ctx context.Context, number uint64) (string, err return block.String(), nil } -// ChaindbProperty returns leveldb properties of the chain database. +// ChaindbProperty returns leveldb properties of the key-value database. func (api *DebugAPI) ChaindbProperty(property string) (string, error) { - ldb, ok := api.b.ChainDb().(interface { - LDB() *leveldb.DB - }) - if !ok { - return "", errors.New("chaindbProperty does not work for memory databases") - } if property == "" { property = "leveldb.stats" } else if !strings.HasPrefix(property, "leveldb.") { property = "leveldb." + property } - return ldb.LDB().GetProperty(property) + return api.b.ChainDb().Stat(property) } +// ChaindbCompact flattens the entire key-value database into a single level, +// removing all unused slots and merging all keys. func (api *DebugAPI) ChaindbCompact() error { - ldb, ok := api.b.ChainDb().(interface { - LDB() *leveldb.DB - }) - if !ok { - return errors.New("chaindbCompact does not work for memory databases") - } - for b := byte(0); b < 255; b++ { - log.Info("Compacting chain database", "range", fmt.Sprintf("0x%0.2X-0x%0.2X", b, b+1)) - err := ldb.LDB().CompactRange(util.Range{Start: []byte{b}, Limit: []byte{b + 1}}) - if err != nil { + cstart := time.Now() + for b := 0; b <= 255; b++ { + var ( + start = []byte{byte(b)} + end = []byte{byte(b + 1)} + ) + if b == 255 { + end = nil + } + log.Info("Compacting database", "range", fmt.Sprintf("%#X-%#X", start, end), "elapsed", common.PrettyDuration(time.Since(cstart))) + if err := api.b.ChainDb().Compact(start, end); err != nil { log.Error("Database compaction failed", "err", err) return err }