refactor(distribution)!: use collections for ValidatorHistoricalRewards state (#16607)

Co-authored-by: unknown unknown <unknown@unknown>
This commit is contained in:
testinginprod
2023-06-22 08:47:21 +00:00
committed by GitHub
co-authored by unknown unknown
parent 8d47088f5b
commit 43d345dc2f
24 changed files with 648 additions and 133 deletions
+41
View File
@@ -1,6 +1,7 @@
package types
import (
"encoding/binary"
"fmt"
"time"
@@ -37,6 +38,12 @@ var (
// be used for new storage keys using time. Please use the time KeyCodec
// provided in the collections package.
TimeKey collcodec.KeyCodec[time.Time] = timeKeyCodec{}
// LEUint64Key is a collections KeyCodec that encodes uint64 using little endian.
// NOTE: it MUST NOT be used by other modules, distribution relies on this only for
// state backwards compatibility.
// Deprecated: use collections.Uint64Key instead.
LEUint64Key collcodec.KeyCodec[uint64] = leUint64Key{}
)
type addressUnion interface {
@@ -208,3 +215,37 @@ func (t timeKeyCodec) DecodeNonTerminal(buffer []byte) (int, time.Time, error) {
return t.Decode(buffer[:timeSize])
}
func (t timeKeyCodec) SizeNonTerminal(key time.Time) int { return t.Size(key) }
type leUint64Key struct{}
func (l leUint64Key) Encode(buffer []byte, key uint64) (int, error) {
binary.LittleEndian.PutUint64(buffer, key)
return 8, nil
}
func (l leUint64Key) Decode(buffer []byte) (int, uint64, error) {
if size := len(buffer); size < 8 {
return 0, 0, fmt.Errorf("invalid buffer size, wanted 8 at least got %d", size)
}
return 8, binary.LittleEndian.Uint64(buffer), nil
}
func (l leUint64Key) Size(_ uint64) int { return 8 }
func (l leUint64Key) EncodeJSON(value uint64) ([]byte, error) {
return collections.Uint64Key.EncodeJSON(value)
}
func (l leUint64Key) DecodeJSON(b []byte) (uint64, error) { return collections.Uint64Key.DecodeJSON(b) }
func (l leUint64Key) Stringify(key uint64) string { return collections.Uint64Key.Stringify(key) }
func (l leUint64Key) KeyType() string { return "little-endian-uint64" }
func (l leUint64Key) EncodeNonTerminal(buffer []byte, key uint64) (int, error) {
return l.Encode(buffer, key)
}
func (l leUint64Key) DecodeNonTerminal(buffer []byte) (int, uint64, error) { return l.Decode(buffer) }
func (l leUint64Key) SizeNonTerminal(_ uint64) int { return 8 }
+13
View File
@@ -5,6 +5,8 @@ import (
"time"
"cosmossdk.io/collections/colltest"
"github.com/stretchr/testify/require"
"pgregory.net/rapid"
)
func TestCollectionsCorrectness(t *testing.T) {
@@ -28,3 +30,14 @@ func TestCollectionsCorrectness(t *testing.T) {
colltest.TestKeyCodec(t, TimeKey, time.Time{})
})
}
func TestLEUint64Key(t *testing.T) {
t.Run("conformance", rapid.MakeCheck(func(r *rapid.T) {
colltest.TestKeyCodec(t, LEUint64Key, rapid.Uint64().Draw(r, "uint64"))
}))
t.Run("buffer too small", func(t *testing.T) {
_, _, err := LEUint64Key.Decode([]byte{0})
require.ErrorContains(t, err, "invalid buffer size")
})
}