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 b20bad14ae
commit 7e17892650
23 changed files with 212 additions and 214 deletions

View File

@@ -207,7 +207,8 @@ func TestReactor_AbruptDisconnect(t *testing.T) {
require.NoError(t, err)
defer os.RemoveAll(cfg.RootDir)
genDoc, privVals := factory.RandGenesisDoc(ctx, t, cfg, 1, false, 30)
valSet, privVals := factory.ValidatorSet(t, 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)
@@ -246,7 +247,8 @@ func TestReactor_SyncTime(t *testing.T) {
require.NoError(t, err)
defer os.RemoveAll(cfg.RootDir)
genDoc, privVals := factory.RandGenesisDoc(ctx, t, cfg, 1, false, 30)
valSet, privVals := factory.ValidatorSet(t, 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)
@@ -271,10 +273,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(ctx, t, cfg, 1, false, 30)
valSet, privVals := factory.ValidatorSet(t, 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)
@@ -326,7 +328,8 @@ func TestReactor_BadBlockStopsPeer(t *testing.T) {
defer os.RemoveAll(cfg.RootDir)
maxBlockHeight := int64(48)
genDoc, privVals := factory.RandGenesisDoc(ctx, t, cfg, 1, false, 30)
valSet, privVals := factory.ValidatorSet(t, 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)
@@ -360,7 +363,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(ctx, t, cfg, 1, false, 30)
valSet, otherPrivVals := factory.ValidatorSet(t, 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

@@ -46,7 +46,8 @@ func TestByzantinePrevoteEquivocation(t *testing.T) {
tickerFunc := newMockTickerFunc(true)
appFunc := newKVStore
genDoc, privVals := factory.RandGenesisDoc(ctx, t, config, nValidators, false, 30)
valSet, privVals := factory.ValidatorSet(t, 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"
"github.com/tendermint/tendermint/internal/mempool"
@@ -493,17 +494,12 @@ func loadPrivValidator(t *testing.T, cfg *config.Config) *privval.FilePV {
return privValidator
}
func randState(
ctx context.Context,
t *testing.T,
cfg *config.Config,
logger log.Logger,
nValidators int,
) (*State, []*validatorStub) {
func makeState(ctx context.Context, t *testing.T, cfg *config.Config, logger log.Logger, nValidators int) (*State, []*validatorStub) {
t.Helper()
// Get State
state, privVals := randGenesisState(ctx, t, cfg, nValidators, false, 10)
state, privVals := makeGenesisState(t, cfg, genesisStateArgs{
Validators: nValidators,
})
vss := make([]*validatorStub, nValidators)
@@ -728,7 +724,7 @@ func consensusLogger() log.Logger {
return log.TestingLogger().With("module", "consensus")
}
func randConsensusState(
func makeConsensusState(
ctx context.Context,
t *testing.T,
cfg *config.Config,
@@ -740,7 +736,8 @@ func randConsensusState(
) ([]*State, cleanupFunc) {
t.Helper()
genDoc, privVals := factory.RandGenesisDoc(ctx, t, cfg, nValidators, false, 30)
valSet, privVals := factory.ValidatorSet(t, nValidators, 30)
genDoc := factory.GenesisDoc(cfg, time.Now(), valSet.Validators, nil)
css := make([]*State, nValidators)
logger := consensusLogger()
@@ -800,7 +797,8 @@ func randConsensusNetWithPeers(
) ([]*State, *types.GenesisDoc, *config.Config, cleanupFunc) {
t.Helper()
genDoc, privVals := factory.RandGenesisDoc(ctx, t, cfg, nValidators, false, testMinPower)
valSet, privVals := factory.ValidatorSet(t, nValidators, testMinPower)
genDoc := factory.GenesisDoc(cfg, time.Now(), valSet.Validators, nil)
css := make([]*State, nPeers)
t.Helper()
logger := consensusLogger()
@@ -850,18 +848,30 @@ func randConsensusNetWithPeers(
}
}
func randGenesisState(
ctx context.Context,
t *testing.T,
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(ctx, t, cfg, numValidators, randPower, minPower)
s0, err := sm.MakeGenesisState(genDoc)
require.NoError(t, err)
func makeGenesisState(t *testing.T, config *cfg.Config, args genesisStateArgs) (sm.State, []types.PrivValidator) {
t.Helper()
if args.Power == 0 {
args.Power = 1
}
if args.Validators == 0 {
args.Power = 4
}
valSet, privValidators := factory.ValidatorSet(t, 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

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

View File

@@ -326,7 +326,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)
@@ -383,7 +383,8 @@ func TestReactorWithEvidence(t *testing.T) {
tickerFunc := newMockTickerFunc(true)
appFunc := newKVStore
genDoc, privVals := factory.RandGenesisDoc(ctx, t, cfg, n, false, 30)
valSet, privVals := factory.ValidatorSet(t, n, 30)
genDoc := factory.GenesisDoc(cfg, time.Now(), valSet.Validators, nil)
states := make([]*State, n)
logger := consensusLogger()
@@ -486,8 +487,7 @@ func TestReactorCreatesBlockWhenEmptyBlocksFalse(t *testing.T) {
cfg := configSetup(t)
n := 4
states, cleanup := randConsensusState(
ctx,
states, cleanup := makeConsensusState(ctx,
t,
cfg,
n,
@@ -543,7 +543,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)
@@ -608,8 +608,7 @@ func TestReactorVotingPowerChange(t *testing.T) {
cfg := configSetup(t)
n := 4
states, cleanup := randConsensusState(
ctx,
states, cleanup := makeConsensusState(ctx,
t,
cfg,
n,

View File

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

View File

@@ -66,9 +66,9 @@ func TestStateProposerSelection0(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
config := configSetup(t)
logger := log.TestingLogger()
cs1, vss := randState(ctx, t, config, log.TestingLogger(), 4)
cs1, vss := makeState(ctx, t, config, logger, 4)
height, round := cs1.Height, cs1.Round
newRoundCh := subscribe(ctx, t, cs1.eventBus, types.EventQueryNewRound)
@@ -116,12 +116,11 @@ 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 := randState(ctx, t, config, log.TestingLogger(), 4) // test needs more work for more than 3 validators
cs1, vss := makeState(ctx, t, config, logger, 4) // test needs more work for more than 3 validators
height := cs1.Height
newRoundCh := subscribe(ctx, t, cs1.eventBus, types.EventQueryNewRound)
@@ -156,11 +155,11 @@ 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, _ := randState(ctx, t, config, log.TestingLogger(), 1)
cs, _ := makeState(ctx, t, config, logger, 1)
cs.SetPrivValidator(ctx, nil)
height, round := cs.Height, cs.Round
@@ -180,10 +179,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, _ := randState(ctx, t, config, log.TestingLogger(), 1)
cs, _ := makeState(ctx, t, config, logger, 1)
height, round := cs.Height, cs.Round
// Listen for propose timeout event
@@ -214,10 +214,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 := randState(ctx, t, config, log.TestingLogger(), 2)
cs1, vss := makeState(ctx, t, config, logger, 2)
height, round := cs1.Height, cs1.Round
vs2 := vss[1]
@@ -284,10 +285,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 := randState(ctx, t, config, log.TestingLogger(), 2)
cs1, vss := makeState(ctx, t, config, logger, 2)
cs1.state.ConsensusParams.Block.MaxBytes = 2000
height, round := cs1.Height, cs1.Round
vs2 := vss[1]
@@ -363,7 +365,7 @@ func TestStateFullRound1(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
cs, vss := randState(ctx, t, config, logger, 1)
cs, vss := makeState(ctx, t, config, logger, 1)
height, round := cs.Height, cs.Round
// NOTE: buffer capacity of 0 ensures we can validate prevote and last commit
@@ -404,10 +406,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 := randState(ctx, t, config, log.TestingLogger(), 1)
cs, vss := makeState(ctx, t, config, logger, 1)
height, round := cs.Height, cs.Round
voteCh := subscribe(ctx, t, cs.eventBus, types.EventQueryVote)
@@ -426,10 +429,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 := randState(ctx, t, config, log.TestingLogger(), 2)
cs1, vss := makeState(ctx, t, config, logger, 2)
vs2 := vss[1]
height, round := cs1.Height, cs1.Round
@@ -470,10 +474,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 := randState(ctx, t, config, log.TestingLogger(), 2)
cs1, vss := makeState(ctx, t, config, logger, 2)
vs2 := vss[1]
height, round := cs1.Height, cs1.Round
@@ -616,8 +621,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, _ := randState(ctx, t, config, log.TestingLogger(), 2)
cs2, _ := makeState(ctx, t, config, logger, 2) // needed so generated block is different than locked block
// before we time out into new round, set next proposal block
prop, propBlock := decideProposal(ctx, t, cs2, vs2, vs2.Height, vs2.Round+1)
if prop == nil || propBlock == nil {
@@ -684,7 +688,7 @@ func TestStateLock_POLUpdateLock(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
cs1, vss := randState(ctx, t, config, logger, 4)
cs1, vss := makeState(ctx, t, config, logger, 4)
vs2, vs3, vs4 := vss[1], vss[2], vss[3]
height, round := cs1.Height, cs1.Round
@@ -788,8 +792,9 @@ func TestStateLock_POLRelock(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
config := configSetup(t)
logger := log.TestingLogger()
cs1, vss := randState(ctx, t, config, log.TestingLogger(), 4)
cs1, vss := makeState(ctx, t, config, logger, 4)
vs2, vs3, vs4 := vss[1], vss[2], vss[3]
height, round := cs1.Height, cs1.Round
@@ -887,8 +892,9 @@ func TestStateLock_PrevoteNilWhenLockedAndMissProposal(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
config := configSetup(t)
logger := log.TestingLogger()
cs1, vss := randState(ctx, t, config, log.TestingLogger(), 4)
cs1, vss := makeState(ctx, t, config, logger, 4)
vs2, vs3, vs4 := vss[1], vss[2], vss[3]
height, round := cs1.Height, cs1.Round
@@ -975,7 +981,7 @@ func TestStateLock_PrevoteNilWhenLockedAndDifferentProposal(t *testing.T) {
state.
*/
cs1, vss := randState(ctx, t, config, logger, 4)
cs1, vss := makeState(ctx, t, config, logger, 4)
vs2, vs3, vs4 := vss[1], vss[2], vss[3]
height, round := cs1.Height, cs1.Round
@@ -1076,7 +1082,7 @@ func TestStateLock_POLDoesNotUnlock(t *testing.T) {
state.
*/
cs1, vss := randState(ctx, t, config, log.TestingLogger(), 4)
cs1, vss := makeState(ctx, t, config, logger, 4)
vs2, vs3, vs4 := vss[1], vss[2], vss[3]
height, round := cs1.Height, cs1.Round
@@ -1212,8 +1218,7 @@ func TestStateLock_MissingProposalWhenPOLSeenDoesNotUpdateLock(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
cs1, vss := randState(ctx, t, config, logger, 4)
cs1, vss := makeState(ctx, t, config, logger, 4)
vs2, vs3, vs4 := vss[1], vss[2], vss[3]
height, round := cs1.Height, cs1.Round
@@ -1300,8 +1305,9 @@ func TestStateLock_DoesNotLockOnOldProposal(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
config := configSetup(t)
logger := log.TestingLogger()
cs1, vss := randState(ctx, t, config, log.TestingLogger(), 4)
cs1, vss := makeState(ctx, t, config, logger, 4)
vs2, vs3, vs4 := vss[1], vss[2], vss[3]
height, round := cs1.Height, cs1.Round
@@ -1377,7 +1383,7 @@ func TestStateLock_POLSafety1(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
cs1, vss := randState(ctx, t, config, log.TestingLogger(), 4)
cs1, vss := makeState(ctx, t, config, logger, 4)
vs2, vs3, vs4 := vss[1], vss[2], vss[3]
height, round := cs1.Height, cs1.Round
@@ -1501,7 +1507,7 @@ func TestStateLock_POLSafety2(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
cs1, vss := randState(ctx, t, config, logger, 4)
cs1, vss := makeState(ctx, t, config, logger, 4)
vs2, vs3, vs4 := vss[1], vss[2], vss[3]
height, round := cs1.Height, cs1.Round
@@ -1601,7 +1607,7 @@ func TestState_PrevotePOLFromPreviousRound(t *testing.T) {
config := configSetup(t)
logger := log.TestingLogger()
cs1, vss := randState(ctx, t, config, logger, 4)
cs1, vss := makeState(ctx, t, config, logger, 4)
vs2, vs3, vs4 := vss[1], vss[2], vss[3]
height, round := cs1.Height, cs1.Round
@@ -1738,11 +1744,12 @@ func TestState_PrevotePOLFromPreviousRound(t *testing.T) {
// What we want:
// P0 proposes B0 at R3.
func TestProposeValidBlock(t *testing.T) {
cfg := configSetup(t)
config := configSetup(t)
logger := log.TestingLogger()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
cs1, vss := randState(ctx, t, cfg, log.TestingLogger(), 4)
cs1, vss := makeState(ctx, t, config, logger, 4)
vs2, vs3, vs4 := vss[1], vss[2], vss[3]
height, round := cs1.Height, cs1.Round
@@ -1772,7 +1779,7 @@ func TestProposeValidBlock(t *testing.T) {
// the others sign a polka
bps, err := propBlock.MakePartSet(partSize)
require.NoError(t, err)
signAddVotes(ctx, t, cfg, cs1, tmproto.PrevoteType,
signAddVotes(ctx, t, config, cs1, tmproto.PrevoteType,
propBlockHash, bps.Header(), vs2,
vs3, vs4)
@@ -1781,7 +1788,7 @@ func TestProposeValidBlock(t *testing.T) {
validatePrecommit(ctx, t, cs1, round, round, vss[0], propBlockHash, propBlockHash)
signAddVotes(ctx, t, cfg, cs1, tmproto.PrecommitType, nil, types.PartSetHeader{}, vs2, vs3, vs4)
signAddVotes(ctx, t, config, cs1, tmproto.PrecommitType, nil, types.PartSetHeader{}, vs2, vs3, vs4)
ensureNewTimeout(t, timeoutWaitCh, height, round, cs1.config.Precommit(round).Nanoseconds())
@@ -1798,7 +1805,7 @@ func TestProposeValidBlock(t *testing.T) {
ensurePrevote(t, voteCh, height, round)
validatePrevote(ctx, t, cs1, round, vss[0], nil)
signAddVotes(ctx, t, cfg, cs1, tmproto.PrevoteType, nil, types.PartSetHeader{}, vs2, vs3, vs4)
signAddVotes(ctx, t, config, cs1, tmproto.PrevoteType, nil, types.PartSetHeader{}, vs2, vs3, vs4)
ensurePrecommit(t, voteCh, height, round)
// we should have precommitted nil during this round because we received
@@ -1808,7 +1815,7 @@ func TestProposeValidBlock(t *testing.T) {
incrementRound(vs2, vs3, vs4)
incrementRound(vs2, vs3, vs4)
signAddVotes(ctx, t, cfg, cs1, tmproto.PrecommitType, nil, types.PartSetHeader{}, vs2, vs3, vs4)
signAddVotes(ctx, t, config, cs1, tmproto.PrecommitType, nil, types.PartSetHeader{}, vs2, vs3, vs4)
round += 2 // increment by multiple rounds
@@ -1833,11 +1840,12 @@ func TestProposeValidBlock(t *testing.T) {
// What we want:
// P0 miss to lock B but set valid block to B after receiving delayed prevote.
func TestSetValidBlockOnDelayedPrevote(t *testing.T) {
cfg := configSetup(t)
config := configSetup(t)
logger := log.TestingLogger()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
cs1, vss := randState(ctx, t, cfg, log.TestingLogger(), 4)
cs1, vss := makeState(ctx, t, config, logger, 4)
vs2, vs3, vs4 := vss[1], vss[2], vss[3]
height, round := cs1.Height, cs1.Round
@@ -1867,10 +1875,10 @@ func TestSetValidBlockOnDelayedPrevote(t *testing.T) {
validatePrevote(ctx, t, cs1, round, vss[0], propBlockHash)
// vs2 send prevote for propBlock
signAddVotes(ctx, t, cfg, cs1, tmproto.PrevoteType, propBlockHash, propBlockParts.Header(), vs2)
signAddVotes(ctx, t, config, cs1, tmproto.PrevoteType, propBlockHash, propBlockParts.Header(), vs2)
// vs3 send prevote nil
signAddVotes(ctx, t, cfg, cs1, tmproto.PrevoteType, nil, types.PartSetHeader{}, vs3)
signAddVotes(ctx, t, config, cs1, tmproto.PrevoteType, nil, types.PartSetHeader{}, vs3)
ensureNewTimeout(t, timeoutWaitCh, height, round, cs1.config.Prevote(round).Nanoseconds())
@@ -1885,7 +1893,7 @@ func TestSetValidBlockOnDelayedPrevote(t *testing.T) {
assert.True(t, rs.ValidRound == -1)
// vs2 send (delayed) prevote for propBlock
signAddVotes(ctx, t, cfg, cs1, tmproto.PrevoteType, propBlockHash, propBlockParts.Header(), vs4)
signAddVotes(ctx, t, config, cs1, tmproto.PrevoteType, propBlockHash, propBlockParts.Header(), vs4)
ensureNewValidBlock(t, validBlockCh, height, round)
@@ -1901,10 +1909,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 := randState(ctx, t, config, log.TestingLogger(), 4)
cs1, vss := makeState(ctx, t, config, logger, 4)
vs2, vs3, vs4 := vss[1], vss[2], vss[3]
height, round := cs1.Height, cs1.Round
@@ -1961,12 +1970,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 := randState(ctx, t, config, log.TestingLogger(), 4)
cs1, vss := makeState(ctx, t, config, logger, 4)
vs2, vs3, vs4 := vss[1], vss[2], vss[3]
height, round := cs1.Height, cs1.Round
@@ -1988,10 +1997,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 := randState(ctx, t, config, log.TestingLogger(), 4)
cs1, vss := makeState(ctx, t, config, logger, 4)
vs2, vs3, vs4 := vss[1], vss[2], vss[3]
height, round := cs1.Height, cs1.Round
@@ -2028,10 +2038,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 := randState(ctx, t, config, log.TestingLogger(), 4)
cs1, vss := makeState(ctx, t, config, logger, 4)
vs2, vs3, vs4 := vss[1], vss[2], vss[3]
height, round := cs1.Height, cs1.Round
@@ -2068,11 +2079,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 := randState(ctx, t, config, log.TestingLogger(), 4)
cs1, vss := makeState(ctx, t, config, logger, 4)
vs2, vs3, vs4 := vss[1], vss[2], vss[3]
height, round := cs1.Height, int32(1)
@@ -2100,10 +2111,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 := randState(ctx, t, config, log.TestingLogger(), 4)
cs1, vss := makeState(ctx, t, config, logger, 4)
vs2, vs3, vs4 := vss[1], vss[2], vss[3]
height, round := cs1.Height, int32(1)
@@ -2139,10 +2151,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 := randState(ctx, t, config, log.TestingLogger(), 4)
cs1, vss := makeState(ctx, t, config, logger, 4)
vs2, vs3, vs4 := vss[1], vss[2], vss[3]
height, round := cs1.Height, int32(1)
@@ -2197,11 +2210,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 := randState(ctx, t, config, log.TestingLogger(), 4)
cs1, vss := makeState(ctx, t, config, logger, 4)
cs1.txNotifier = &fakeTxNotifier{ch: make(chan struct{})}
vs2, vs3, vs4 := vss[1], vss[2], vss[3]
@@ -2262,11 +2276,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 := randState(ctx, t, config, log.TestingLogger(), 4)
cs1, vss := makeState(ctx, t, config, logger, 4)
vs2, vs3, vs4 := vss[1], vss[2], vss[3]
height, round := cs1.Height, cs1.Round
@@ -2409,10 +2424,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 := randState(ctx, t, config, log.TestingLogger(), 4)
cs1, vss := makeState(ctx, t, config, logger, 4)
vs2, vs3, vs4 := vss[1], vss[2], vss[3]
height, round := cs1.Height, cs1.Round
partSize := types.BlockPartSizeBytes
@@ -2480,11 +2496,12 @@ 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, _ := randState(ctx, t, config, log.TestingLogger(), 1)
cs, _ := makeState(ctx, t, config, logger, 1)
peerID, err := types.NewNodeID("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA")
require.NoError(t, err)
@@ -2528,10 +2545,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 := randState(ctx, t, config, log.TestingLogger(), 2)
cs, vss := makeState(ctx, t, config, logger, 2)
// create dummy peer
peerID, err := types.NewNodeID("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA")
require.NoError(t, err)
@@ -2566,10 +2584,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 := randState(ctx, t, config, log.TestingLogger(), 2)
_, vss := makeState(ctx, t, config, logger, 2)
randBytes := tmrand.Bytes(tmhash.Size)

View File

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

View File

@@ -41,8 +41,7 @@ func TestEvidencePoolBasic(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
valSet, privVals := factory.RandValidatorSet(ctx, t, 1, 10)
valSet, privVals := factory.ValidatorSet(t, 1, 10)
blockStore.On("LoadBlockMeta", mock.AnythingOfType("int64")).Return(
&types.BlockMeta{Header: types.Header{Time: defaultEvidenceTime}},
)

View File

@@ -201,7 +201,7 @@ func TestVerifyLightClientAttack_Equivocation(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
conflictingVals, conflictingPrivVals := factory.RandValidatorSet(ctx, t, 5, 10)
conflictingVals, conflictingPrivVals := factory.ValidatorSet(t, 5, 10)
conflictingHeader := factory.MakeHeader(t, &types.Header{
ChainID: evidenceChainID,
@@ -295,12 +295,11 @@ func TestVerifyLightClientAttack_Equivocation(t *testing.T) {
func TestVerifyLightClientAttack_Amnesia(t *testing.T) {
var height int64 = 10
conflictingVals, conflictingPrivVals := factory.ValidatorSet(t, 5, 10)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
conflictingVals, conflictingPrivVals := factory.RandValidatorSet(ctx, t, 5, 10)
conflictingHeader := factory.MakeHeader(t, &types.Header{
ChainID: evidenceChainID,
Height: height,
@@ -496,14 +495,14 @@ func makeLunaticEvidence(
) (ev *types.LightClientAttackEvidence, trusted *types.LightBlock, common *types.LightBlock) {
t.Helper()
commonValSet, commonPrivVals := factory.RandValidatorSet(ctx, t, totalVals, defaultVotingPower)
commonValSet, commonPrivVals := factory.ValidatorSet(t, 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(ctx, t, phantomVals, defaultVotingPower)
phantomValSet, phantomPrivVals := factory.ValidatorSet(t, phantomVals, defaultVotingPower)
conflictingVals := phantomValSet.Copy()
require.NoError(t, conflictingVals.UpdateWithChangeSet(byzValSet))
@@ -558,7 +557,7 @@ func makeLunaticEvidence(
ValidatorSet: commonValSet,
}
trustedBlockID := factory.MakeBlockIDWithHash(trustedHeader.Hash())
trustedVals, privVals := factory.RandValidatorSet(ctx, t, totalVals, defaultVotingPower)
trustedVals, privVals := factory.ValidatorSet(t, totalVals, defaultVotingPower)
trustedVoteSet := types.NewVoteSet(evidenceChainID, height, 1, tmproto.SignedMsgType(2), trustedVals)
trustedCommit, err := factory.MakeCommit(ctx, trustedBlockID, height, 1, trustedVoteSet, privVals, defaultEvidenceTime)
require.NoError(t, err)

View File

@@ -95,7 +95,7 @@ func iotest(t *testing.T, writer protoio.WriteCloser, reader protoio.ReadCloser)
}
i++
}
require.NotEqual(t, size, i)
require.Equal(t, size, i)
if err := reader.Close(); err != nil {
return err
}

View File

@@ -4,6 +4,7 @@ import (
"bytes"
"context"
"fmt"
"math/rand"
"testing"
"time"
@@ -258,7 +259,6 @@ func makeRandomStateFromValidatorSet(
InitialHeight: 1,
}
}
func makeRandomStateFromConsensusParams(
ctx context.Context,
t *testing.T,
@@ -267,7 +267,7 @@ func makeRandomStateFromConsensusParams(
lastHeightConsensusParamsChanged int64,
) sm.State {
t.Helper()
val, _, err := factory.RandValidator(ctx, true, 10)
val, _, err := factory.Validator(10 + int64(rand.Uint32()))
require.NoError(t, err)
valSet := types.NewValidatorSet([]*types.Validator{val})
return sm.State{

View File

@@ -1,7 +1,6 @@
package state_test
import (
"context"
"testing"
"github.com/stretchr/testify/require"
@@ -19,11 +18,9 @@ func TestRollback(t *testing.T) {
height int64 = 100
nextHeight int64 = 101
)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
blockStore := &mocks.BlockStore{}
stateStore := setupStateStore(ctx, t, height)
stateStore := setupStateStore(t, height)
initialState, err := stateStore.Load()
require.NoError(t, err)
@@ -83,10 +80,7 @@ func TestRollbackNoState(t *testing.T) {
func TestRollbackNoBlocks(t *testing.T) {
const height = int64(100)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
stateStore := setupStateStore(ctx, t, height)
stateStore := setupStateStore(t, height)
blockStore := &mocks.BlockStore{}
blockStore.On("Height").Return(height)
blockStore.On("LoadBlockMeta", height-1).Return(nil)
@@ -98,11 +92,7 @@ func TestRollbackNoBlocks(t *testing.T) {
func TestRollbackDifferentStateHeight(t *testing.T) {
const height = int64(100)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
stateStore := setupStateStore(ctx, t, height)
stateStore := setupStateStore(t, height)
blockStore := &mocks.BlockStore{}
blockStore.On("Height").Return(height + 2)
@@ -111,9 +101,9 @@ func TestRollbackDifferentStateHeight(t *testing.T) {
require.Equal(t, err.Error(), "statestore height (100) is not one below or equal to blockstore height (102)")
}
func setupStateStore(ctx context.Context, t *testing.T, height int64) state.Store {
func setupStateStore(t *testing.T, height int64) state.Store {
stateStore := state.NewStore(dbm.NewMemDB())
valSet, _ := factory.RandValidatorSet(ctx, t, 5, 10)
valSet, _ := factory.ValidatorSet(t, 5, 10)
params := types.DefaultConsensusParams()
params.Version.AppVersion = 10

View File

@@ -3,6 +3,7 @@ package state_test
import (
"context"
"fmt"
"math/rand"
"os"
"testing"
@@ -27,16 +28,13 @@ const (
)
func TestStoreBootstrap(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
stateDB := dbm.NewMemDB()
stateStore := sm.NewStore(stateDB)
val, _, err := factory.RandValidator(ctx, true, 10)
val, _, err := factory.Validator(10 + int64(rand.Uint32()))
require.NoError(t, err)
val2, _, err := factory.RandValidator(ctx, true, 10)
val2, _, err := factory.Validator(10 + int64(rand.Uint32()))
require.NoError(t, err)
val3, _, err := factory.RandValidator(ctx, true, 10)
val3, _, err := factory.Validator(10 + int64(rand.Uint32()))
require.NoError(t, err)
vals := types.NewValidatorSet([]*types.Validator{val, val2, val3})
bootstrapState := makeRandomStateFromValidatorSet(vals, 100, 100)
@@ -58,16 +56,13 @@ func TestStoreBootstrap(t *testing.T) {
}
func TestStoreLoadValidators(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
stateDB := dbm.NewMemDB()
stateStore := sm.NewStore(stateDB)
val, _, err := factory.RandValidator(ctx, true, 10)
val, _, err := factory.Validator(10 + int64(rand.Uint32()))
require.NoError(t, err)
val2, _, err := factory.RandValidator(ctx, true, 10)
val2, _, err := factory.Validator(10 + int64(rand.Uint32()))
require.NoError(t, err)
val3, _, err := factory.RandValidator(ctx, true, 10)
val3, _, err := factory.Validator(10 + int64(rand.Uint32()))
require.NoError(t, err)
vals := types.NewValidatorSet([]*types.Validator{val, val2, val3})

View File

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

View File

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

View File

@@ -1,36 +1,33 @@
package factory
import (
"context"
"sort"
"testing"
"time"
"github.com/stretchr/testify/require"
"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(ctx context.Context, t *testing.T, cfg *config.Config, numValidators int, randPower bool, minPower int64) (*types.GenesisDoc, []types.PrivValidator) {
t.Helper()
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, err := RandValidator(ctx, randPower, minPower)
require.NoError(t, err)
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

@@ -2,8 +2,6 @@ package factory
import (
"context"
"fmt"
"math/rand"
"sort"
"testing"
@@ -11,23 +9,18 @@ import (
"github.com/tendermint/tendermint/types"
)
func RandValidator(ctx context.Context, randPower bool, minPower int64) (*types.Validator, types.PrivValidator, error) {
func Validator(votingPower int64) (*types.Validator, types.PrivValidator, error) {
privVal := types.NewMockPV()
votePower := minPower
if randPower {
// nolint:gosec // G404: Use of weak random number generator
votePower += int64(rand.Uint32())
}
pubKey, err := privVal.GetPubKey(ctx)
pubKey, err := privVal.GetPubKey(context.Background())
if err != nil {
return nil, nil, fmt.Errorf("could not retrieve public key: %w", err)
return nil, nil, err
}
val := types.NewValidator(pubKey, votePower)
return val, privVal, err
val := types.NewValidator(pubKey, votingPower)
return val, privVal, nil
}
func RandValidatorSet(ctx context.Context, t *testing.T, numValidators int, votingPower int64) (*types.ValidatorSet, []types.PrivValidator) {
func ValidatorSet(t *testing.T, numValidators int, votingPower int64) (*types.ValidatorSet, []types.PrivValidator) {
var (
valz = make([]*types.Validator, numValidators)
privValidators = make([]types.PrivValidator, numValidators)
@@ -35,7 +28,7 @@ func RandValidatorSet(ctx context.Context, t *testing.T, numValidators int, voti
t.Helper()
for i := 0; i < numValidators; i++ {
val, privValidator, err := RandValidator(ctx, false, votingPower)
val, privValidator, err := Validator(votingPower)
require.NoError(t, err)
valz[i] = val
privValidators[i] = privValidator

View File

@@ -109,12 +109,9 @@ func TestValidateTrustOptions(t *testing.T) {
}
func TestClient_SequentialVerification(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
newKeys := genPrivKeys(4)
newVals := newKeys.ToValidators(10, 1)
differentVals, _ := factory.RandValidatorSet(ctx, t, 10, 100)
differentVals, _ := factory.ValidatorSet(t, 10, 100)
testCases := []struct {
name string
@@ -942,7 +939,7 @@ func TestClient_TrustedValidatorSet(t *testing.T) {
logger := log.NewTestingLogger(t)
differentVals, _ := factory.RandValidatorSet(ctx, t, 10, 100)
differentVals, _ := factory.ValidatorSet(t, 10, 100)
mockBadValSetNode := mockNodeFromHeadersAndVals(
map[int64]*types.SignedHeader{
1: h1,

View File

@@ -1,7 +1,6 @@
package db
import (
"context"
"sync"
"testing"
"time"
@@ -19,9 +18,6 @@ import (
)
func TestLast_FirstLightBlockHeight(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
dbStore := New(dbm.NewMemDB())
// Empty store
@@ -34,7 +30,7 @@ func TestLast_FirstLightBlockHeight(t *testing.T) {
assert.EqualValues(t, -1, height)
// 1 key
err = dbStore.SaveLightBlock(randLightBlock(ctx, t, int64(1)))
err = dbStore.SaveLightBlock(randLightBlock(t, int64(1)))
require.NoError(t, err)
height, err = dbStore.LastLightBlockHeight()
@@ -49,16 +45,13 @@ func TestLast_FirstLightBlockHeight(t *testing.T) {
func Test_SaveLightBlock(t *testing.T) {
dbStore := New(dbm.NewMemDB())
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Empty store
h, err := dbStore.LightBlock(1)
require.Error(t, err)
assert.Nil(t, h)
// 1 key
err = dbStore.SaveLightBlock(randLightBlock(ctx, t, 1))
err = dbStore.SaveLightBlock(randLightBlock(t, 1))
require.NoError(t, err)
size := dbStore.Size()
@@ -87,10 +80,7 @@ func Test_LightBlockBefore(t *testing.T) {
_, _ = dbStore.LightBlockBefore(100)
})
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
err := dbStore.SaveLightBlock(randLightBlock(ctx, t, int64(2)))
err := dbStore.SaveLightBlock(randLightBlock(t, int64(2)))
require.NoError(t, err)
h, err := dbStore.LightBlockBefore(3)
@@ -106,16 +96,13 @@ func Test_LightBlockBefore(t *testing.T) {
func Test_Prune(t *testing.T) {
dbStore := New(dbm.NewMemDB())
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Empty store
assert.EqualValues(t, 0, dbStore.Size())
err := dbStore.Prune(0)
require.NoError(t, err)
// One header
err = dbStore.SaveLightBlock(randLightBlock(ctx, t, 2))
err = dbStore.SaveLightBlock(randLightBlock(t, 2))
require.NoError(t, err)
assert.EqualValues(t, 1, dbStore.Size())
@@ -130,7 +117,7 @@ func Test_Prune(t *testing.T) {
// Multiple headers
for i := 1; i <= 10; i++ {
err = dbStore.SaveLightBlock(randLightBlock(ctx, t, int64(i)))
err = dbStore.SaveLightBlock(randLightBlock(t, int64(i)))
require.NoError(t, err)
}
@@ -146,16 +133,13 @@ func Test_Prune(t *testing.T) {
func Test_Concurrency(t *testing.T) {
dbStore := New(dbm.NewMemDB())
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var wg sync.WaitGroup
for i := 1; i <= 100; i++ {
wg.Add(1)
go func(i int64) {
defer wg.Done()
err := dbStore.SaveLightBlock(randLightBlock(ctx, t, i))
err := dbStore.SaveLightBlock(randLightBlock(t, i))
require.NoError(t, err)
_, err = dbStore.LightBlock(i)
@@ -198,9 +182,8 @@ func Test_Concurrency(t *testing.T) {
wg.Wait()
}
func randLightBlock(ctx context.Context, t *testing.T, height int64) *types.LightBlock {
t.Helper()
vals, _ := factory.RandValidatorSet(ctx, t, 2, 1)
func randLightBlock(t *testing.T, height int64) *types.LightBlock {
vals, _ := factory.ValidatorSet(t, 2, 1)
return &types.LightBlock{
SignedHeader: &types.SignedHeader{
Header: &types.Header{

View File

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

View File

@@ -157,7 +157,7 @@ func generateLightClientAttackEvidence(
// add a new bogus validator and remove an existing one to
// vary the validator set slightly
pv, conflictingVals, err := mutateValidatorSet(ctx, privVals, vals)
pv, conflictingVals, err := mutateValidatorSet(privVals, vals)
if err != nil {
return nil, err
}
@@ -288,8 +288,9 @@ func makeBlockID(hash []byte, partSetSize uint32, partSetHash []byte) types.Bloc
}
}
func mutateValidatorSet(ctx context.Context, privVals []types.MockPV, vals *types.ValidatorSet) ([]types.PrivValidator, *types.ValidatorSet, error) {
newVal, newPrivVal, err := factory.RandValidator(ctx, false, 10)
func mutateValidatorSet(privVals []types.MockPV, vals *types.ValidatorSet,
) ([]types.PrivValidator, *types.ValidatorSet, error) {
newVal, newPrivVal, err := factory.Validator(10)
if err != nil {
return nil, nil, err
}