diff --git a/params/config.go b/params/config.go index 5aaca9f693..c4d814311a 100644 --- a/params/config.go +++ b/params/config.go @@ -17,7 +17,9 @@ package params import ( + "cmp" "fmt" + "maps" "math/big" "strings" "sync" @@ -793,21 +795,11 @@ func (v2 *V2) Config(round uint64) *V2Config { } func (v2 *V2) BuildConfigIndex() { - var list []uint64 - - 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 + list := slices.Collect(maps.Keys(v2.AllConfigs)) // Make it descending order - for i := 0; i < len(list)-1; i++ { - for j := i + 1; j < len(list); j++ { - if list[i] < list[j] { - list[i], list[j] = list[j], list[i] - } - } - } + slices.SortFunc(list, func(a, b uint64) int { + return cmp.Compare(b, a) + }) log.Info("[BuildConfigIndex] config list", "list", list) v2.configIndex = list } diff --git a/params/config_test.go b/params/config_test.go index bd4113e135..7dbbc82291 100644 --- a/params/config_test.go +++ b/params/config_test.go @@ -118,6 +118,20 @@ func TestBuildConfigIndex(t *testing.T) { 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 func TestSwitchEpoch(t *testing.T) { config := XDCMainnetChainConfig.XDPoS