params: improve function BuildConfigIndex() (#1935)

This commit is contained in:
Daniel Liu 2026-01-16 18:19:03 +08:00 committed by GitHub
parent 09e8b0b812
commit 7267895b82
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 20 additions and 14 deletions

View file

@ -17,7 +17,9 @@
package params package params
import ( import (
"cmp"
"fmt" "fmt"
"maps"
"math/big" "math/big"
"strings" "strings"
"sync" "sync"
@ -793,21 +795,11 @@ func (v2 *V2) Config(round uint64) *V2Config {
} }
func (v2 *V2) BuildConfigIndex() { func (v2 *V2) BuildConfigIndex() {
var list []uint64 list := slices.Collect(maps.Keys(v2.AllConfigs))
for i := range v2.AllConfigs {
list = append(list, i)
}
// sort, sort lib doesn't support type uint64, it's ok to have O(n^2) because only few items in the list
// Make it descending order // Make it descending order
for i := 0; i < len(list)-1; i++ { slices.SortFunc(list, func(a, b uint64) int {
for j := i + 1; j < len(list); j++ { return cmp.Compare(b, a)
if list[i] < list[j] { })
list[i], list[j] = list[j], list[i]
}
}
}
log.Info("[BuildConfigIndex] config list", "list", list) log.Info("[BuildConfigIndex] config list", "list", list)
v2.configIndex = list v2.configIndex = list
} }

View file

@ -118,6 +118,20 @@ func TestBuildConfigIndex(t *testing.T) {
assert.Equal(t, expected, index) assert.Equal(t, expected, index)
} }
func TestBuildConfigIndexDescendingOrder(t *testing.T) {
v2 := &V2{
AllConfigs: map[uint64]*V2Config{
5: {SwitchRound: 5},
2: {SwitchRound: 2},
10: {SwitchRound: 10},
0: {SwitchRound: 0},
15: {SwitchRound: 15},
},
}
v2.BuildConfigIndex()
assert.Equal(t, []uint64{15, 10, 5, 2, 0}, v2.ConfigIndex())
}
// Test switch epoch is switchblock divide into epoch per block // Test switch epoch is switchblock divide into epoch per block
func TestSwitchEpoch(t *testing.T) { func TestSwitchEpoch(t *testing.T) {
config := XDCMainnetChainConfig.XDPoS config := XDCMainnetChainConfig.XDPoS