factory: simplify validator and genesis factory functions (#7305)

This commit is contained in:
William Banfield
2021-11-22 15:55:39 -05:00
committed by William Banfield
parent 15d6aefaf9
commit d4e712e4f1
22 changed files with 185 additions and 137 deletions

View File

@@ -200,7 +200,8 @@ func TestReactor_AbruptDisconnect(t *testing.T) {
require.NoError(t, err)
defer os.RemoveAll(cfg.RootDir)
genDoc, privVals := factory.RandGenesisDoc(cfg, 1, false, 30)
valSet, privVals := factory.ValidatorSet(1, 30)
genDoc := factory.GenesisDoc(cfg, time.Now(), valSet.Validators, nil)
maxBlockHeight := int64(64)
rts := setup(ctx, t, genDoc, privVals[0], []int64{maxBlockHeight, 0}, 0)
@@ -239,7 +240,8 @@ func TestReactor_SyncTime(t *testing.T) {
require.NoError(t, err)
defer os.RemoveAll(cfg.RootDir)
genDoc, privVals := factory.RandGenesisDoc(cfg, 1, false, 30)
valSet, privVals := factory.ValidatorSet(1, 30)
genDoc := factory.GenesisDoc(cfg, time.Now(), valSet.Validators, nil)
maxBlockHeight := int64(101)
rts := setup(ctx, t, genDoc, privVals[0], []int64{maxBlockHeight, 0}, 0)
@@ -264,10 +266,10 @@ func TestReactor_NoBlockResponse(t *testing.T) {
cfg, err := config.ResetTestRoot("block_sync_reactor_test")
require.NoError(t, err)
defer os.RemoveAll(cfg.RootDir)
genDoc, privVals := factory.RandGenesisDoc(cfg, 1, false, 30)
valSet, privVals := factory.ValidatorSet(1, 30)
genDoc := factory.GenesisDoc(cfg, time.Now(), valSet.Validators, nil)
maxBlockHeight := int64(65)
rts := setup(ctx, t, genDoc, privVals[0], []int64{maxBlockHeight, 0}, 0)
@@ -319,7 +321,8 @@ func TestReactor_BadBlockStopsPeer(t *testing.T) {
defer os.RemoveAll(cfg.RootDir)
maxBlockHeight := int64(48)
genDoc, privVals := factory.RandGenesisDoc(cfg, 1, false, 30)
valSet, privVals := factory.ValidatorSet(1, 30)
genDoc := factory.GenesisDoc(cfg, time.Now(), valSet.Validators, nil)
rts := setup(ctx, t, genDoc, privVals[0], []int64{maxBlockHeight, 0, 0, 0, 0}, 1000)
@@ -353,7 +356,8 @@ func TestReactor_BadBlockStopsPeer(t *testing.T) {
//
// XXX: This causes a potential race condition.
// See: https://github.com/tendermint/tendermint/issues/6005
otherGenDoc, otherPrivVals := factory.RandGenesisDoc(cfg, 1, false, 30)
valSet, otherPrivVals := factory.ValidatorSet(1, 30)
otherGenDoc := factory.GenesisDoc(cfg, time.Now(), valSet.Validators, nil)
newNode := rts.network.MakeNode(ctx, t, p2ptest.NodeOptions{
MaxPeers: uint16(len(rts.nodes) + 1),
MaxConnected: uint16(len(rts.nodes) + 1),

View File

@@ -7,6 +7,7 @@ import (
"path"
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
@@ -42,7 +43,8 @@ func TestByzantinePrevoteEquivocation(t *testing.T) {
tickerFunc := newMockTickerFunc(true)
appFunc := newKVStore
genDoc, privVals := factory.RandGenesisDoc(config, nValidators, false, 30)
valSet, privVals := factory.ValidatorSet(nValidators, 30)
genDoc := factory.GenesisDoc(config, time.Now(), valSet.Validators, nil)
states := make([]*State, nValidators)
for i := 0; i < nValidators; i++ {

View File

@@ -19,6 +19,7 @@ import (
"github.com/tendermint/tendermint/abci/example/kvstore"
abci "github.com/tendermint/tendermint/abci/types"
"github.com/tendermint/tendermint/config"
cfg "github.com/tendermint/tendermint/config"
cstypes "github.com/tendermint/tendermint/internal/consensus/types"
"github.com/tendermint/tendermint/internal/eventbus"
tmsync "github.com/tendermint/tendermint/internal/libs/sync"
@@ -492,14 +493,11 @@ func loadPrivValidator(t *testing.T, config *config.Config) *privval.FilePV {
return privValidator
}
func randState(
ctx context.Context,
cfg *config.Config,
logger log.Logger,
nValidators int,
) (*State, []*validatorStub, error) {
func makeState(ctx context.Context, cfg *config.Config, logger log.Logger, nValidators int) (*State, []*validatorStub, error) {
// Get State
state, privVals := randGenesisState(cfg, nValidators, false, 10)
state, privVals := makeGenesisState(cfg, genesisStateArgs{
Validators: nValidators,
})
vss := make([]*validatorStub, nValidators)
@@ -764,7 +762,7 @@ func consensusLogger() log.Logger {
return log.TestingLogger().With("module", "consensus")
}
func randConsensusState(
func makeConsensusState(
ctx context.Context,
t *testing.T,
cfg *config.Config,
@@ -776,7 +774,8 @@ func randConsensusState(
) ([]*State, cleanupFunc) {
t.Helper()
genDoc, privVals := factory.RandGenesisDoc(cfg, nValidators, false, 30)
valSet, privVals := factory.ValidatorSet(nValidators, 30)
genDoc := factory.GenesisDoc(cfg, time.Now(), valSet.Validators, nil)
css := make([]*State, nValidators)
logger := consensusLogger()
@@ -834,7 +833,8 @@ func randConsensusNetWithPeers(
tickerFunc func() TimeoutTicker,
appFunc func(string) abci.Application,
) ([]*State, *types.GenesisDoc, *config.Config, cleanupFunc) {
genDoc, privVals := factory.RandGenesisDoc(cfg, nValidators, false, testMinPower)
valSet, privVals := factory.ValidatorSet(nValidators, testMinPower)
genDoc := factory.GenesisDoc(cfg, time.Now(), valSet.Validators, nil)
css := make([]*State, nPeers)
t.Helper()
logger := consensusLogger()
@@ -891,13 +891,28 @@ func randConsensusNetWithPeers(
}
}
func randGenesisState(
cfg *config.Config,
numValidators int,
randPower bool,
minPower int64) (sm.State, []types.PrivValidator) {
type genesisStateArgs struct {
Validators int
Power int64
Params *types.ConsensusParams
Time time.Time
}
genDoc, privValidators := factory.RandGenesisDoc(cfg, numValidators, randPower, minPower)
func makeGenesisState(config *cfg.Config, args genesisStateArgs) (sm.State, []types.PrivValidator) {
if args.Power == 0 {
args.Power = 1
}
if args.Validators == 0 {
args.Power = 4
}
valSet, privValidators := factory.ValidatorSet(args.Validators, args.Power)
if args.Params == nil {
args.Params = types.DefaultConsensusParams()
}
if args.Time.IsZero() {
args.Time = time.Now()
}
genDoc := factory.GenesisDoc(config, args.Time, valSet.Validators, args.Params)
s0, _ := sm.MakeGenesisState(genDoc)
return s0, privValidators
}

View File

@@ -23,7 +23,7 @@ func TestReactorInvalidPrecommit(t *testing.T) {
config := configSetup(t)
n := 4
states, cleanup := randConsensusState(ctx, t,
states, cleanup := makeConsensusState(ctx, t,
config, n, "consensus_reactor_test",
newMockTickerFunc(true), newKVStore)
t.Cleanup(cleanup)

View File

@@ -37,7 +37,9 @@ func TestMempoolNoProgressUntilTxsAvailable(t *testing.T) {
t.Cleanup(func() { _ = os.RemoveAll(config.RootDir) })
config.Consensus.CreateEmptyBlocks = false
state, privVals := randGenesisState(baseConfig, 1, false, 10)
state, privVals := makeGenesisState(baseConfig, genesisStateArgs{
Validators: 1,
Power: 10})
cs := newStateWithConfig(ctx, log.TestingLogger(), config, state, privVals[0], NewCounterApplication())
assertMempool(cs.txNotifier).EnableTxsAvailable()
height, round := cs.Height, cs.Round
@@ -62,7 +64,9 @@ func TestMempoolProgressAfterCreateEmptyBlocksInterval(t *testing.T) {
t.Cleanup(func() { _ = os.RemoveAll(config.RootDir) })
config.Consensus.CreateEmptyBlocksInterval = ensureTimeout
state, privVals := randGenesisState(baseConfig, 1, false, 10)
state, privVals := makeGenesisState(baseConfig, genesisStateArgs{
Validators: 1,
Power: 10})
cs := newStateWithConfig(ctx, log.TestingLogger(), config, state, privVals[0], NewCounterApplication())
assertMempool(cs.txNotifier).EnableTxsAvailable()
@@ -85,7 +89,9 @@ func TestMempoolProgressInHigherRound(t *testing.T) {
t.Cleanup(func() { _ = os.RemoveAll(config.RootDir) })
config.Consensus.CreateEmptyBlocks = false
state, privVals := randGenesisState(baseConfig, 1, false, 10)
state, privVals := makeGenesisState(baseConfig, genesisStateArgs{
Validators: 1,
Power: 10})
cs := newStateWithConfig(ctx, log.TestingLogger(), config, state, privVals[0], NewCounterApplication())
assertMempool(cs.txNotifier).EnableTxsAvailable()
height, round := cs.Height, cs.Round
@@ -136,7 +142,9 @@ func TestMempoolTxConcurrentWithCommit(t *testing.T) {
config := configSetup(t)
logger := log.TestingLogger()
state, privVals := randGenesisState(config, 1, false, 10)
state, privVals := makeGenesisState(config, genesisStateArgs{
Validators: 1,
Power: 10})
stateStore := sm.NewStore(dbm.NewMemDB())
blockStore := store.NewBlockStore(dbm.NewMemDB())
@@ -168,7 +176,9 @@ func TestMempoolRmBadTx(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
state, privVals := randGenesisState(config, 1, false, 10)
state, privVals := makeGenesisState(config, genesisStateArgs{
Validators: 1,
Power: 10})
app := NewCounterApplication()
stateStore := sm.NewStore(dbm.NewMemDB())
blockStore := store.NewBlockStore(dbm.NewMemDB())

View File

@@ -311,7 +311,7 @@ func TestReactorBasic(t *testing.T) {
cfg := configSetup(t)
n := 4
states, cleanup := randConsensusState(ctx, t,
states, cleanup := makeConsensusState(ctx, t,
cfg, n, "consensus_reactor_test",
newMockTickerFunc(true), newKVStore)
t.Cleanup(cleanup)
@@ -368,7 +368,8 @@ func TestReactorWithEvidence(t *testing.T) {
tickerFunc := newMockTickerFunc(true)
appFunc := newKVStore
genDoc, privVals := factory.RandGenesisDoc(cfg, n, false, 30)
valSet, privVals := factory.ValidatorSet(n, 30)
genDoc := factory.GenesisDoc(cfg, time.Now(), valSet.Validators, nil)
states := make([]*State, n)
logger := consensusLogger()
@@ -470,8 +471,7 @@ func TestReactorCreatesBlockWhenEmptyBlocksFalse(t *testing.T) {
cfg := configSetup(t)
n := 4
states, cleanup := randConsensusState(
ctx,
states, cleanup := makeConsensusState(ctx,
t,
cfg,
n,
@@ -527,7 +527,7 @@ func TestReactorRecordsVotesAndBlockParts(t *testing.T) {
cfg := configSetup(t)
n := 4
states, cleanup := randConsensusState(ctx, t,
states, cleanup := makeConsensusState(ctx, t,
cfg, n, "consensus_reactor_test",
newMockTickerFunc(true), newKVStore)
t.Cleanup(cleanup)
@@ -592,8 +592,7 @@ func TestReactorVotingPowerChange(t *testing.T) {
cfg := configSetup(t)
n := 4
states, cleanup := randConsensusState(
ctx,
states, cleanup := makeConsensusState(ctx,
t,
cfg,
n,

View File

@@ -1274,7 +1274,8 @@ func TestHandshakeUpdatesValidators(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
val, _ := factory.RandValidator(true, 10)
votePower := 10 + int64(rand.Uint32())
val, _ := factory.Validator(votePower)
vals := types.NewValidatorSet([]*types.Validator{val})
app := &initChainApp{vals: types.TM2PB.ValidatorUpdates(vals)}
clientCreator := abciclient.NewLocalCreator(app)

View File

@@ -66,10 +66,10 @@ func TestStateProposerSelection0(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
config := configSetup(t)
logger := log.TestingLogger()
cs1, vss, err := randState(ctx, config, log.TestingLogger(), 4)
cs1, vss, err := makeState(ctx, config, logger, 4)
require.NoError(t, err)
height, round := cs1.Height, cs1.Round
newRoundCh := subscribe(ctx, t, cs1.eventBus, types.EventQueryNewRound)
@@ -118,13 +118,12 @@ func TestStateProposerSelection0(t *testing.T) {
// Now let's do it all again, but starting from round 2 instead of 0
func TestStateProposerSelection2(t *testing.T) {
config := configSetup(t)
logger := log.TestingLogger()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
cs1, vss, err := randState(ctx, config, log.TestingLogger(), 4) // test needs more work for more than 3 validators
cs1, vss, err := makeState(ctx, config, logger, 4) // test needs more work for more than 3 validators
require.NoError(t, err)
height := cs1.Height
newRoundCh := subscribe(ctx, t, cs1.eventBus, types.EventQueryNewRound)
@@ -161,10 +160,12 @@ func TestStateProposerSelection2(t *testing.T) {
// a non-validator should timeout into the prevote round
func TestStateEnterProposeNoPrivValidator(t *testing.T) {
config := configSetup(t)
logger := log.TestingLogger()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
cs, _, err := randState(ctx, config, log.TestingLogger(), 1)
cs, _, err := makeState(ctx, config, logger, 1)
require.NoError(t, err)
require.NoError(t, err)
cs.SetPrivValidator(nil)
height, round := cs.Height, cs.Round
@@ -185,10 +186,11 @@ func TestStateEnterProposeNoPrivValidator(t *testing.T) {
// a validator should not timeout of the prevote round (TODO: unless the block is really big!)
func TestStateEnterProposeYesPrivValidator(t *testing.T) {
config := configSetup(t)
logger := log.TestingLogger()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
cs, _, err := randState(ctx, config, log.TestingLogger(), 1)
cs, _, err := makeState(ctx, config, logger, 1)
require.NoError(t, err)
height, round := cs.Height, cs.Round
@@ -220,10 +222,11 @@ func TestStateEnterProposeYesPrivValidator(t *testing.T) {
func TestStateBadProposal(t *testing.T) {
config := configSetup(t)
logger := log.TestingLogger()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
cs1, vss, err := randState(ctx, config, log.TestingLogger(), 2)
cs1, vss, err := makeState(ctx, config, logger, 2)
require.NoError(t, err)
height, round := cs1.Height, cs1.Round
vs2 := vss[1]
@@ -283,10 +286,11 @@ func TestStateBadProposal(t *testing.T) {
func TestStateOversizedBlock(t *testing.T) {
config := configSetup(t)
logger := log.TestingLogger()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
cs1, vss, err := randState(ctx, config, log.TestingLogger(), 2)
cs1, vss, err := makeState(ctx, config, logger, 2)
require.NoError(t, err)
cs1.state.ConsensusParams.Block.MaxBytes = 2000
height, round := cs1.Height, cs1.Round
@@ -354,7 +358,7 @@ func TestStateFullRound1(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
cs, vss, err := randState(ctx, config, logger, 1)
cs, vss, err := makeState(ctx, config, logger, 1)
require.NoError(t, err)
height, round := cs.Height, cs.Round
@@ -396,10 +400,11 @@ func TestStateFullRound1(t *testing.T) {
// nil is proposed, so prevote and precommit nil
func TestStateFullRoundNil(t *testing.T) {
config := configSetup(t)
logger := log.TestingLogger()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
cs, vss, err := randState(ctx, config, log.TestingLogger(), 1)
cs, vss, err := makeState(ctx, config, logger, 1)
require.NoError(t, err)
height, round := cs.Height, cs.Round
@@ -419,10 +424,11 @@ func TestStateFullRoundNil(t *testing.T) {
// where the first validator has to wait for votes from the second
func TestStateFullRound2(t *testing.T) {
config := configSetup(t)
logger := log.TestingLogger()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
cs1, vss, err := randState(ctx, config, log.TestingLogger(), 2)
cs1, vss, err := makeState(ctx, config, logger, 2)
require.NoError(t, err)
vs2 := vss[1]
height, round := cs1.Height, cs1.Round
@@ -464,10 +470,11 @@ func TestStateFullRound2(t *testing.T) {
// two vals take turns proposing. val1 locks on first one, precommits nil on everything else
func TestStateLock_NoPOL(t *testing.T) {
config := configSetup(t)
logger := log.TestingLogger()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
cs1, vss, err := randState(ctx, config, log.TestingLogger(), 2)
cs1, vss, err := makeState(ctx, config, logger, 2)
require.NoError(t, err)
vs2 := vss[1]
height, round := cs1.Height, cs1.Round
@@ -605,8 +612,7 @@ func TestStateLock_NoPOL(t *testing.T) {
ensureNewTimeout(t, timeoutWaitCh, height, round, cs1.config.Precommit(round).Nanoseconds())
// needed so generated block is different than locked block
cs2, _, err := randState(ctx, config, log.TestingLogger(), 2)
cs2, _, err := makeState(ctx, config, logger, 2) // needed so generated block is different than locked block
require.NoError(t, err)
// before we time out into new round, set next proposal block
prop, propBlock := decideProposal(ctx, t, cs2, vs2, vs2.Height, vs2.Round+1)
@@ -666,7 +672,7 @@ func TestStateLock_POLUpdateLock(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
cs1, vss, err := randState(ctx, config, logger, 4)
cs1, vss, err := makeState(ctx, config, logger, 4)
require.NoError(t, err)
vs2, vs3, vs4 := vss[1], vss[2], vss[3]
height, round := cs1.Height, cs1.Round
@@ -770,8 +776,9 @@ func TestStateLock_POLRelock(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
config := configSetup(t)
logger := log.TestingLogger()
cs1, vss, err := randState(ctx, config, log.TestingLogger(), 4)
cs1, vss, err := makeState(ctx, config, logger, 4)
require.NoError(t, err)
vs2, vs3, vs4 := vss[1], vss[2], vss[3]
height, round := cs1.Height, cs1.Round
@@ -871,8 +878,9 @@ func TestStateLock_PrevoteNilWhenLockedAndMissProposal(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
config := configSetup(t)
logger := log.TestingLogger()
cs1, vss, err := randState(ctx, config, log.TestingLogger(), 4)
cs1, vss, err := makeState(ctx, config, logger, 4)
require.NoError(t, err)
vs2, vs3, vs4 := vss[1], vss[2], vss[3]
height, round := cs1.Height, cs1.Round
@@ -960,7 +968,7 @@ func TestStateLock_PrevoteNilWhenLockedAndDifferentProposal(t *testing.T) {
state.
*/
cs1, vss, err := randState(ctx, config, logger, 4)
cs1, vss, err := makeState(ctx, config, logger, 4)
require.NoError(t, err)
vs2, vs3, vs4 := vss[1], vss[2], vss[3]
height, round := cs1.Height, cs1.Round
@@ -1062,7 +1070,7 @@ func TestStateLock_POLDoesNotUnlock(t *testing.T) {
state.
*/
cs1, vss, err := randState(ctx, config, logger, 4)
cs1, vss, err := makeState(ctx, config, logger, 4)
require.NoError(t, err)
vs2, vs3, vs4 := vss[1], vss[2], vss[3]
height, round := cs1.Height, cs1.Round
@@ -1199,7 +1207,7 @@ func TestStateLock_MissingProposalWhenPOLSeenDoesNotUpdateLock(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
cs1, vss, err := randState(ctx, config, logger, 4)
cs1, vss, err := makeState(ctx, config, logger, 4)
require.NoError(t, err)
vs2, vs3, vs4 := vss[1], vss[2], vss[3]
height, round := cs1.Height, cs1.Round
@@ -1285,8 +1293,9 @@ func TestStateLock_DoesNotLockOnOldProposal(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
config := configSetup(t)
logger := log.TestingLogger()
cs1, vss, err := randState(ctx, config, log.TestingLogger(), 4)
cs1, vss, err := makeState(ctx, config, logger, 4)
require.NoError(t, err)
vs2, vs3, vs4 := vss[1], vss[2], vss[3]
height, round := cs1.Height, cs1.Round
@@ -1364,7 +1373,7 @@ func TestStateLock_POLSafety1(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
cs1, vss, err := randState(ctx, config, logger, 4)
cs1, vss, err := makeState(ctx, config, logger, 4)
require.NoError(t, err)
vs2, vs3, vs4 := vss[1], vss[2], vss[3]
height, round := cs1.Height, cs1.Round
@@ -1486,7 +1495,7 @@ func TestStateLock_POLSafety2(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
cs1, vss, err := randState(ctx, config, logger, 4)
cs1, vss, err := makeState(ctx, config, logger, 4)
require.NoError(t, err)
vs2, vs3, vs4 := vss[1], vss[2], vss[3]
height, round := cs1.Height, cs1.Round
@@ -1585,7 +1594,7 @@ func TestState_PrevotePOLFromPreviousRound(t *testing.T) {
config := configSetup(t)
logger := log.TestingLogger()
cs1, vss, err := randState(ctx, config, logger, 4)
cs1, vss, err := makeState(ctx, config, logger, 4)
require.NoError(t, err)
vs2, vs3, vs4 := vss[1], vss[2], vss[3]
height, round := cs1.Height, cs1.Round
@@ -1724,10 +1733,11 @@ func TestState_PrevotePOLFromPreviousRound(t *testing.T) {
// P0 proposes B0 at R3.
func TestProposeValidBlock(t *testing.T) {
cfg := configSetup(t)
logger := log.TestingLogger()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
cs1, vss, err := randState(ctx, cfg, log.TestingLogger(), 4)
cs1, vss, err := makeState(ctx, cfg, logger, 4)
require.NoError(t, err)
vs2, vs3, vs4 := vss[1], vss[2], vss[3]
height, round := cs1.Height, cs1.Round
@@ -1818,10 +1828,11 @@ func TestProposeValidBlock(t *testing.T) {
// P0 miss to lock B but set valid block to B after receiving delayed prevote.
func TestSetValidBlockOnDelayedPrevote(t *testing.T) {
config := configSetup(t)
logger := log.TestingLogger()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
cs1, vss, err := randState(ctx, config, log.TestingLogger(), 4)
cs1, vss, err := makeState(ctx, config, logger, 4)
require.NoError(t, err)
vs2, vs3, vs4 := vss[1], vss[2], vss[3]
height, round := cs1.Height, cs1.Round
@@ -1885,10 +1896,11 @@ func TestSetValidBlockOnDelayedPrevote(t *testing.T) {
// receiving delayed Block Proposal.
func TestSetValidBlockOnDelayedProposal(t *testing.T) {
config := configSetup(t)
logger := log.TestingLogger()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
cs1, vss, err := randState(ctx, config, log.TestingLogger(), 4)
cs1, vss, err := makeState(ctx, config, logger, 4)
require.NoError(t, err)
vs2, vs3, vs4 := vss[1], vss[2], vss[3]
height, round := cs1.Height, cs1.Round
@@ -1945,12 +1957,12 @@ func TestSetValidBlockOnDelayedProposal(t *testing.T) {
// What we want:
// P0 waits for timeoutPrecommit before starting next round
func TestWaitingTimeoutOnNilPolka(t *testing.T) {
config := configSetup(t)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
config := configSetup(t)
logger := log.TestingLogger()
cs1, vss, err := randState(ctx, config, log.TestingLogger(), 4)
cs1, vss, err := makeState(ctx, config, logger, 4)
require.NoError(t, err)
vs2, vs3, vs4 := vss[1], vss[2], vss[3]
height, round := cs1.Height, cs1.Round
@@ -1973,10 +1985,11 @@ func TestWaitingTimeoutOnNilPolka(t *testing.T) {
// P0 waits for timeoutPropose in the next round before entering prevote
func TestWaitingTimeoutProposeOnNewRound(t *testing.T) {
config := configSetup(t)
logger := log.TestingLogger()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
cs1, vss, err := randState(ctx, config, log.TestingLogger(), 4)
cs1, vss, err := makeState(ctx, config, logger, 4)
require.NoError(t, err)
vs2, vs3, vs4 := vss[1], vss[2], vss[3]
height, round := cs1.Height, cs1.Round
@@ -2014,10 +2027,11 @@ func TestWaitingTimeoutProposeOnNewRound(t *testing.T) {
// P0 jump to higher round, precommit and start precommit wait
func TestRoundSkipOnNilPolkaFromHigherRound(t *testing.T) {
config := configSetup(t)
logger := log.TestingLogger()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
cs1, vss, err := randState(ctx, config, log.TestingLogger(), 4)
cs1, vss, err := makeState(ctx, config, logger, 4)
require.NoError(t, err)
vs2, vs3, vs4 := vss[1], vss[2], vss[3]
height, round := cs1.Height, cs1.Round
@@ -2055,10 +2069,11 @@ func TestRoundSkipOnNilPolkaFromHigherRound(t *testing.T) {
// P0 wait for timeoutPropose to expire before sending prevote.
func TestWaitTimeoutProposeOnNilPolkaForTheCurrentRound(t *testing.T) {
config := configSetup(t)
logger := log.TestingLogger()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
cs1, vss, err := randState(ctx, config, log.TestingLogger(), 4)
cs1, vss, err := makeState(ctx, config, logger, 4)
require.NoError(t, err)
vs2, vs3, vs4 := vss[1], vss[2], vss[3]
height, round := cs1.Height, int32(1)
@@ -2087,10 +2102,11 @@ func TestWaitTimeoutProposeOnNilPolkaForTheCurrentRound(t *testing.T) {
// P0 emit NewValidBlock event upon receiving 2/3+ Precommit for B but hasn't received block B yet
func TestEmitNewValidBlockEventOnCommitWithoutBlock(t *testing.T) {
config := configSetup(t)
logger := log.TestingLogger()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
cs1, vss, err := randState(ctx, config, log.TestingLogger(), 4)
cs1, vss, err := makeState(ctx, config, logger, 4)
require.NoError(t, err)
vs2, vs3, vs4 := vss[1], vss[2], vss[3]
height, round := cs1.Height, int32(1)
@@ -2126,10 +2142,11 @@ func TestEmitNewValidBlockEventOnCommitWithoutBlock(t *testing.T) {
// After receiving block, it executes block and moves to the next height.
func TestCommitFromPreviousRound(t *testing.T) {
config := configSetup(t)
logger := log.TestingLogger()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
cs1, vss, err := randState(ctx, config, log.TestingLogger(), 4)
cs1, vss, err := makeState(ctx, config, logger, 4)
require.NoError(t, err)
vs2, vs3, vs4 := vss[1], vss[2], vss[3]
height, round := cs1.Height, int32(1)
@@ -2184,11 +2201,12 @@ func (n *fakeTxNotifier) Notify() {
// start of the next round
func TestStartNextHeightCorrectlyAfterTimeout(t *testing.T) {
config := configSetup(t)
logger := log.TestingLogger()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
config.Consensus.SkipTimeoutCommit = false
cs1, vss, err := randState(ctx, config, log.TestingLogger(), 4)
cs1, vss, err := makeState(ctx, config, logger, 4)
require.NoError(t, err)
cs1.txNotifier = &fakeTxNotifier{ch: make(chan struct{})}
@@ -2250,11 +2268,12 @@ func TestStartNextHeightCorrectlyAfterTimeout(t *testing.T) {
func TestResetTimeoutPrecommitUponNewHeight(t *testing.T) {
config := configSetup(t)
logger := log.TestingLogger()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
config.Consensus.SkipTimeoutCommit = false
cs1, vss, err := randState(ctx, config, log.TestingLogger(), 4)
cs1, vss, err := makeState(ctx, config, logger, 4)
require.NoError(t, err)
vs2, vs3, vs4 := vss[1], vss[2], vss[3]
@@ -2397,10 +2416,11 @@ func TestStateSlashing_Precommits(t *testing.T) {
// we receive a final precommit after going into next round, but others might have gone to commit already!
func TestStateHalt1(t *testing.T) {
config := configSetup(t)
logger := log.TestingLogger()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
cs1, vss, err := randState(ctx, config, log.TestingLogger(), 4)
cs1, vss, err := makeState(ctx, config, logger, 4)
require.NoError(t, err)
vs2, vs3, vs4 := vss[1], vss[2], vss[3]
height, round := cs1.Height, cs1.Round
@@ -2468,14 +2488,14 @@ func TestStateHalt1(t *testing.T) {
func TestStateOutputsBlockPartsStats(t *testing.T) {
config := configSetup(t)
logger := log.TestingLogger()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// create dummy peer
cs, _, err := randState(ctx, config, log.TestingLogger(), 1)
cs, _, err := makeState(ctx, config, logger, 1)
require.NoError(t, err)
peerID, err := types.NewNodeID("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA")
require.NoError(t, err)
// 1) new block part
parts := types.NewPartSetFromData(tmrand.Bytes(100), 10)
@@ -2517,10 +2537,11 @@ func TestStateOutputsBlockPartsStats(t *testing.T) {
func TestStateOutputVoteStats(t *testing.T) {
config := configSetup(t)
logger := log.TestingLogger()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
cs, vss, err := randState(ctx, config, log.TestingLogger(), 2)
cs, vss, err := makeState(ctx, config, logger, 2)
require.NoError(t, err)
// create dummy peer
peerID, err := types.NewNodeID("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA")
@@ -2556,10 +2577,11 @@ func TestStateOutputVoteStats(t *testing.T) {
func TestSignSameVoteTwice(t *testing.T) {
config := configSetup(t)
logger := log.TestingLogger()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
_, vss, err := randState(ctx, config, log.TestingLogger(), 2)
_, vss, err := makeState(ctx, config, logger, 2)
require.NoError(t, err)
randBytes := tmrand.Bytes(tmhash.Size)

View File

@@ -32,7 +32,7 @@ func TestPeerCatchupRounds(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
valSet, privVals := factory.RandValidatorSet(10, 1)
valSet, privVals := factory.ValidatorSet(10, 1)
hvs := NewHeightVoteSet(cfg.ChainID(), 1, valSet)

View File

@@ -38,7 +38,7 @@ func TestEvidencePoolBasic(t *testing.T) {
blockStore = &mocks.BlockStore{}
)
valSet, privVals := factory.RandValidatorSet(1, 10)
valSet, privVals := factory.ValidatorSet(1, 10)
blockStore.On("LoadBlockMeta", mock.AnythingOfType("int64")).Return(
&types.BlockMeta{Header: types.Header{Time: defaultEvidenceTime}},

View File

@@ -190,7 +190,7 @@ func TestVerify_ForwardLunaticAttack(t *testing.T) {
}
func TestVerifyLightClientAttack_Equivocation(t *testing.T) {
conflictingVals, conflictingPrivVals := factory.RandValidatorSet(5, 10)
conflictingVals, conflictingPrivVals := factory.ValidatorSet(5, 10)
conflictingHeader, err := factory.MakeHeader(&types.Header{
ChainID: evidenceChainID,
@@ -285,7 +285,7 @@ func TestVerifyLightClientAttack_Equivocation(t *testing.T) {
func TestVerifyLightClientAttack_Amnesia(t *testing.T) {
var height int64 = 10
conflictingVals, conflictingPrivVals := factory.RandValidatorSet(5, 10)
conflictingVals, conflictingPrivVals := factory.ValidatorSet(5, 10)
conflictingHeader, err := factory.MakeHeader(&types.Header{
ChainID: evidenceChainID,
@@ -474,14 +474,14 @@ func makeLunaticEvidence(
totalVals, byzVals, phantomVals int,
commonTime, attackTime time.Time,
) (ev *types.LightClientAttackEvidence, trusted *types.LightBlock, common *types.LightBlock) {
commonValSet, commonPrivVals := factory.RandValidatorSet(totalVals, defaultVotingPower)
commonValSet, commonPrivVals := factory.ValidatorSet(totalVals, defaultVotingPower)
require.Greater(t, totalVals, byzVals)
// extract out the subset of byzantine validators in the common validator set
byzValSet, byzPrivVals := commonValSet.Validators[:byzVals], commonPrivVals[:byzVals]
phantomValSet, phantomPrivVals := factory.RandValidatorSet(phantomVals, defaultVotingPower)
phantomValSet, phantomPrivVals := factory.ValidatorSet(phantomVals, defaultVotingPower)
conflictingVals := phantomValSet.Copy()
require.NoError(t, conflictingVals.UpdateWithChangeSet(byzValSet))
@@ -537,7 +537,7 @@ func makeLunaticEvidence(
ValidatorSet: commonValSet,
}
trustedBlockID := factory.MakeBlockIDWithHash(trustedHeader.Hash())
trustedVals, privVals := factory.RandValidatorSet(totalVals, defaultVotingPower)
trustedVals, privVals := factory.ValidatorSet(totalVals, defaultVotingPower)
trustedVoteSet := types.NewVoteSet(evidenceChainID, height, 1, tmproto.SignedMsgType(2), trustedVals)
trustedCommit, err := factory.MakeCommit(trustedBlockID, height, 1, trustedVoteSet, privVals, defaultEvidenceTime)
require.NoError(t, err)

View File

@@ -3,6 +3,7 @@ package state_test
import (
"bytes"
"fmt"
"math/rand"
"time"
dbm "github.com/tendermint/tm-db"
@@ -246,7 +247,7 @@ func makeRandomStateFromValidatorSet(
func makeRandomStateFromConsensusParams(consensusParams *types.ConsensusParams,
height, lastHeightConsensusParamsChanged int64) sm.State {
val, _ := factory.RandValidator(true, 10)
val, _ := factory.Validator(10 + int64(rand.Uint32()))
valSet := types.NewValidatorSet([]*types.Validator{val})
return sm.State{
LastBlockHeight: height - 1,

View File

@@ -102,7 +102,7 @@ func TestRollbackDifferentStateHeight(t *testing.T) {
func setupStateStore(t *testing.T, height int64) state.Store {
stateStore := state.NewStore(dbm.NewMemDB())
valSet, _ := factory.RandValidatorSet(5, 10)
valSet, _ := factory.ValidatorSet(5, 10)
params := types.DefaultConsensusParams()
params.Version.AppVersion = 10

View File

@@ -2,6 +2,7 @@ package state_test
import (
"fmt"
"math/rand"
"os"
"testing"
@@ -28,9 +29,9 @@ const (
func TestStoreBootstrap(t *testing.T) {
stateDB := dbm.NewMemDB()
stateStore := sm.NewStore(stateDB)
val, _ := factory.RandValidator(true, 10)
val2, _ := factory.RandValidator(true, 10)
val3, _ := factory.RandValidator(true, 10)
val, _ := factory.Validator(10 + int64(rand.Uint32()))
val2, _ := factory.Validator(10 + int64(rand.Uint32()))
val3, _ := factory.Validator(10 + int64(rand.Uint32()))
vals := types.NewValidatorSet([]*types.Validator{val, val2, val3})
bootstrapState := makeRandomStateFromValidatorSet(vals, 100, 100)
err := stateStore.Bootstrap(bootstrapState)
@@ -54,9 +55,9 @@ func TestStoreBootstrap(t *testing.T) {
func TestStoreLoadValidators(t *testing.T) {
stateDB := dbm.NewMemDB()
stateStore := sm.NewStore(stateDB)
val, _ := factory.RandValidator(true, 10)
val2, _ := factory.RandValidator(true, 10)
val3, _ := factory.RandValidator(true, 10)
val, _ := factory.Validator(10 + int64(rand.Uint32()))
val2, _ := factory.Validator(10 + int64(rand.Uint32()))
val3, _ := factory.Validator(10 + int64(rand.Uint32()))
vals := types.NewValidatorSet([]*types.Validator{val, val2, val3})
// 1) LoadValidators loads validators using a height where they were last changed

View File

@@ -274,7 +274,7 @@ loop:
}
func mockLBResp(t *testing.T, peer types.NodeID, height int64, time time.Time) lightBlockResponse {
vals, pv := factory.RandValidatorSet(3, 10)
vals, pv := factory.ValidatorSet(3, 10)
_, _, lb := mockLB(t, height, time, factory.MakeBlockID(), vals, pv)
return lightBlockResponse{
block: lb,

View File

@@ -423,7 +423,7 @@ func TestReactor_LightBlockResponse(t *testing.T) {
h := factory.MakeRandomHeader()
h.Height = height
blockID := factory.MakeBlockIDWithHash(h.Hash())
vals, pv := factory.RandValidatorSet(1, 10)
vals, pv := factory.ValidatorSet(1, 10)
vote, err := factory.MakeVote(pv[0], h.ChainID, 0, h.Height, 0, 2,
blockID, factory.DefaultTestTime)
require.NoError(t, err)
@@ -714,7 +714,7 @@ func handleLightBlockRequests(
} else {
switch errorCount % 3 {
case 0: // send a different block
vals, pv := factory.RandValidatorSet(3, 10)
vals, pv := factory.ValidatorSet(3, 10)
_, _, lb := mockLB(t, int64(msg.Height), factory.DefaultTestTime, factory.MakeBlockID(), vals, pv)
differntLB, err := lb.ToProto()
require.NoError(t, err)
@@ -782,7 +782,7 @@ func buildLightBlockChain(t *testing.T, fromHeight, toHeight int64, startTime ti
chain := make(map[int64]*types.LightBlock, toHeight-fromHeight)
lastBlockID := factory.MakeBlockID()
blockTime := startTime.Add(time.Duration(fromHeight-toHeight) * time.Minute)
vals, pv := factory.RandValidatorSet(3, 10)
vals, pv := factory.ValidatorSet(3, 10)
for height := fromHeight; height < toHeight; height++ {
vals, pv, chain[height] = mockLB(t, height, blockTime, lastBlockID, vals, pv)
lastBlockID = factory.MakeBlockIDWithHash(chain[height].Header.Hash())
@@ -800,7 +800,7 @@ func mockLB(t *testing.T, height int64, time time.Time, lastBlockID types.BlockI
Time: time,
})
require.NoError(t, err)
nextVals, nextPrivVals := factory.RandValidatorSet(3, 10)
nextVals, nextPrivVals := factory.ValidatorSet(3, 10)
header.ValidatorsHash = currentVals.Hash()
header.NextValidatorsHash = nextVals.Hash()
header.ConsensusHash = types.DefaultConsensusParams().HashConsensusParams()

View File

@@ -1,35 +1,33 @@
package factory
import (
"sort"
"time"
"github.com/tendermint/tendermint/config"
tmtime "github.com/tendermint/tendermint/libs/time"
cfg "github.com/tendermint/tendermint/config"
"github.com/tendermint/tendermint/types"
)
func RandGenesisDoc(
cfg *config.Config,
numValidators int,
randPower bool,
minPower int64) (*types.GenesisDoc, []types.PrivValidator) {
func GenesisDoc(
config *cfg.Config,
time time.Time,
validators []*types.Validator,
consensusParams *types.ConsensusParams,
) *types.GenesisDoc {
validators := make([]types.GenesisValidator, numValidators)
privValidators := make([]types.PrivValidator, numValidators)
for i := 0; i < numValidators; i++ {
val, privVal := RandValidator(randPower, minPower)
validators[i] = types.GenesisValidator{
PubKey: val.PubKey,
Power: val.VotingPower,
genesisValidators := make([]types.GenesisValidator, len(validators))
for i := range validators {
genesisValidators[i] = types.GenesisValidator{
Power: validators[i].VotingPower,
PubKey: validators[i].PubKey,
}
privValidators[i] = privVal
}
sort.Sort(types.PrivValidatorsByAddress(privValidators))
return &types.GenesisDoc{
GenesisTime: tmtime.Now(),
InitialHeight: 1,
ChainID: cfg.ChainID(),
Validators: validators,
}, privValidators
GenesisTime: time,
InitialHeight: 1,
ChainID: config.ChainID(),
Validators: genesisValidators,
ConsensusParams: consensusParams,
}
}

View File

@@ -3,35 +3,29 @@ package factory
import (
"context"
"fmt"
"math/rand"
"sort"
"github.com/tendermint/tendermint/types"
)
func RandValidator(randPower bool, minPower int64) (*types.Validator, types.PrivValidator) {
func Validator(votingPower int64) (*types.Validator, types.PrivValidator) {
privVal := types.NewMockPV()
votePower := minPower
if randPower {
// nolint:gosec // G404: Use of weak random number generator
votePower += int64(rand.Uint32())
}
pubKey, err := privVal.GetPubKey(context.Background())
if err != nil {
panic(fmt.Errorf("could not retrieve pubkey %w", err))
}
val := types.NewValidator(pubKey, votePower)
val := types.NewValidator(pubKey, votingPower)
return val, privVal
}
func RandValidatorSet(numValidators int, votingPower int64) (*types.ValidatorSet, []types.PrivValidator) {
func ValidatorSet(numValidators int, votingPower int64) (*types.ValidatorSet, []types.PrivValidator) {
var (
valz = make([]*types.Validator, numValidators)
privValidators = make([]types.PrivValidator, numValidators)
)
for i := 0; i < numValidators; i++ {
val, privValidator := RandValidator(false, votingPower)
val, privValidator := Validator(votingPower)
valz[i] = val
privValidators[i] = privValidator
}

View File

@@ -112,7 +112,7 @@ func TestValidateTrustOptions(t *testing.T) {
func TestClient_SequentialVerification(t *testing.T) {
newKeys := genPrivKeys(4)
newVals := newKeys.ToValidators(10, 1)
differentVals, _ := factory.RandValidatorSet(10, 100)
differentVals, _ := factory.ValidatorSet(10, 100)
testCases := []struct {
name string
@@ -865,7 +865,7 @@ func TestClientRemovesWitnessIfItSendsUsIncorrectHeader(t *testing.T) {
}
func TestClient_TrustedValidatorSet(t *testing.T) {
differentVals, _ := factory.RandValidatorSet(10, 100)
differentVals, _ := factory.ValidatorSet(10, 100)
mockBadValSetNode := mockNodeFromHeadersAndVals(
map[int64]*types.SignedHeader{
1: h1,

View File

@@ -183,7 +183,7 @@ func Test_Concurrency(t *testing.T) {
}
func randLightBlock(height int64) *types.LightBlock {
vals, _ := factory.RandValidatorSet(2, 1)
vals, _ := factory.ValidatorSet(2, 1)
return &types.LightBlock{
SignedHeader: &types.SignedHeader{
Header: &types.Header{

View File

@@ -737,7 +737,8 @@ func loadStatefromGenesis(t *testing.T) sm.State {
require.NoError(t, err)
require.True(t, loadedState.IsEmpty())
genDoc, _ := factory.RandGenesisDoc(cfg, 0, false, 10)
valSet, _ := factory.ValidatorSet(0, 10)
genDoc := factory.GenesisDoc(cfg, time.Now(), valSet.Validators, nil)
state, err := loadStateFromDBOrGenesisDocProvider(
stateStore,

View File

@@ -286,7 +286,7 @@ func makeBlockID(hash []byte, partSetSize uint32, partSetHash []byte) types.Bloc
func mutateValidatorSet(privVals []types.MockPV, vals *types.ValidatorSet,
) ([]types.PrivValidator, *types.ValidatorSet, error) {
newVal, newPrivVal := factory.RandValidator(false, 10)
newVal, newPrivVal := factory.Validator(10)
var newVals *types.ValidatorSet
if vals.Size() > 2 {