Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added Stake Manager fuzz tests #1500

Merged
merged 7 commits into from
May 24, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 9 additions & 9 deletions consensus/polybft/helpers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -142,35 +142,35 @@ func getEpochNumber(t *testing.T, blockNumber, epochSize uint64) uint64 {
}

// newTestState creates new instance of state used by tests.
func newTestState(t *testing.T) *State {
t.Helper()
func newTestState(tb testing.TB) *State {
tb.Helper()

dir := fmt.Sprintf("/tmp/consensus-temp_%v", time.Now().UTC().Format(time.RFC3339Nano))
err := os.Mkdir(dir, 0775)

if err != nil {
t.Fatal(err)
tb.Fatal(err)
}

state, err := newState(path.Join(dir, "my.db"), hclog.NewNullLogger(), make(chan struct{}))
if err != nil {
t.Fatal(err)
tb.Fatal(err)
}

t.Cleanup(func() {
tb.Cleanup(func() {
if err := os.RemoveAll(dir); err != nil {
t.Fatal(err)
tb.Fatal(err)
}
})

return state
}

func generateTestAccount(t *testing.T) *wallet.Account {
t.Helper()
func generateTestAccount(tb testing.TB) *wallet.Account {
tb.Helper()

acc, err := wallet.GenerateAccount()
require.NoError(t, err)
require.NoError(tb, err)

return acc
}
Expand Down
18 changes: 9 additions & 9 deletions consensus/polybft/mocks_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -279,19 +279,19 @@ type testValidators struct {
validators map[string]*testValidator
}

func newTestValidators(t *testing.T, validatorsCount int) *testValidators {
t.Helper()
func newTestValidators(tb testing.TB, validatorsCount int) *testValidators {
tb.Helper()

aliases := make([]string, validatorsCount)
for i := 0; i < validatorsCount; i++ {
aliases[i] = strconv.Itoa(i)
}

return newTestValidatorsWithAliases(t, aliases)
return newTestValidatorsWithAliases(tb, aliases)
}

func newTestValidatorsWithAliases(t *testing.T, aliases []string, votingPowers ...[]uint64) *testValidators {
t.Helper()
func newTestValidatorsWithAliases(tb testing.TB, aliases []string, votingPowers ...[]uint64) *testValidators {
tb.Helper()

validators := map[string]*testValidator{}

Expand All @@ -301,7 +301,7 @@ func newTestValidatorsWithAliases(t *testing.T, aliases []string, votingPowers .
votingPower = votingPowers[0][i]
}

validators[alias] = newTestValidator(t, alias, votingPower)
validators[alias] = newTestValidator(tb, alias, votingPower)
}

return &testValidators{validators: validators}
Expand Down Expand Up @@ -398,13 +398,13 @@ type testValidator struct {
votingPower uint64
}

func newTestValidator(t *testing.T, alias string, votingPower uint64) *testValidator {
t.Helper()
func newTestValidator(tb testing.TB, alias string, votingPower uint64) *testValidator {
tb.Helper()

return &testValidator{
alias: alias,
votingPower: votingPower,
account: generateTestAccount(t),
account: generateTestAccount(tb),
}
}

Expand Down
205 changes: 205 additions & 0 deletions consensus/polybft/stake_manager_fuzz_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,205 @@
package polybft

import (
"encoding/json"
"math/big"
"testing"

"github.com/0xPolygon/polygon-edge/consensus/polybft/wallet"
"github.com/0xPolygon/polygon-edge/types"
"github.com/hashicorp/go-hclog"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
go_fuzz_utils "github.com/trailofbits/go-fuzz-utils"
)

func FuzzTestStakeManagerPostEpoch(f *testing.F) {
state := newTestState(f)

seeds := []struct {
EpochID uint64
Validators AccountSet
}{
{
EpochID: 0,
Validators: newTestValidators(f, 6).getPublicIdentities(),
},
{
EpochID: 1,
Validators: newTestValidators(f, 42).getPublicIdentities(),
},
{
EpochID: 42,
Validators: newTestValidators(f, 6).getPublicIdentities(),
},
}

for _, seed := range seeds {
data, _ := json.Marshal(seed)
f.Add(data)
}

f.Fuzz(func(t *testing.T, input []byte) {
stakeManager := &stakeManager{
logger: hclog.NewNullLogger(),
state: state,
maxValidatorSetSize: 10,
}

tp, err := go_fuzz_utils.NewTypeProvider(input)
if err != nil {
return
}
newEpochID, err := tp.GetUint64()
if err != nil {
return
}
var validators AccountSet
err = tp.Fill(validators)
if err != nil {
jelacamarko marked this conversation as resolved.
Show resolved Hide resolved
return
}

_ = stakeManager.PostEpoch(&PostEpochRequest{
jelacamarko marked this conversation as resolved.
Show resolved Hide resolved
NewEpochID: newEpochID,
ValidatorSet: NewValidatorSet(
validators,
stakeManager.logger,
),
})
})
}

func FuzzTestStakeManagerPostBlock(f *testing.F) {
var (
allAliases = []string{"A", "B", "C", "D", "E", "F"}
initialSetAliases = []string{"A", "B", "C", "D", "E"}
validators = newTestValidatorsWithAliases(f, allAliases)
state = newTestState(f)
)

f.Fuzz(func(t *testing.T, input []byte) {
t.Parallel()

tp, err := go_fuzz_utils.NewTypeProvider(input)
if err != nil {
return
}

stakeValue, err := tp.GetUint64()
if err != nil {
return
}

epoch, err := tp.GetUint64()
if err != nil {
return
}
validatorID, err := tp.GetUint64()
if err != nil {
return
}

if validatorID > uint64(len(initialSetAliases)-1) {
t.Skip()
}

block, err := tp.GetUint64()
if err != nil {
return
}

systemStateMock := new(systemStateMock)
systemStateMock.On("GetStakeOnValidatorSet", mock.Anything).Return(big.NewInt(int64(stakeValue)), nil).Once()

blockchainMock := new(blockchainMock)
blockchainMock.On("GetStateProviderForBlock", mock.Anything).Return(new(stateProviderMock)).Once()
blockchainMock.On("GetSystemState", mock.Anything, mock.Anything).Return(systemStateMock)

stakeManager := newStakeManager(
hclog.NewNullLogger(),
state,
blockchainMock,
nil,
wallet.NewEcdsaSigner(validators.getValidator("A").Key()),
types.StringToAddress("0x0001"),
types.StringToAddress("0x0002"),
5,
)

// insert initial full validator set
require.NoError(t, state.StakeStore.insertFullValidatorSet(validatorSetState{
Validators: newValidatorStakeMap(validators.getPublicIdentities(initialSetAliases...)),
}))

receipt := &types.Receipt{
Logs: []*types.Log{
createTestLogForTransferEvent(
t,
stakeManager.validatorSetContract,
validators.getValidator(initialSetAliases[validatorID]).Address(),
types.ZeroAddress,
stakeValue,
),
},
}

req := &PostBlockRequest{
FullBlock: &types.FullBlock{Block: &types.Block{Header: &types.Header{Number: block}},
Receipts: []*types.Receipt{receipt},
},
Epoch: epoch,
}
_ = stakeManager.PostBlock(req)
})
}

func FuzzTestStakeManagerUpdateValidatorSet(f *testing.F) {
var (
aliases = []string{"A", "B", "C", "D", "E"}
stakes = []uint64{10, 10, 10, 10, 10}
)

validators := newTestValidatorsWithAliases(f, aliases, stakes)
state := newTestState(f)

stakeManager := newStakeManager(
hclog.NewNullLogger(),
state,
nil,
nil,
wallet.NewEcdsaSigner(validators.getValidator("A").Key()),
types.StringToAddress("0x0001"), types.StringToAddress("0x0002"),
10,
)

f.Fuzz(func(t *testing.T, input []byte) {
tp, err := go_fuzz_utils.NewTypeProvider(input)
if err != nil {
return
}
epoch, err := tp.GetUint64()
if err != nil {
return
}
x, err := tp.GetUint64()
if err != nil {
return
}
if x > uint64(len(aliases)-1) {
t.Skip()
}
votingPower, err := tp.GetInt64()
if err != nil {
return
}

_, _ = stakeManager.UpdateValidatorSet(epoch, validators.getPublicIdentities(aliases[x:]...))
jelacamarko marked this conversation as resolved.
Show resolved Hide resolved

fullValidatorSet := validators.getPublicIdentities().Copy()
validatorToUpdate := fullValidatorSet[x]
validatorToUpdate.VotingPower = big.NewInt(votingPower)

_, _ = stakeManager.UpdateValidatorSet(epoch, validators.getPublicIdentities())
jelacamarko marked this conversation as resolved.
Show resolved Hide resolved
})
}