From afc4d7a61fc03816636a2092b377bc3de574cfc4 Mon Sep 17 00:00:00 2001 From: Marko Date: Tue, 10 Dec 2019 18:38:34 +0100 Subject: [PATCH] libs/common: refactor libs/common 2 (#4231) * libs/common: refactor libs/common 2 - move random function to there own pkg Signed-off-by: Marko Baricevic * change imports and usage throughout repo * fix goimports * add changelog entry --- CHANGELOG_PENDING.md | 1 + PHILOSOPHY.md | 8 ++--- abci/client/socket_client_test.go | 3 +- abci/example/kvstore/helpers.go | 6 ++-- abci/tests/server/client.go | 6 ++-- blockchain/v0/pool_test.go | 6 ++-- blockchain/v1/peer_test.go | 18 ++++++------ blockchain/v1/reactor_fsm_test.go | 13 +++++---- cmd/tendermint/commands/init.go | 3 +- cmd/tendermint/commands/testnet.go | 5 ++-- consensus/replay_test.go | 6 ++-- consensus/state_test.go | 4 +-- consensus/types/round_state_test.go | 26 ++++++++--------- consensus/wal_generator.go | 4 +-- crypto/merkle/simple_tree_test.go | 10 +++---- .../bitarray/compact_bit_array_test.go | 4 +-- libs/autofile/autofile.go | 4 +-- libs/autofile/group_test.go | 13 +++++---- libs/clist/clist_test.go | 8 ++--- libs/common/bit_array.go | 4 ++- libs/common/bit_array_test.go | 4 ++- libs/common/tempfile_test.go | 6 ++-- libs/events/events_test.go | 6 ++-- libs/{common => rand}/random.go | 2 +- libs/{common => rand}/random_test.go | 2 +- libs/test/mutate.go | 8 ++--- lite/dbprovider.go | 2 +- lite2/client.go | 3 +- mempool/clist_mempool_test.go | 7 +++-- node/node_test.go | 8 ++--- p2p/conn/secret_connection_test.go | 21 +++++++------- p2p/fuzz.go | 6 ++-- p2p/key_test.go | 4 +-- p2p/pex/addrbook.go | 7 +++-- p2p/pex/addrbook_test.go | 15 +++++----- p2p/pex/pex_reactor.go | 9 +++--- p2p/switch.go | 5 ++-- p2p/test_util.go | 11 +++---- privval/signer_client_test.go | 4 +-- privval/signer_listener_endpoint_test.go | 5 ++-- proxy/app_conn_test.go | 8 ++--- rpc/client/event_test.go | 6 ++-- rpc/lib/client/ws_client.go | 3 +- rpc/lib/rpc_test.go | 5 ++-- state/helpers_test.go | 4 +-- state/state_test.go | 10 +++---- state/tx_filter_test.go | 14 ++++----- state/txindex/kv/kv_test.go | 4 +-- types/block_test.go | 3 +- types/event_bus_test.go | 8 ++--- types/part_set_test.go | 10 +++---- types/tx_test.go | 6 ++-- types/validator.go | 4 +-- types/validator_set_test.go | 29 ++++++++++--------- types/vote_set_test.go | 16 +++++----- 55 files changed, 221 insertions(+), 196 deletions(-) rename libs/{common => rand}/random.go (99%) rename libs/{common => rand}/random_test.go (99%) diff --git a/CHANGELOG_PENDING.md b/CHANGELOG_PENDING.md index 7ad7cab91..246cb14cf 100644 --- a/CHANGELOG_PENDING.md +++ b/CHANGELOG_PENDING.md @@ -70,6 +70,7 @@ program](https://hackerone.com/tendermint). - [libs/common] \#3862 Remove `errors.go` from `libs/common` - [libs/common] \#4230 Move `KV` out of common to its own pkg - [libs/common] \#4230 Rename `cmn.KVPair(s)` to `kv.Pair(s)`s + - [libs/common] \#4231 Move random functions from `libs/common` into pkg `rand` - Blockchain Protocol diff --git a/PHILOSOPHY.md b/PHILOSOPHY.md index cf79710fd..9be7a56cb 100644 --- a/PHILOSOPHY.md +++ b/PHILOSOPHY.md @@ -88,11 +88,11 @@ non-concurrent logic, then the performance is good enough. If they are used in the context of concurrent logic, then it will still perform correctly. Examples of this design principle can be seen in the types.ValidatorSet struct, -and the cmn.Rand struct. It's one single struct declaration that can be used +and the rand.Rand struct. It's one single struct declaration that can be used in both concurrent and non-concurrent logic, and due to its well encapsulation, it's easy to get the usage of the mutex right. -#### example: cmn.Rand: +#### example: rand.Rand: `The default Source is safe for concurrent use by multiple goroutines, but Sources created by NewSource are not`. The reason why the default @@ -101,14 +101,14 @@ package-level source is safe for concurrent use is because it is protected (see But we shouldn't rely on the global source, we should be creating our own Rand/Source instances and using them, especially for determinism in testing. -So it is reasonable to have cmn.Rand be protected by a mutex. Whether we want +So it is reasonable to have rand.Rand be protected by a mutex. Whether we want our own implementation of Rand is another question, but the answer there is also in the affirmative. Sometimes you want to know where Rand is being used in your code, so it becomes a simple matter of dropping in a log statement to inject inspectability into Rand usage. Also, it is nice to be able to extend the functionality of Rand with custom methods. For these reasons, and for the reasons which is outlined in this design philosophy document, we should -continue to use the cmn.Rand object, with mutex protection. +continue to use the rand.Rand object, with mutex protection. Another key aspect of good encapsulation is the choice of exposed vs unexposed methods. It should be clear to the reader of the code, which methods are diff --git a/abci/client/socket_client_test.go b/abci/client/socket_client_test.go index 49114afd5..2a00142b0 100644 --- a/abci/client/socket_client_test.go +++ b/abci/client/socket_client_test.go @@ -13,6 +13,7 @@ import ( "github.com/tendermint/tendermint/abci/server" "github.com/tendermint/tendermint/abci/types" cmn "github.com/tendermint/tendermint/libs/common" + "github.com/tendermint/tendermint/libs/rand" ) func TestSocketClientStopForErrorDeadlock(t *testing.T) { @@ -96,7 +97,7 @@ func TestHangingSyncCalls(t *testing.T) { func setupClientServer(t *testing.T, app types.Application) ( cmn.Service, abcicli.Client) { // some port between 20k and 30k - port := 20000 + cmn.RandInt32()%10000 + port := 20000 + rand.RandInt32()%10000 addr := fmt.Sprintf("localhost:%d", port) s, err := server.NewServer(addr, "socket", app) diff --git a/abci/example/kvstore/helpers.go b/abci/example/kvstore/helpers.go index bb086dec0..9cde3ffb2 100644 --- a/abci/example/kvstore/helpers.go +++ b/abci/example/kvstore/helpers.go @@ -2,14 +2,14 @@ package kvstore import ( "github.com/tendermint/tendermint/abci/types" - cmn "github.com/tendermint/tendermint/libs/common" + "github.com/tendermint/tendermint/libs/rand" ) // RandVal creates one random validator, with a key derived // from the input value func RandVal(i int) types.ValidatorUpdate { - pubkey := cmn.RandBytes(32) - power := cmn.RandUint16() + 1 + pubkey := rand.RandBytes(32) + power := rand.RandUint16() + 1 v := types.Ed25519ValidatorUpdate(pubkey, int64(power)) return v } diff --git a/abci/tests/server/client.go b/abci/tests/server/client.go index f0608ba08..14d785053 100644 --- a/abci/tests/server/client.go +++ b/abci/tests/server/client.go @@ -7,15 +7,15 @@ import ( abcicli "github.com/tendermint/tendermint/abci/client" "github.com/tendermint/tendermint/abci/types" - cmn "github.com/tendermint/tendermint/libs/common" + "github.com/tendermint/tendermint/libs/rand" ) func InitChain(client abcicli.Client) error { total := 10 vals := make([]types.ValidatorUpdate, total) for i := 0; i < total; i++ { - pubkey := cmn.RandBytes(33) - power := cmn.RandInt() + pubkey := rand.RandBytes(33) + power := rand.RandInt() vals[i] = types.Ed25519ValidatorUpdate(pubkey, int64(power)) } _, err := client.InitChainSync(types.RequestInitChain{ diff --git a/blockchain/v0/pool_test.go b/blockchain/v0/pool_test.go index a573b27b2..b3d4a0203 100644 --- a/blockchain/v0/pool_test.go +++ b/blockchain/v0/pool_test.go @@ -8,8 +8,8 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - cmn "github.com/tendermint/tendermint/libs/common" "github.com/tendermint/tendermint/libs/log" + "github.com/tendermint/tendermint/libs/rand" "github.com/tendermint/tendermint/p2p" "github.com/tendermint/tendermint/types" ) @@ -65,8 +65,8 @@ func (ps testPeers) stop() { func makePeers(numPeers int, minHeight, maxHeight int64) testPeers { peers := make(testPeers, numPeers) for i := 0; i < numPeers; i++ { - peerID := p2p.ID(cmn.RandStr(12)) - height := minHeight + cmn.RandInt63n(maxHeight-minHeight) + peerID := p2p.ID(rand.RandStr(12)) + height := minHeight + rand.RandInt63n(maxHeight-minHeight) peers[peerID] = testPeer{peerID, height, make(chan inputData, 10)} } return peers diff --git a/blockchain/v1/peer_test.go b/blockchain/v1/peer_test.go index c35419790..348ed8330 100644 --- a/blockchain/v1/peer_test.go +++ b/blockchain/v1/peer_test.go @@ -8,15 +8,15 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - cmn "github.com/tendermint/tendermint/libs/common" "github.com/tendermint/tendermint/libs/log" + "github.com/tendermint/tendermint/libs/rand" "github.com/tendermint/tendermint/p2p" "github.com/tendermint/tendermint/types" ) func TestPeerMonitor(t *testing.T) { peer := NewBpPeer( - p2p.ID(cmn.RandStr(12)), 10, + p2p.ID(rand.RandStr(12)), 10, func(err error, _ p2p.ID) {}, nil) peer.SetLogger(log.TestingLogger()) @@ -35,7 +35,7 @@ func TestPeerResetBlockResponseTimer(t *testing.T) { params := &BpPeerParams{timeout: 2 * time.Millisecond} peer := NewBpPeer( - p2p.ID(cmn.RandStr(12)), 10, + p2p.ID(rand.RandStr(12)), 10, func(err error, _ p2p.ID) { peerTestMtx.Lock() defer peerTestMtx.Unlock() @@ -75,7 +75,7 @@ func TestPeerRequestSent(t *testing.T) { params := &BpPeerParams{timeout: 2 * time.Millisecond} peer := NewBpPeer( - p2p.ID(cmn.RandStr(12)), 10, + p2p.ID(rand.RandStr(12)), 10, func(err error, _ p2p.ID) {}, params) @@ -94,7 +94,7 @@ func TestPeerRequestSent(t *testing.T) { func TestPeerGetAndRemoveBlock(t *testing.T) { peer := NewBpPeer( - p2p.ID(cmn.RandStr(12)), 100, + p2p.ID(rand.RandStr(12)), 100, func(err error, _ p2p.ID) {}, nil) @@ -142,7 +142,7 @@ func TestPeerGetAndRemoveBlock(t *testing.T) { func TestPeerAddBlock(t *testing.T) { peer := NewBpPeer( - p2p.ID(cmn.RandStr(12)), 100, + p2p.ID(rand.RandStr(12)), 100, func(err error, _ p2p.ID) {}, nil) @@ -189,7 +189,7 @@ func TestPeerOnErrFuncCalledDueToExpiration(t *testing.T) { ) peer := NewBpPeer( - p2p.ID(cmn.RandStr(12)), 10, + p2p.ID(rand.RandStr(12)), 10, func(err error, _ p2p.ID) { peerTestMtx.Lock() defer peerTestMtx.Unlock() @@ -215,7 +215,7 @@ func TestPeerCheckRate(t *testing.T) { minRecvRate: int64(100), // 100 bytes/sec exponential moving average } peer := NewBpPeer( - p2p.ID(cmn.RandStr(12)), 10, + p2p.ID(rand.RandStr(12)), 10, func(err error, _ p2p.ID) {}, params) peer.SetLogger(log.TestingLogger()) @@ -249,7 +249,7 @@ func TestPeerCleanup(t *testing.T) { params := &BpPeerParams{timeout: 2 * time.Millisecond} peer := NewBpPeer( - p2p.ID(cmn.RandStr(12)), 10, + p2p.ID(rand.RandStr(12)), 10, func(err error, _ p2p.ID) {}, params) peer.SetLogger(log.TestingLogger()) diff --git a/blockchain/v1/reactor_fsm_test.go b/blockchain/v1/reactor_fsm_test.go index 7dff5bbaf..511664121 100644 --- a/blockchain/v1/reactor_fsm_test.go +++ b/blockchain/v1/reactor_fsm_test.go @@ -8,6 +8,7 @@ import ( "github.com/stretchr/testify/assert" cmn "github.com/tendermint/tendermint/libs/common" "github.com/tendermint/tendermint/libs/log" + "github.com/tendermint/tendermint/libs/rand" "github.com/tendermint/tendermint/p2p" "github.com/tendermint/tendermint/types" ) @@ -735,7 +736,7 @@ func makeCorrectTransitionSequence(startingHeight int64, numBlocks int64, numPee continue } if randomPeerHeights { - peerHeights[i] = int64(cmn.MaxInt(cmn.RandIntn(int(numBlocks)), int(startingHeight)+1)) + peerHeights[i] = int64(cmn.MaxInt(rand.RandIntn(int(numBlocks)), int(startingHeight)+1)) } else { peerHeights[i] = numBlocks } @@ -825,19 +826,19 @@ const ( func makeCorrectTransitionSequenceWithRandomParameters() testFields { // Generate a starting height for fast sync. - startingHeight := int64(cmn.RandIntn(maxStartingHeightTest) + 1) + startingHeight := int64(rand.RandIntn(maxStartingHeightTest) + 1) // Generate the number of requests per peer. - maxRequestsPerPeer := cmn.RandIntn(maxRequestsPerPeerTest) + 1 + maxRequestsPerPeer := rand.RandIntn(maxRequestsPerPeerTest) + 1 // Generate the maximum number of total pending requests, >= maxRequestsPerPeer. - maxPendingRequests := cmn.RandIntn(maxTotalPendingRequestsTest-maxRequestsPerPeer) + maxRequestsPerPeer + maxPendingRequests := rand.RandIntn(maxTotalPendingRequestsTest-maxRequestsPerPeer) + maxRequestsPerPeer // Generate the number of blocks to be synced. - numBlocks := int64(cmn.RandIntn(maxNumBlocksInChainTest)) + startingHeight + numBlocks := int64(rand.RandIntn(maxNumBlocksInChainTest)) + startingHeight // Generate a number of peers. - numPeers := cmn.RandIntn(maxNumPeersTest) + 1 + numPeers := rand.RandIntn(maxNumPeersTest) + 1 return makeCorrectTransitionSequence(startingHeight, numBlocks, numPeers, true, maxRequestsPerPeer, maxPendingRequests) } diff --git a/cmd/tendermint/commands/init.go b/cmd/tendermint/commands/init.go index 1d6e24d7d..3d93ca3d1 100644 --- a/cmd/tendermint/commands/init.go +++ b/cmd/tendermint/commands/init.go @@ -6,6 +6,7 @@ import ( "github.com/spf13/cobra" cfg "github.com/tendermint/tendermint/config" cmn "github.com/tendermint/tendermint/libs/common" + "github.com/tendermint/tendermint/libs/rand" "github.com/tendermint/tendermint/p2p" "github.com/tendermint/tendermint/privval" "github.com/tendermint/tendermint/types" @@ -55,7 +56,7 @@ func initFilesWithConfig(config *cfg.Config) error { logger.Info("Found genesis file", "path", genFile) } else { genDoc := types.GenesisDoc{ - ChainID: fmt.Sprintf("test-chain-%v", cmn.RandStr(6)), + ChainID: fmt.Sprintf("test-chain-%v", rand.RandStr(6)), GenesisTime: tmtime.Now(), ConsensusParams: types.DefaultConsensusParams(), } diff --git a/cmd/tendermint/commands/testnet.go b/cmd/tendermint/commands/testnet.go index 5f199908e..c85d635fd 100644 --- a/cmd/tendermint/commands/testnet.go +++ b/cmd/tendermint/commands/testnet.go @@ -12,6 +12,7 @@ import ( cfg "github.com/tendermint/tendermint/config" cmn "github.com/tendermint/tendermint/libs/common" + "github.com/tendermint/tendermint/libs/rand" "github.com/tendermint/tendermint/p2p" "github.com/tendermint/tendermint/privval" "github.com/tendermint/tendermint/types" @@ -167,7 +168,7 @@ func testnetFiles(cmd *cobra.Command, args []string) error { // Generate genesis doc from generated validators genDoc := &types.GenesisDoc{ - ChainID: "chain-" + cmn.RandStr(6), + ChainID: "chain-" + rand.RandStr(6), ConsensusParams: types.DefaultConsensusParams(), GenesisTime: tmtime.Now(), Validators: genVals, @@ -261,5 +262,5 @@ func moniker(i int) string { } func randomMoniker() string { - return cmn.HexBytes(cmn.RandBytes(8)).String() + return cmn.HexBytes(rand.RandBytes(8)).String() } diff --git a/consensus/replay_test.go b/consensus/replay_test.go index 5df16bc7b..85f260694 100644 --- a/consensus/replay_test.go +++ b/consensus/replay_test.go @@ -21,8 +21,8 @@ import ( abci "github.com/tendermint/tendermint/abci/types" cfg "github.com/tendermint/tendermint/config" "github.com/tendermint/tendermint/crypto" - cmn "github.com/tendermint/tendermint/libs/common" "github.com/tendermint/tendermint/libs/log" + "github.com/tendermint/tendermint/libs/rand" mempl "github.com/tendermint/tendermint/mempool" "github.com/tendermint/tendermint/mock" "github.com/tendermint/tendermint/privval" @@ -912,11 +912,11 @@ func (app *badApp) Commit() abci.ResponseCommit { app.height++ if app.onlyLastHashIsWrong { if app.height == app.numBlocks { - return abci.ResponseCommit{Data: cmn.RandBytes(8)} + return abci.ResponseCommit{Data: rand.RandBytes(8)} } return abci.ResponseCommit{Data: []byte{app.height}} } else if app.allHashesAreWrong { - return abci.ResponseCommit{Data: cmn.RandBytes(8)} + return abci.ResponseCommit{Data: rand.RandBytes(8)} } panic("either allHashesAreWrong or onlyLastHashIsWrong must be set") diff --git a/consensus/state_test.go b/consensus/state_test.go index 3c0413a69..4d8553a8c 100644 --- a/consensus/state_test.go +++ b/consensus/state_test.go @@ -11,9 +11,9 @@ import ( "github.com/stretchr/testify/require" cstypes "github.com/tendermint/tendermint/consensus/types" - cmn "github.com/tendermint/tendermint/libs/common" "github.com/tendermint/tendermint/libs/log" tmpubsub "github.com/tendermint/tendermint/libs/pubsub" + "github.com/tendermint/tendermint/libs/rand" p2pmock "github.com/tendermint/tendermint/p2p/mock" "github.com/tendermint/tendermint/types" ) @@ -1563,7 +1563,7 @@ func TestStateOutputsBlockPartsStats(t *testing.T) { peer := p2pmock.NewPeer(nil) // 1) new block part - parts := types.NewPartSetFromData(cmn.RandBytes(100), 10) + parts := types.NewPartSetFromData(rand.RandBytes(100), 10) msg := &BlockPartMessage{ Height: 1, Round: 0, diff --git a/consensus/types/round_state_test.go b/consensus/types/round_state_test.go index d7861b313..d0cd6b937 100644 --- a/consensus/types/round_state_test.go +++ b/consensus/types/round_state_test.go @@ -5,7 +5,7 @@ import ( amino "github.com/tendermint/go-amino" "github.com/tendermint/tendermint/crypto/ed25519" - cmn "github.com/tendermint/tendermint/libs/common" + "github.com/tendermint/tendermint/libs/rand" "github.com/tendermint/tendermint/types" tmtime "github.com/tendermint/tendermint/types/time" ) @@ -18,15 +18,15 @@ func BenchmarkRoundStateDeepCopy(b *testing.B) { vset, _ := types.RandValidatorSet(nval, 1) commitSigs := make([]types.CommitSig, nval) blockID := types.BlockID{ - Hash: cmn.RandBytes(20), + Hash: rand.RandBytes(20), PartsHeader: types.PartSetHeader{ - Hash: cmn.RandBytes(20), + Hash: rand.RandBytes(20), }, } sig := make([]byte, ed25519.SignatureSize) for i := 0; i < nval; i++ { commitSigs[i] = (&types.Vote{ - ValidatorAddress: types.Address(cmn.RandBytes(20)), + ValidatorAddress: types.Address(rand.RandBytes(20)), Timestamp: tmtime.Now(), BlockID: blockID, Signature: sig, @@ -34,21 +34,21 @@ func BenchmarkRoundStateDeepCopy(b *testing.B) { } txs := make([]types.Tx, ntxs) for i := 0; i < ntxs; i++ { - txs[i] = cmn.RandBytes(100) + txs[i] = rand.RandBytes(100) } // Random block block := &types.Block{ Header: types.Header{ - ChainID: cmn.RandStr(12), + ChainID: rand.RandStr(12), Time: tmtime.Now(), LastBlockID: blockID, - LastCommitHash: cmn.RandBytes(20), - DataHash: cmn.RandBytes(20), - ValidatorsHash: cmn.RandBytes(20), - ConsensusHash: cmn.RandBytes(20), - AppHash: cmn.RandBytes(20), - LastResultsHash: cmn.RandBytes(20), - EvidenceHash: cmn.RandBytes(20), + LastCommitHash: rand.RandBytes(20), + DataHash: rand.RandBytes(20), + ValidatorsHash: rand.RandBytes(20), + ConsensusHash: rand.RandBytes(20), + AppHash: rand.RandBytes(20), + LastResultsHash: rand.RandBytes(20), + EvidenceHash: rand.RandBytes(20), }, Data: types.Data{ Txs: txs, diff --git a/consensus/wal_generator.go b/consensus/wal_generator.go index bd6961ffc..3729b72a0 100644 --- a/consensus/wal_generator.go +++ b/consensus/wal_generator.go @@ -13,8 +13,8 @@ import ( "github.com/tendermint/tendermint/abci/example/kvstore" cfg "github.com/tendermint/tendermint/config" - cmn "github.com/tendermint/tendermint/libs/common" "github.com/tendermint/tendermint/libs/log" + "github.com/tendermint/tendermint/libs/rand" "github.com/tendermint/tendermint/mock" "github.com/tendermint/tendermint/privval" "github.com/tendermint/tendermint/proxy" @@ -120,7 +120,7 @@ func WALWithNBlocks(t *testing.T, numBlocks int) (data []byte, err error) { func randPort() int { // returns between base and base + spread base, spread := 20000, 20000 - return base + cmn.RandIntn(spread) + return base + rand.RandIntn(spread) } func makeAddrs() (string, string, string) { diff --git a/crypto/merkle/simple_tree_test.go b/crypto/merkle/simple_tree_test.go index 5bbe294af..c59e50461 100644 --- a/crypto/merkle/simple_tree_test.go +++ b/crypto/merkle/simple_tree_test.go @@ -5,7 +5,7 @@ import ( "github.com/stretchr/testify/require" - cmn "github.com/tendermint/tendermint/libs/common" + "github.com/tendermint/tendermint/libs/rand" . "github.com/tendermint/tendermint/libs/test" "github.com/tendermint/tendermint/crypto/tmhash" @@ -23,7 +23,7 @@ func TestSimpleProof(t *testing.T) { items := make([][]byte, total) for i := 0; i < total; i++ { - items[i] = testItem(cmn.RandBytes(tmhash.Size)) + items[i] = testItem(rand.RandBytes(tmhash.Size)) } rootHash := SimpleHashFromByteSlices(items) @@ -47,7 +47,7 @@ func TestSimpleProof(t *testing.T) { // Trail too long should make it fail origAunts := proof.Aunts - proof.Aunts = append(proof.Aunts, cmn.RandBytes(32)) + proof.Aunts = append(proof.Aunts, rand.RandBytes(32)) err = proof.Verify(rootHash, item) require.Error(t, err, "Expected verification to fail for wrong trail length") @@ -76,7 +76,7 @@ func TestSimpleHashAlternatives(t *testing.T) { items := make([][]byte, total) for i := 0; i < total; i++ { - items[i] = testItem(cmn.RandBytes(tmhash.Size)) + items[i] = testItem(rand.RandBytes(tmhash.Size)) } rootHash1 := SimpleHashFromByteSlicesIterative(items) @@ -89,7 +89,7 @@ func BenchmarkSimpleHashAlternatives(b *testing.B) { items := make([][]byte, total) for i := 0; i < total; i++ { - items[i] = testItem(cmn.RandBytes(tmhash.Size)) + items[i] = testItem(rand.RandBytes(tmhash.Size)) } b.ResetTimer() diff --git a/crypto/multisig/bitarray/compact_bit_array_test.go b/crypto/multisig/bitarray/compact_bit_array_test.go index 369945ff3..9bc963931 100644 --- a/crypto/multisig/bitarray/compact_bit_array_test.go +++ b/crypto/multisig/bitarray/compact_bit_array_test.go @@ -7,12 +7,12 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - cmn "github.com/tendermint/tendermint/libs/common" + tmrand "github.com/tendermint/tendermint/libs/rand" ) func randCompactBitArray(bits int) (*CompactBitArray, []byte) { numBytes := (bits + 7) / 8 - src := cmn.RandBytes((bits + 7) / 8) + src := tmrand.RandBytes((bits + 7) / 8) bA := NewCompactBitArray(bits) for i := 0; i < numBytes-1; i++ { diff --git a/libs/autofile/autofile.go b/libs/autofile/autofile.go index e428e26c5..a9444e52d 100644 --- a/libs/autofile/autofile.go +++ b/libs/autofile/autofile.go @@ -7,7 +7,7 @@ import ( "syscall" "time" - cmn "github.com/tendermint/tendermint/libs/common" + "github.com/tendermint/tendermint/libs/rand" ) /* AutoFile usage @@ -58,7 +58,7 @@ type AutoFile struct { // permissions got changed (should be 0600)). func OpenAutoFile(path string) (*AutoFile, error) { af := &AutoFile{ - ID: cmn.RandStr(12) + ":" + path, + ID: rand.RandStr(12) + ":" + path, Path: path, closeTicker: time.NewTicker(autoFileClosePeriod), closeTickerStopc: make(chan struct{}), diff --git a/libs/autofile/group_test.go b/libs/autofile/group_test.go index 434292248..2029e56dc 100644 --- a/libs/autofile/group_test.go +++ b/libs/autofile/group_test.go @@ -10,10 +10,11 @@ import ( "github.com/stretchr/testify/require" cmn "github.com/tendermint/tendermint/libs/common" + "github.com/tendermint/tendermint/libs/rand" ) func createTestGroupWithHeadSizeLimit(t *testing.T, headSizeLimit int64) *Group { - testID := cmn.RandStr(12) + testID := rand.RandStr(12) testDir := "_test_" + testID err := cmn.EnsureDir(testDir, 0700) require.NoError(t, err, "Error creating dir") @@ -48,7 +49,7 @@ func TestCheckHeadSizeLimit(t *testing.T) { // Write 1000 bytes 999 times. for i := 0; i < 999; i++ { - err := g.WriteLine(cmn.RandStr(999)) + err := g.WriteLine(rand.RandStr(999)) require.NoError(t, err, "Error appending to head") } g.FlushAndSync() @@ -59,7 +60,7 @@ func TestCheckHeadSizeLimit(t *testing.T) { assertGroupInfo(t, g.ReadGroupInfo(), 0, 0, 999000, 999000) // Write 1000 more bytes. - err := g.WriteLine(cmn.RandStr(999)) + err := g.WriteLine(rand.RandStr(999)) require.NoError(t, err, "Error appending to head") g.FlushAndSync() @@ -68,7 +69,7 @@ func TestCheckHeadSizeLimit(t *testing.T) { assertGroupInfo(t, g.ReadGroupInfo(), 0, 1, 1000000, 0) // Write 1000 more bytes. - err = g.WriteLine(cmn.RandStr(999)) + err = g.WriteLine(rand.RandStr(999)) require.NoError(t, err, "Error appending to head") g.FlushAndSync() @@ -78,7 +79,7 @@ func TestCheckHeadSizeLimit(t *testing.T) { // Write 1000 bytes 999 times. for i := 0; i < 999; i++ { - err = g.WriteLine(cmn.RandStr(999)) + err = g.WriteLine(rand.RandStr(999)) require.NoError(t, err, "Error appending to head") } g.FlushAndSync() @@ -89,7 +90,7 @@ func TestCheckHeadSizeLimit(t *testing.T) { assertGroupInfo(t, g.ReadGroupInfo(), 0, 2, 2000000, 0) // Write 1000 more bytes. - _, err = g.Head.Write([]byte(cmn.RandStr(999) + "\n")) + _, err = g.Head.Write([]byte(rand.RandStr(999) + "\n")) require.NoError(t, err, "Error appending to head") g.FlushAndSync() assertGroupInfo(t, g.ReadGroupInfo(), 0, 2, 2001000, 1000) diff --git a/libs/clist/clist_test.go b/libs/clist/clist_test.go index 64cc75d1b..3a5903bf2 100644 --- a/libs/clist/clist_test.go +++ b/libs/clist/clist_test.go @@ -8,7 +8,7 @@ import ( "time" "github.com/stretchr/testify/assert" - cmn "github.com/tendermint/tendermint/libs/common" + "github.com/tendermint/tendermint/libs/rand" ) func TestPanicOnMaxLength(t *testing.T) { @@ -147,7 +147,7 @@ func _TestGCRandom(t *testing.T) { els = append(els, el) } - for _, i := range cmn.RandPerm(numElements) { + for _, i := range rand.RandPerm(numElements) { el := els[i] l.Remove(el) _ = el.Next() @@ -205,7 +205,7 @@ func TestScanRightDeleteRandom(t *testing.T) { // Remove an element, push back an element. for i := 0; i < numTimes; i++ { // Pick an element to remove - rmElIdx := cmn.RandIntn(len(els)) + rmElIdx := rand.RandIntn(len(els)) rmEl := els[rmElIdx] // Remove it @@ -259,7 +259,7 @@ func TestWaitChan(t *testing.T) { for i := 1; i < 100; i++ { l.PushBack(i) pushed++ - time.Sleep(time.Duration(cmn.RandIntn(25)) * time.Millisecond) + time.Sleep(time.Duration(rand.RandIntn(25)) * time.Millisecond) } // apply a deterministic pause so the counter has time to catch up time.Sleep(25 * time.Millisecond) diff --git a/libs/common/bit_array.go b/libs/common/bit_array.go index e996b390e..08bc0ee85 100644 --- a/libs/common/bit_array.go +++ b/libs/common/bit_array.go @@ -6,6 +6,8 @@ import ( "regexp" "strings" "sync" + + "github.com/tendermint/tendermint/libs/rand" ) // BitArray is a thread-safe implementation of a bit array. @@ -250,7 +252,7 @@ func (bA *BitArray) PickRandom() (int, bool) { return 0, false } - return trueIndices[RandIntn(len(trueIndices))], true + return trueIndices[rand.RandIntn(len(trueIndices))], true } func (bA *BitArray) getTrueIndices() []int { diff --git a/libs/common/bit_array_test.go b/libs/common/bit_array_test.go index 722ab2d81..ee88bb6ca 100644 --- a/libs/common/bit_array_test.go +++ b/libs/common/bit_array_test.go @@ -8,10 +8,12 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + + "github.com/tendermint/tendermint/libs/rand" ) func randBitArray(bits int) (*BitArray, []byte) { - src := RandBytes((bits + 7) / 8) + src := rand.RandBytes((bits + 7) / 8) bA := NewBitArray(bits) for i := 0; i < len(src); i++ { for j := 0; j < 8; j++ { diff --git a/libs/common/tempfile_test.go b/libs/common/tempfile_test.go index 51da90913..1a799c422 100644 --- a/libs/common/tempfile_test.go +++ b/libs/common/tempfile_test.go @@ -10,12 +10,14 @@ import ( testing "testing" "github.com/stretchr/testify/require" + + "github.com/tendermint/tendermint/libs/rand" ) func TestWriteFileAtomic(t *testing.T) { var ( - data = []byte(RandStr(RandIntn(2048))) - old = RandBytes(RandIntn(2048)) + data = []byte(rand.RandStr(rand.RandIntn(2048))) + old = rand.RandBytes(rand.RandIntn(2048)) perm os.FileMode = 0600 ) diff --git a/libs/events/events_test.go b/libs/events/events_test.go index a7a1ab2f1..c7b2b9d8b 100644 --- a/libs/events/events_test.go +++ b/libs/events/events_test.go @@ -8,7 +8,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - cmn "github.com/tendermint/tendermint/libs/common" + "github.com/tendermint/tendermint/libs/rand" ) // TestAddListenerForEventFireOnce sets up an EventSwitch, subscribes a single @@ -356,7 +356,7 @@ func TestRemoveListenersAsync(t *testing.T) { // collect received events for event2 go sumReceivedNumbers(numbers2, doneSum2) addListenersStress := func() { - r1 := cmn.NewRand() + r1 := rand.NewRand() r1.Seed(time.Now().UnixNano()) for k := uint16(0); k < 400; k++ { listenerNumber := r1.Intn(100) + 3 @@ -367,7 +367,7 @@ func TestRemoveListenersAsync(t *testing.T) { } } removeListenersStress := func() { - r2 := cmn.NewRand() + r2 := rand.NewRand() r2.Seed(time.Now().UnixNano()) for k := uint16(0); k < 80; k++ { listenerNumber := r2.Intn(100) + 3 diff --git a/libs/common/random.go b/libs/rand/random.go similarity index 99% rename from libs/common/random.go rename to libs/rand/random.go index 47e44d1c0..8a203c061 100644 --- a/libs/common/random.go +++ b/libs/rand/random.go @@ -1,4 +1,4 @@ -package common +package rand import ( crand "crypto/rand" diff --git a/libs/common/random_test.go b/libs/rand/random_test.go similarity index 99% rename from libs/common/random_test.go rename to libs/rand/random_test.go index 0cfb9d1af..37472cf76 100644 --- a/libs/common/random_test.go +++ b/libs/rand/random_test.go @@ -1,4 +1,4 @@ -package common +package rand import ( "bytes" diff --git a/libs/test/mutate.go b/libs/test/mutate.go index 3bbbbd217..f32adaa13 100644 --- a/libs/test/mutate.go +++ b/libs/test/mutate.go @@ -1,7 +1,7 @@ package test import ( - cmn "github.com/tendermint/tendermint/libs/common" + "github.com/tendermint/tendermint/libs/rand" ) // Contract: !bytes.Equal(input, output) && len(input) >= len(output) @@ -17,11 +17,11 @@ func MutateByteSlice(bytez []byte) []byte { bytez = mBytez // Try a random mutation - switch cmn.RandInt() % 2 { + switch rand.RandInt() % 2 { case 0: // Mutate a single byte - bytez[cmn.RandInt()%len(bytez)] += byte(cmn.RandInt()%255 + 1) + bytez[rand.RandInt()%len(bytez)] += byte(rand.RandInt()%255 + 1) case 1: // Remove an arbitrary byte - pos := cmn.RandInt() % len(bytez) + pos := rand.RandInt() % len(bytez) bytez = append(bytez[:pos], bytez[pos+1:]...) } return bytez diff --git a/lite/dbprovider.go b/lite/dbprovider.go index 98e8989a5..397cd7c2b 100644 --- a/lite/dbprovider.go +++ b/lite/dbprovider.go @@ -27,7 +27,7 @@ type DBProvider struct { func NewDBProvider(label string, db dbm.DB) *DBProvider { // NOTE: when debugging, this type of construction might be useful. - //db = dbm.NewDebugDB("db provider "+cmn.RandStr(4), db) + //db = dbm.NewDebugDB("db provider "+rand.RandStr(4), db) cdc := amino.NewCodec() cryptoamino.RegisterAmino(cdc) diff --git a/lite2/client.go b/lite2/client.go index 296b2c9d4..db1e494a1 100644 --- a/lite2/client.go +++ b/lite2/client.go @@ -9,6 +9,7 @@ import ( cmn "github.com/tendermint/tendermint/libs/common" "github.com/tendermint/tendermint/libs/log" + "github.com/tendermint/tendermint/libs/rand" "github.com/tendermint/tendermint/lite2/provider" "github.com/tendermint/tendermint/lite2/store" "github.com/tendermint/tendermint/types" @@ -421,7 +422,7 @@ func (c *Client) fetchHeaderAndValsAtHeight(height int64) (*types.SignedHeader, func (c *Client) compareNewHeaderWithRandomAlternative(h *types.SignedHeader) error { // 1. Pick an alternative provider. - p := c.alternatives[cmn.RandIntn(len(c.alternatives))] + p := c.alternatives[rand.RandIntn(len(c.alternatives))] // 2. Fetch the header. altHeader, err := p.SignedHeader(h.Height) diff --git a/mempool/clist_mempool_test.go b/mempool/clist_mempool_test.go index a06a3a4e5..5efc4ea72 100644 --- a/mempool/clist_mempool_test.go +++ b/mempool/clist_mempool_test.go @@ -24,6 +24,7 @@ import ( cfg "github.com/tendermint/tendermint/config" cmn "github.com/tendermint/tendermint/libs/common" "github.com/tendermint/tendermint/libs/log" + tmrand "github.com/tendermint/tendermint/libs/rand" "github.com/tendermint/tendermint/proxy" "github.com/tendermint/tendermint/types" ) @@ -455,7 +456,7 @@ func TestMempoolMaxMsgSize(t *testing.T) { for i, testCase := range testCases { caseString := fmt.Sprintf("case %d, len %d", i, testCase.len) - tx := cmn.RandBytes(testCase.len) + tx := tmrand.RandBytes(testCase.len) err := mempl.CheckTx(tx, nil, TxInfo{}) msg := &TxMessage{tx} encoded := cdc.MustMarshalBinaryBare(msg) @@ -542,7 +543,7 @@ func TestMempoolTxsBytes(t *testing.T) { // TODO: all of the tests should probably also run using the remote proxy app // since otherwise we're not actually testing the concurrency of the mempool here! func TestMempoolRemoteAppConcurrency(t *testing.T) { - sockPath := fmt.Sprintf("unix:///tmp/echo_%v.sock", cmn.RandStr(6)) + sockPath := fmt.Sprintf("unix:///tmp/echo_%v.sock", tmrand.RandStr(6)) app := kvstore.NewApplication() cc, server := newRemoteApp(t, sockPath, app) defer server.Stop() @@ -555,7 +556,7 @@ func TestMempoolRemoteAppConcurrency(t *testing.T) { txLen := 200 txs := make([]types.Tx, nTxs) for i := 0; i < nTxs; i++ { - txs[i] = cmn.RandBytes(txLen) + txs[i] = tmrand.RandBytes(txLen) } // simulate a group of peers sending them over and over diff --git a/node/node_test.go b/node/node_test.go index 9a1c7abc5..6fd6065b5 100644 --- a/node/node_test.go +++ b/node/node_test.go @@ -16,8 +16,8 @@ import ( cfg "github.com/tendermint/tendermint/config" "github.com/tendermint/tendermint/crypto/ed25519" "github.com/tendermint/tendermint/evidence" - cmn "github.com/tendermint/tendermint/libs/common" "github.com/tendermint/tendermint/libs/log" + "github.com/tendermint/tendermint/libs/rand" mempl "github.com/tendermint/tendermint/mempool" "github.com/tendermint/tendermint/p2p" p2pmock "github.com/tendermint/tendermint/p2p/mock" @@ -174,7 +174,7 @@ func TestPrivValidatorListenAddrNoProtocol(t *testing.T) { } func TestNodeSetPrivValIPC(t *testing.T) { - tmpfile := "/tmp/kms." + cmn.RandStr(6) + ".sock" + tmpfile := "/tmp/kms." + rand.RandStr(6) + ".sock" defer os.Remove(tmpfile) // clean up config := cfg.ResetTestRoot("node_priv_val_tcp_test") @@ -257,7 +257,7 @@ func TestCreateProposalBlock(t *testing.T) { minEvSize := 12 numEv := (maxBytes / types.MaxEvidenceBytesDenominator) / minEvSize for i := 0; i < numEv; i++ { - ev := types.NewMockRandomGoodEvidence(1, proposerAddr, cmn.RandBytes(minEvSize)) + ev := types.NewMockRandomGoodEvidence(1, proposerAddr, rand.RandBytes(minEvSize)) err := evidencePool.AddEvidence(ev) assert.NoError(t, err) } @@ -266,7 +266,7 @@ func TestCreateProposalBlock(t *testing.T) { // than can fit in a block txLength := 1000 for i := 0; i < maxBytes/txLength; i++ { - tx := cmn.RandBytes(txLength) + tx := rand.RandBytes(txLength) err := mempool.CheckTx(tx, nil, mempl.TxInfo{}) assert.NoError(t, err) } diff --git a/p2p/conn/secret_connection_test.go b/p2p/conn/secret_connection_test.go index 8faa895b0..d6d85fd80 100644 --- a/p2p/conn/secret_connection_test.go +++ b/p2p/conn/secret_connection_test.go @@ -20,6 +20,7 @@ import ( "github.com/tendermint/tendermint/crypto/ed25519" "github.com/tendermint/tendermint/crypto/secp256k1" cmn "github.com/tendermint/tendermint/libs/common" + "github.com/tendermint/tendermint/libs/rand" ) type kvstoreConn struct { @@ -103,7 +104,7 @@ func TestSecretConnectionHandshake(t *testing.T) { func TestConcurrentWrite(t *testing.T) { fooSecConn, barSecConn := makeSecretConnPair(t) - fooWriteText := cmn.RandStr(dataMaxSize) + fooWriteText := rand.RandStr(dataMaxSize) // write from two routines. // should be safe from race according to net.Conn: @@ -125,7 +126,7 @@ func TestConcurrentWrite(t *testing.T) { func TestConcurrentRead(t *testing.T) { fooSecConn, barSecConn := makeSecretConnPair(t) - fooWriteText := cmn.RandStr(dataMaxSize) + fooWriteText := rand.RandStr(dataMaxSize) n := 100 // read from two routines. @@ -172,8 +173,8 @@ func TestSecretConnectionReadWrite(t *testing.T) { // Pre-generate the things to write (for foo & bar) for i := 0; i < 100; i++ { - fooWrites = append(fooWrites, cmn.RandStr((cmn.RandInt()%(dataMaxSize*5))+1)) - barWrites = append(barWrites, cmn.RandStr((cmn.RandInt()%(dataMaxSize*5))+1)) + fooWrites = append(fooWrites, rand.RandStr((rand.RandInt()%(dataMaxSize*5))+1)) + barWrites = append(barWrites, rand.RandStr((rand.RandInt()%(dataMaxSize*5))+1)) } // A helper that will run with (fooConn, fooWrites, fooReads) and vice versa @@ -370,11 +371,11 @@ func TestNonEd25519Pubkey(t *testing.T) { func createGoldenTestVectors(t *testing.T) string { data := "" for i := 0; i < 32; i++ { - randSecretVector := cmn.RandBytes(32) + randSecretVector := rand.RandBytes(32) randSecret := new([32]byte) copy((*randSecret)[:], randSecretVector) data += hex.EncodeToString((*randSecret)[:]) + "," - locIsLeast := cmn.RandBool() + locIsLeast := rand.RandBool() data += strconv.FormatBool(locIsLeast) + "," recvSecret, sendSecret := deriveSecrets(randSecret, locIsLeast) data += hex.EncodeToString((*recvSecret)[:]) + "," @@ -398,7 +399,7 @@ func BenchmarkWriteSecretConnection(b *testing.B) { } fooWriteBytes := make([][]byte, 0, len(randomMsgSizes)) for _, size := range randomMsgSizes { - fooWriteBytes = append(fooWriteBytes, cmn.RandBytes(size)) + fooWriteBytes = append(fooWriteBytes, rand.RandBytes(size)) } // Consume reads from bar's reader go func() { @@ -416,7 +417,7 @@ func BenchmarkWriteSecretConnection(b *testing.B) { b.StartTimer() for i := 0; i < b.N; i++ { - idx := cmn.RandIntn(len(fooWriteBytes)) + idx := rand.RandIntn(len(fooWriteBytes)) _, err := fooSecConn.Write(fooWriteBytes[idx]) if err != nil { b.Errorf("failed to write to fooSecConn: %v", err) @@ -446,11 +447,11 @@ func BenchmarkReadSecretConnection(b *testing.B) { } fooWriteBytes := make([][]byte, 0, len(randomMsgSizes)) for _, size := range randomMsgSizes { - fooWriteBytes = append(fooWriteBytes, cmn.RandBytes(size)) + fooWriteBytes = append(fooWriteBytes, rand.RandBytes(size)) } go func() { for i := 0; i < b.N; i++ { - idx := cmn.RandIntn(len(fooWriteBytes)) + idx := rand.RandIntn(len(fooWriteBytes)) _, err := fooSecConn.Write(fooWriteBytes[idx]) if err != nil { b.Errorf("failed to write to fooSecConn: %v, %v,%v", err, i, b.N) diff --git a/p2p/fuzz.go b/p2p/fuzz.go index 135155d86..809070b03 100644 --- a/p2p/fuzz.go +++ b/p2p/fuzz.go @@ -6,7 +6,7 @@ import ( "time" "github.com/tendermint/tendermint/config" - cmn "github.com/tendermint/tendermint/libs/common" + "github.com/tendermint/tendermint/libs/rand" ) // FuzzedConnection wraps any net.Conn and depending on the mode either delays @@ -103,7 +103,7 @@ func (fc *FuzzedConnection) SetWriteDeadline(t time.Time) error { func (fc *FuzzedConnection) randomDuration() time.Duration { maxDelayMillis := int(fc.config.MaxDelay.Nanoseconds() / 1000) - return time.Millisecond * time.Duration(cmn.RandInt()%maxDelayMillis) // nolint: gas + return time.Millisecond * time.Duration(rand.RandInt()%maxDelayMillis) // nolint: gas } // implements the fuzz (delay, kill conn) @@ -116,7 +116,7 @@ func (fc *FuzzedConnection) fuzz() bool { switch fc.config.Mode { case config.FuzzModeDrop: // randomly drop the r/w, drop the conn, or sleep - r := cmn.RandFloat64() + r := rand.RandFloat64() switch { case r <= fc.config.ProbDropRW: return true diff --git a/p2p/key_test.go b/p2p/key_test.go index 51e1c0787..44bfb49da 100644 --- a/p2p/key_test.go +++ b/p2p/key_test.go @@ -7,11 +7,11 @@ import ( "testing" "github.com/stretchr/testify/assert" - cmn "github.com/tendermint/tendermint/libs/common" + "github.com/tendermint/tendermint/libs/rand" ) func TestLoadOrGenNodeKey(t *testing.T) { - filePath := filepath.Join(os.TempDir(), cmn.RandStr(12)+"_peer_id.json") + filePath := filepath.Join(os.TempDir(), rand.RandStr(12)+"_peer_id.json") nodeKey, err := LoadOrGenNodeKey(filePath) assert.Nil(t, err) diff --git a/p2p/pex/addrbook.go b/p2p/pex/addrbook.go index 3d7d08794..47adca31d 100644 --- a/p2p/pex/addrbook.go +++ b/p2p/pex/addrbook.go @@ -16,6 +16,7 @@ import ( "github.com/tendermint/tendermint/crypto" cmn "github.com/tendermint/tendermint/libs/common" + tmrand "github.com/tendermint/tendermint/libs/rand" "github.com/tendermint/tendermint/p2p" ) @@ -81,7 +82,7 @@ type addrBook struct { // accessed concurrently mtx sync.Mutex - rand *cmn.Rand + rand *tmrand.Rand ourAddrs map[string]struct{} privateIDs map[p2p.ID]struct{} addrLookup map[p2p.ID]*knownAddress // new & old @@ -102,7 +103,7 @@ type addrBook struct { // Use Start to begin processing asynchronous address updates. func NewAddrBook(filePath string, routabilityStrict bool) *addrBook { am := &addrBook{ - rand: cmn.NewRand(), + rand: tmrand.NewRand(), ourAddrs: make(map[string]struct{}), privateIDs: make(map[p2p.ID]struct{}), addrLookup: make(map[p2p.ID]*knownAddress), @@ -361,7 +362,7 @@ func (a *addrBook) GetSelection() []*p2p.NetAddress { // `numAddresses' since we are throwing the rest. for i := 0; i < numAddresses; i++ { // pick a number between current index and the end - j := cmn.RandIntn(len(allAddr)-i) + i + j := tmrand.RandIntn(len(allAddr)-i) + i allAddr[i], allAddr[j] = allAddr[j], allAddr[i] } diff --git a/p2p/pex/addrbook_test.go b/p2p/pex/addrbook_test.go index be8f2a337..8d424224f 100644 --- a/p2p/pex/addrbook_test.go +++ b/p2p/pex/addrbook_test.go @@ -13,6 +13,7 @@ import ( cmn "github.com/tendermint/tendermint/libs/common" "github.com/tendermint/tendermint/libs/log" + "github.com/tendermint/tendermint/libs/rand" "github.com/tendermint/tendermint/p2p" ) @@ -184,13 +185,13 @@ func randNetAddressPairs(t *testing.T, n int) []netAddressPair { func randIPv4Address(t *testing.T) *p2p.NetAddress { for { ip := fmt.Sprintf("%v.%v.%v.%v", - cmn.RandIntn(254)+1, - cmn.RandIntn(255), - cmn.RandIntn(255), - cmn.RandIntn(255), + rand.RandIntn(254)+1, + rand.RandIntn(255), + rand.RandIntn(255), + rand.RandIntn(255), ) - port := cmn.RandIntn(65535-1) + 1 - id := p2p.ID(hex.EncodeToString(cmn.RandBytes(p2p.IDByteLength))) + port := rand.RandIntn(65535-1) + 1 + id := p2p.ID(hex.EncodeToString(rand.RandBytes(p2p.IDByteLength))) idAddr := p2p.IDAddressString(id, fmt.Sprintf("%v:%v", ip, port)) addr, err := p2p.NewNetAddressString(idAddr) assert.Nil(t, err, "error generating rand network address") @@ -537,7 +538,7 @@ func TestMultipleAddrBookAddressSelection(t *testing.T) { ranges := [...][]int{{33, 100}, {100, 175}} bookSizes := make([]int, 0, len(ranges)) for _, r := range ranges { - bookSizes = append(bookSizes, cmn.RandIntn(r[1]-r[0])+r[0]) + bookSizes = append(bookSizes, rand.RandIntn(r[1]-r[0])+r[0]) } t.Logf("Testing address selection for the following book sizes %v\n", bookSizes) for _, bookSize := range bookSizes { diff --git a/p2p/pex/pex_reactor.go b/p2p/pex/pex_reactor.go index d21218d44..d623100b3 100644 --- a/p2p/pex/pex_reactor.go +++ b/p2p/pex/pex_reactor.go @@ -10,6 +10,7 @@ import ( amino "github.com/tendermint/go-amino" cmn "github.com/tendermint/tendermint/libs/common" + "github.com/tendermint/tendermint/libs/rand" "github.com/tendermint/tendermint/p2p" "github.com/tendermint/tendermint/p2p/conn" ) @@ -397,7 +398,7 @@ func (r *Reactor) SetEnsurePeersPeriod(d time.Duration) { // Ensures that sufficient peers are connected. (continuous) func (r *Reactor) ensurePeersRoutine() { var ( - seed = cmn.NewRand() + seed = rand.NewRand() jitter = seed.Int63n(r.ensurePeersPeriod.Nanoseconds()) ) @@ -494,7 +495,7 @@ func (r *Reactor) ensurePeers() { peers := r.Switch.Peers().List() peersCount := len(peers) if peersCount > 0 { - peer := peers[cmn.RandInt()%peersCount] + peer := peers[rand.RandInt()%peersCount] r.Logger.Info("We need more addresses. Sending pexRequest to random peer", "peer", peer) r.RequestAddrs(peer) } @@ -531,7 +532,7 @@ func (r *Reactor) dialPeer(addr *p2p.NetAddress) error { // exponential backoff if it's not our first attempt to dial given address if attempts > 0 { - jitterSeconds := time.Duration(cmn.RandFloat64() * float64(time.Second)) // 1s == (1e9 ns) + jitterSeconds := time.Duration(rand.RandFloat64() * float64(time.Second)) // 1s == (1e9 ns) backoffDuration := jitterSeconds + ((1 << uint(attempts)) * time.Second) backoffDuration = r.maxBackoffDurationForPeer(addr, backoffDuration) sinceLastDialed := time.Since(lastDialed) @@ -597,7 +598,7 @@ func (r *Reactor) checkSeeds() (numOnline int, netAddrs []*p2p.NetAddress, err e // randomly dial seeds until we connect to one or exhaust them func (r *Reactor) dialSeeds() { - perm := cmn.RandPerm(len(r.seedAddrs)) + perm := rand.RandPerm(len(r.seedAddrs)) // perm := r.Switch.rng.Perm(lSeeds) for _, i := range perm { // dial a random seed diff --git a/p2p/switch.go b/p2p/switch.go index f93ed73f9..4d50e438c 100644 --- a/p2p/switch.go +++ b/p2p/switch.go @@ -10,6 +10,7 @@ import ( "github.com/tendermint/tendermint/config" cmn "github.com/tendermint/tendermint/libs/common" + "github.com/tendermint/tendermint/libs/rand" "github.com/tendermint/tendermint/p2p/conn" ) @@ -86,7 +87,7 @@ type Switch struct { filterTimeout time.Duration peerFilters []PeerFilterFunc - rng *cmn.Rand // seed for randomizing dial times and orders + rng *rand.Rand // seed for randomizing dial times and orders metrics *Metrics } @@ -122,7 +123,7 @@ func NewSwitch( } // Ensure we have a completely undeterministic PRNG. - sw.rng = cmn.NewRand() + sw.rng = rand.NewRand() sw.BaseService = *cmn.NewBaseService(nil, "P2P Switch", sw) diff --git a/p2p/test_util.go b/p2p/test_util.go index f2932be12..7ef50235c 100644 --- a/p2p/test_util.go +++ b/p2p/test_util.go @@ -11,6 +11,7 @@ import ( "github.com/tendermint/tendermint/crypto/ed25519" cmn "github.com/tendermint/tendermint/libs/common" "github.com/tendermint/tendermint/libs/log" + "github.com/tendermint/tendermint/libs/rand" "github.com/tendermint/tendermint/config" "github.com/tendermint/tendermint/p2p/conn" @@ -52,11 +53,11 @@ func CreateRoutableAddr() (addr string, netAddr *NetAddress) { for { var err error addr = fmt.Sprintf("%X@%v.%v.%v.%v:26656", - cmn.RandBytes(20), - cmn.RandInt()%256, - cmn.RandInt()%256, - cmn.RandInt()%256, - cmn.RandInt()%256) + rand.RandBytes(20), + rand.RandInt()%256, + rand.RandInt()%256, + rand.RandInt()%256, + rand.RandInt()%256) netAddr, err = NewNetAddressString(addr) if err != nil { panic(err) diff --git a/privval/signer_client_test.go b/privval/signer_client_test.go index 3d7cfb3e0..04e8087e8 100644 --- a/privval/signer_client_test.go +++ b/privval/signer_client_test.go @@ -8,7 +8,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/tendermint/tendermint/libs/common" + "github.com/tendermint/tendermint/libs/rand" "github.com/tendermint/tendermint/types" ) @@ -24,7 +24,7 @@ func getSignerTestCases(t *testing.T) []signerTestCase { // Get test cases for each possible dialer (DialTCP / DialUnix / etc) for _, dtc := range getDialerTestCases(t) { - chainID := common.RandStr(12) + chainID := rand.RandStr(12) mockPV := types.NewMockPV() // get a pair of signer listener, signer dialer endpoints diff --git a/privval/signer_listener_endpoint_test.go b/privval/signer_listener_endpoint_test.go index 7422776c0..25cfd0877 100644 --- a/privval/signer_listener_endpoint_test.go +++ b/privval/signer_listener_endpoint_test.go @@ -11,6 +11,7 @@ import ( "github.com/tendermint/tendermint/crypto/ed25519" cmn "github.com/tendermint/tendermint/libs/common" "github.com/tendermint/tendermint/libs/log" + "github.com/tendermint/tendermint/libs/rand" "github.com/tendermint/tendermint/types" ) @@ -66,7 +67,7 @@ func TestSignerRemoteRetryTCPOnly(t *testing.T) { SignerDialerEndpointTimeoutReadWrite(time.Millisecond)(dialerEndpoint) SignerDialerEndpointConnRetries(retries)(dialerEndpoint) - chainID := cmn.RandStr(12) + chainID := rand.RandStr(12) mockPV := types.NewMockPV() signerServer := NewSignerServer(dialerEndpoint, chainID, mockPV) @@ -86,7 +87,7 @@ func TestRetryConnToRemoteSigner(t *testing.T) { for _, tc := range getDialerTestCases(t) { var ( logger = log.TestingLogger() - chainID = cmn.RandStr(12) + chainID = rand.RandStr(12) mockPV = types.NewMockPV() endpointIsOpenCh = make(chan struct{}) thisConnTimeout = testTimeoutReadWrite diff --git a/proxy/app_conn_test.go b/proxy/app_conn_test.go index f0b74e687..27fc2ea96 100644 --- a/proxy/app_conn_test.go +++ b/proxy/app_conn_test.go @@ -9,8 +9,8 @@ import ( "github.com/tendermint/tendermint/abci/example/kvstore" "github.com/tendermint/tendermint/abci/server" "github.com/tendermint/tendermint/abci/types" - cmn "github.com/tendermint/tendermint/libs/common" "github.com/tendermint/tendermint/libs/log" + "github.com/tendermint/tendermint/libs/rand" ) //---------------------------------------- @@ -46,7 +46,7 @@ func (app *appConnTest) InfoSync(req types.RequestInfo) (*types.ResponseInfo, er var SOCKET = "socket" func TestEcho(t *testing.T) { - sockPath := fmt.Sprintf("unix:///tmp/echo_%v.sock", cmn.RandStr(6)) + sockPath := fmt.Sprintf("unix:///tmp/echo_%v.sock", rand.RandStr(6)) clientCreator := NewRemoteClientCreator(sockPath, SOCKET, true) // Start server @@ -80,7 +80,7 @@ func TestEcho(t *testing.T) { func BenchmarkEcho(b *testing.B) { b.StopTimer() // Initialize - sockPath := fmt.Sprintf("unix:///tmp/echo_%v.sock", cmn.RandStr(6)) + sockPath := fmt.Sprintf("unix:///tmp/echo_%v.sock", rand.RandStr(6)) clientCreator := NewRemoteClientCreator(sockPath, SOCKET, true) // Start server @@ -119,7 +119,7 @@ func BenchmarkEcho(b *testing.B) { } func TestInfo(t *testing.T) { - sockPath := fmt.Sprintf("unix:///tmp/echo_%v.sock", cmn.RandStr(6)) + sockPath := fmt.Sprintf("unix:///tmp/echo_%v.sock", rand.RandStr(6)) clientCreator := NewRemoteClientCreator(sockPath, SOCKET, true) // Start server diff --git a/rpc/client/event_test.go b/rpc/client/event_test.go index b0a40fc2b..5c98db01c 100644 --- a/rpc/client/event_test.go +++ b/rpc/client/event_test.go @@ -9,7 +9,7 @@ import ( "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" - cmn "github.com/tendermint/tendermint/libs/common" + "github.com/tendermint/tendermint/libs/rand" "github.com/tendermint/tendermint/rpc/client" ctypes "github.com/tendermint/tendermint/rpc/core/types" "github.com/tendermint/tendermint/types" @@ -19,8 +19,8 @@ var waitForEventTimeout = 5 * time.Second // MakeTxKV returns a text transaction, allong with expected key, value pair func MakeTxKV() ([]byte, []byte, []byte) { - k := []byte(cmn.RandStr(8)) - v := []byte(cmn.RandStr(8)) + k := []byte(rand.RandStr(8)) + v := []byte(rand.RandStr(8)) return k, v, append(k, append([]byte("="), v...)...) } diff --git a/rpc/lib/client/ws_client.go b/rpc/lib/client/ws_client.go index 976d24c70..bde6e7168 100644 --- a/rpc/lib/client/ws_client.go +++ b/rpc/lib/client/ws_client.go @@ -15,6 +15,7 @@ import ( amino "github.com/tendermint/go-amino" cmn "github.com/tendermint/tendermint/libs/common" + "github.com/tendermint/tendermint/libs/rand" types "github.com/tendermint/tendermint/rpc/lib/types" ) @@ -288,7 +289,7 @@ func (c *WSClient) reconnect() error { }() for { - jitterSeconds := time.Duration(cmn.RandFloat64() * float64(time.Second)) // 1s == (1e9 ns) + jitterSeconds := time.Duration(rand.RandFloat64() * float64(time.Second)) // 1s == (1e9 ns) backoffDuration := jitterSeconds + ((1 << uint(attempt)) * time.Second) c.Logger.Info("reconnecting", "attempt", attempt+1, "backoff_duration", backoffDuration) diff --git a/rpc/lib/rpc_test.go b/rpc/lib/rpc_test.go index 782ba8ea9..ae5768457 100644 --- a/rpc/lib/rpc_test.go +++ b/rpc/lib/rpc_test.go @@ -19,6 +19,7 @@ import ( amino "github.com/tendermint/go-amino" cmn "github.com/tendermint/tendermint/libs/common" "github.com/tendermint/tendermint/libs/log" + "github.com/tendermint/tendermint/libs/rand" client "github.com/tendermint/tendermint/rpc/lib/client" server "github.com/tendermint/tendermint/rpc/lib/server" @@ -206,7 +207,7 @@ func testWithHTTPClient(t *testing.T, cl client.HTTPClient) { require.Nil(t, err) assert.Equal(t, got3, val3) - val4 := cmn.RandIntn(10000) + val4 := rand.RandIntn(10000) got4, err := echoIntViaHTTP(cl, val4) require.Nil(t, err) assert.Equal(t, got4, val4) @@ -370,7 +371,7 @@ func TestWSClientPingPong(t *testing.T) { } func randBytes(t *testing.T) []byte { - n := cmn.RandIntn(10) + 2 + n := rand.RandIntn(10) + 2 buf := make([]byte, n) _, err := crand.Read(buf) require.Nil(t, err) diff --git a/state/helpers_test.go b/state/helpers_test.go index 00f30ed24..c5a6b054b 100644 --- a/state/helpers_test.go +++ b/state/helpers_test.go @@ -9,7 +9,7 @@ import ( abci "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/crypto/ed25519" - cmn "github.com/tendermint/tendermint/libs/common" + "github.com/tendermint/tendermint/libs/rand" "github.com/tendermint/tendermint/proxy" sm "github.com/tendermint/tendermint/state" "github.com/tendermint/tendermint/types" @@ -64,7 +64,7 @@ func makeAndApplyGoodBlock(state sm.State, height int64, lastCommit *types.Commi return state, types.BlockID{}, err } blockID := types.BlockID{Hash: block.Hash(), - PartsHeader: types.PartSetHeader{Total: 3, Hash: cmn.RandBytes(32)}} + PartsHeader: types.PartSetHeader{Total: 3, Hash: rand.RandBytes(32)}} state, err := blockExec.ApplyBlock(state, blockID, block) if err != nil { return state, types.BlockID{}, err diff --git a/state/state_test.go b/state/state_test.go index a407f49ad..fa2715f52 100644 --- a/state/state_test.go +++ b/state/state_test.go @@ -12,8 +12,8 @@ import ( "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/crypto/ed25519" - cmn "github.com/tendermint/tendermint/libs/common" "github.com/tendermint/tendermint/libs/kv" + "github.com/tendermint/tendermint/libs/rand" sm "github.com/tendermint/tendermint/state" dbm "github.com/tendermint/tm-db" @@ -316,17 +316,17 @@ func TestProposerFrequency(t *testing.T) { maxPower := 1000 nTestCases := 5 for i := 0; i < nTestCases; i++ { - N := cmn.RandInt()%maxVals + 1 + N := rand.RandInt()%maxVals + 1 vals := make([]*types.Validator, N) totalVotePower := int64(0) for j := 0; j < N; j++ { // make sure votePower > 0 - votePower := int64(cmn.RandInt()%maxPower) + 1 + votePower := int64(rand.RandInt()%maxPower) + 1 totalVotePower += votePower privVal := types.NewMockPV() pubKey := privVal.GetPubKey() val := types.NewValidator(pubKey, votePower) - val.ProposerPriority = cmn.RandInt64() + val.ProposerPriority = rand.RandInt64() vals[j] = val } valSet := types.NewValidatorSet(vals) @@ -343,7 +343,7 @@ func genValSetWithPowers(powers []int64) *types.ValidatorSet { for i := 0; i < size; i++ { totalVotePower += powers[i] val := types.NewValidator(ed25519.GenPrivKey().PubKey(), powers[i]) - val.ProposerPriority = cmn.RandInt64() + val.ProposerPriority = rand.RandInt64() vals[i] = val } valSet := types.NewValidatorSet(vals) diff --git a/state/tx_filter_test.go b/state/tx_filter_test.go index 3370368ed..850971b1d 100644 --- a/state/tx_filter_test.go +++ b/state/tx_filter_test.go @@ -7,7 +7,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - cmn "github.com/tendermint/tendermint/libs/common" + "github.com/tendermint/tendermint/libs/rand" sm "github.com/tendermint/tendermint/state" "github.com/tendermint/tendermint/types" dbm "github.com/tendermint/tm-db" @@ -23,12 +23,12 @@ func TestTxFilter(t *testing.T) { tx types.Tx isErr bool }{ - {types.Tx(cmn.RandBytes(250)), false}, - {types.Tx(cmn.RandBytes(1811)), false}, - {types.Tx(cmn.RandBytes(1831)), false}, - {types.Tx(cmn.RandBytes(1838)), true}, - {types.Tx(cmn.RandBytes(1839)), true}, - {types.Tx(cmn.RandBytes(3000)), true}, + {types.Tx(rand.RandBytes(250)), false}, + {types.Tx(rand.RandBytes(1811)), false}, + {types.Tx(rand.RandBytes(1831)), false}, + {types.Tx(rand.RandBytes(1838)), true}, + {types.Tx(rand.RandBytes(1839)), true}, + {types.Tx(rand.RandBytes(3000)), true}, } for i, tc := range testCases { diff --git a/state/txindex/kv/kv_test.go b/state/txindex/kv/kv_test.go index ecdac7260..5546f85d6 100644 --- a/state/txindex/kv/kv_test.go +++ b/state/txindex/kv/kv_test.go @@ -12,9 +12,9 @@ import ( db "github.com/tendermint/tm-db" abci "github.com/tendermint/tendermint/abci/types" - cmn "github.com/tendermint/tendermint/libs/common" "github.com/tendermint/tendermint/libs/kv" "github.com/tendermint/tendermint/libs/pubsub/query" + "github.com/tendermint/tendermint/libs/rand" "github.com/tendermint/tendermint/state/txindex" "github.com/tendermint/tendermint/types" ) @@ -325,7 +325,7 @@ func benchmarkTxIndex(txsCount int64, b *testing.B) { batch := txindex.NewBatch(txsCount) txIndex := uint32(0) for i := int64(0); i < txsCount; i++ { - tx := cmn.RandBytes(250) + tx := rand.RandBytes(250) txResult := &types.TxResult{ Height: 1, Index: txIndex, diff --git a/types/block_test.go b/types/block_test.go index daac8cdec..79a2605f5 100644 --- a/types/block_test.go +++ b/types/block_test.go @@ -18,6 +18,7 @@ import ( "github.com/tendermint/tendermint/crypto/merkle" "github.com/tendermint/tendermint/crypto/tmhash" cmn "github.com/tendermint/tendermint/libs/common" + tmrand "github.com/tendermint/tendermint/libs/rand" tmtime "github.com/tendermint/tendermint/types/time" "github.com/tendermint/tendermint/version" ) @@ -79,7 +80,7 @@ func TestBlockValidateBasic(t *testing.T) { blk.Data.hash = nil // clear hash or change wont be noticed }, true}, {"Tampered DataHash", func(blk *Block) { - blk.DataHash = cmn.RandBytes(len(blk.DataHash)) + blk.DataHash = tmrand.RandBytes(len(blk.DataHash)) }, true}, {"Tampered EvidenceHash", func(blk *Block) { blk.EvidenceHash = []byte("something else") diff --git a/types/event_bus_test.go b/types/event_bus_test.go index edc473f2c..2097080ff 100644 --- a/types/event_bus_test.go +++ b/types/event_bus_test.go @@ -10,10 +10,10 @@ import ( "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" - cmn "github.com/tendermint/tendermint/libs/common" "github.com/tendermint/tendermint/libs/kv" tmpubsub "github.com/tendermint/tendermint/libs/pubsub" tmquery "github.com/tendermint/tendermint/libs/pubsub/query" + "github.com/tendermint/tendermint/libs/rand" ) func TestEventBusPublishEventTx(t *testing.T) { @@ -348,7 +348,7 @@ func BenchmarkEventBus(b *testing.B) { func benchmarkEventBus(numClients int, randQueries bool, randEvents bool, b *testing.B) { // for random* functions - cmn.Seed(time.Now().Unix()) + rand.Seed(time.Now().Unix()) eventBus := NewEventBusWithBufferCapacity(0) // set buffer capacity to 0 so we are not testing cache eventBus.Start() @@ -404,7 +404,7 @@ var events = []string{ EventVote} func randEvent() string { - return events[cmn.RandIntn(len(events))] + return events[rand.RandIntn(len(events))] } var queries = []tmpubsub.Query{ @@ -422,5 +422,5 @@ var queries = []tmpubsub.Query{ EventQueryVote} func randQuery() tmpubsub.Query { - return queries[cmn.RandIntn(len(queries))] + return queries[rand.RandIntn(len(queries))] } diff --git a/types/part_set_test.go b/types/part_set_test.go index f67f4e7c9..b2d1d0596 100644 --- a/types/part_set_test.go +++ b/types/part_set_test.go @@ -8,7 +8,7 @@ import ( "github.com/stretchr/testify/require" "github.com/tendermint/tendermint/crypto/merkle" - cmn "github.com/tendermint/tendermint/libs/common" + "github.com/tendermint/tendermint/libs/rand" ) const ( @@ -17,7 +17,7 @@ const ( func TestBasicPartSet(t *testing.T) { // Construct random data of size partSize * 100 - data := cmn.RandBytes(testPartSize * 100) + data := rand.RandBytes(testPartSize * 100) partSet := NewPartSetFromData(data, testPartSize) assert.NotEmpty(t, partSet.Hash()) @@ -62,7 +62,7 @@ func TestBasicPartSet(t *testing.T) { func TestWrongProof(t *testing.T) { // Construct random data of size partSize * 100 - data := cmn.RandBytes(testPartSize * 100) + data := rand.RandBytes(testPartSize * 100) partSet := NewPartSetFromData(data, testPartSize) // Test adding a part with wrong data. @@ -98,7 +98,7 @@ func TestPartSetHeaderValidateBasic(t *testing.T) { for _, tc := range testCases { tc := tc t.Run(tc.testName, func(t *testing.T) { - data := cmn.RandBytes(testPartSize * 100) + data := rand.RandBytes(testPartSize * 100) ps := NewPartSetFromData(data, testPartSize) psHeader := ps.Header() tc.malleatePartSetHeader(&psHeader) @@ -128,7 +128,7 @@ func TestPartValidateBasic(t *testing.T) { for _, tc := range testCases { tc := tc t.Run(tc.testName, func(t *testing.T) { - data := cmn.RandBytes(testPartSize * 100) + data := rand.RandBytes(testPartSize * 100) ps := NewPartSetFromData(data, testPartSize) part := ps.GetPart(0) tc.malleatePart(part) diff --git a/types/tx_test.go b/types/tx_test.go index 511f4c3a8..6ddd0a088 100644 --- a/types/tx_test.go +++ b/types/tx_test.go @@ -6,20 +6,20 @@ import ( "github.com/stretchr/testify/assert" - cmn "github.com/tendermint/tendermint/libs/common" + "github.com/tendermint/tendermint/libs/rand" ctest "github.com/tendermint/tendermint/libs/test" ) func makeTxs(cnt, size int) Txs { txs := make(Txs, cnt) for i := 0; i < cnt; i++ { - txs[i] = cmn.RandBytes(size) + txs[i] = rand.RandBytes(size) } return txs } func randInt(low, high int) int { - off := cmn.RandInt() % (high - low) + off := rand.RandInt() % (high - low) return low + off } diff --git a/types/validator.go b/types/validator.go index 20069ff9a..3f4d9e241 100644 --- a/types/validator.go +++ b/types/validator.go @@ -6,7 +6,7 @@ import ( "strings" "github.com/tendermint/tendermint/crypto" - cmn "github.com/tendermint/tendermint/libs/common" + "github.com/tendermint/tendermint/libs/rand" ) // Volatile state for each Validator @@ -103,7 +103,7 @@ func RandValidator(randPower bool, minPower int64) (*Validator, PrivValidator) { privVal := NewMockPV() votePower := minPower if randPower { - votePower += int64(cmn.RandUint32()) + votePower += int64(rand.RandUint32()) } pubKey := privVal.GetPubKey() val := NewValidator(pubKey, votePower) diff --git a/types/validator_set_test.go b/types/validator_set_test.go index 91cded710..9cb6d6536 100644 --- a/types/validator_set_test.go +++ b/types/validator_set_test.go @@ -14,6 +14,7 @@ import ( "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/crypto/ed25519" cmn "github.com/tendermint/tendermint/libs/common" + "github.com/tendermint/tendermint/libs/rand" tmtime "github.com/tendermint/tendermint/types/time" ) @@ -283,10 +284,10 @@ func TestProposerSelection3(t *testing.T) { // times is usually 1 times := 1 - mod := (cmn.RandInt() % 5) + 1 - if cmn.RandInt()%mod > 0 { + mod := (rand.RandInt() % 5) + 1 + if rand.RandInt()%mod > 0 { // sometimes its up to 5 - times = (cmn.RandInt() % 4) + 1 + times = (rand.RandInt() % 4) + 1 } vset.IncrementProposerPriority(times) @@ -300,15 +301,15 @@ func newValidator(address []byte, power int64) *Validator { func randPubKey() crypto.PubKey { var pubKey [32]byte - copy(pubKey[:], cmn.RandBytes(32)) + copy(pubKey[:], rand.RandBytes(32)) return ed25519.PubKeyEd25519(pubKey) } func randValidator(totalVotingPower int64) *Validator { // this modulo limits the ProposerPriority/VotingPower to stay in the // bounds of MaxTotalVotingPower minus the already existing voting power: - val := NewValidator(randPubKey(), int64(cmn.RandUint64()%uint64((MaxTotalVotingPower-totalVotingPower)))) - val.ProposerPriority = cmn.RandInt64() % (MaxTotalVotingPower - totalVotingPower) + val := NewValidator(randPubKey(), int64(rand.RandUint64()%uint64((MaxTotalVotingPower-totalVotingPower)))) + val.ProposerPriority = rand.RandInt64() % (MaxTotalVotingPower - totalVotingPower) return val } @@ -708,7 +709,7 @@ func permutation(valList []testVal) []testVal { return nil } permList := make([]testVal, len(valList)) - perm := cmn.RandPerm(len(valList)) + perm := rand.RandPerm(len(valList)) for i, v := range perm { permList[v] = valList[i] } @@ -1110,14 +1111,14 @@ func randTestVSetCfg(t *testing.T, nBase, nAddMax int) testVSetCfg { const maxPower = 1000 var nOld, nDel, nChanged, nAdd int - nOld = int(cmn.RandUint()%uint(nBase)) + 1 + nOld = int(rand.RandUint()%uint(nBase)) + 1 if nBase-nOld > 0 { - nDel = int(cmn.RandUint() % uint(nBase-nOld)) + nDel = int(rand.RandUint() % uint(nBase-nOld)) } nChanged = nBase - nOld - nDel if nAddMax > 0 { - nAdd = cmn.RandInt()%nAddMax + 1 + nAdd = rand.RandInt()%nAddMax + 1 } cfg := testVSetCfg{} @@ -1129,12 +1130,12 @@ func randTestVSetCfg(t *testing.T, nBase, nAddMax int) testVSetCfg { cfg.expectedVals = make([]testVal, nBase-nDel+nAdd) for i := 0; i < nBase; i++ { - cfg.startVals[i] = testVal{fmt.Sprintf("v%d", i), int64(cmn.RandUint()%maxPower + 1)} + cfg.startVals[i] = testVal{fmt.Sprintf("v%d", i), int64(rand.RandUint()%maxPower + 1)} if i < nOld { cfg.expectedVals[i] = cfg.startVals[i] } if i >= nOld && i < nOld+nChanged { - cfg.updatedVals[i-nOld] = testVal{fmt.Sprintf("v%d", i), int64(cmn.RandUint()%maxPower + 1)} + cfg.updatedVals[i-nOld] = testVal{fmt.Sprintf("v%d", i), int64(rand.RandUint()%maxPower + 1)} cfg.expectedVals[i] = cfg.updatedVals[i-nOld] } if i >= nOld+nChanged { @@ -1143,7 +1144,7 @@ func randTestVSetCfg(t *testing.T, nBase, nAddMax int) testVSetCfg { } for i := nBase; i < nBase+nAdd; i++ { - cfg.addedVals[i-nBase] = testVal{fmt.Sprintf("v%d", i), int64(cmn.RandUint()%maxPower + 1)} + cfg.addedVals[i-nBase] = testVal{fmt.Sprintf("v%d", i), int64(rand.RandUint()%maxPower + 1)} cfg.expectedVals[i-nDel] = cfg.addedVals[i-nBase] } @@ -1224,7 +1225,7 @@ func TestValSetUpdatePriorityOrderTests(t *testing.T) { func verifyValSetUpdatePriorityOrder(t *testing.T, valSet *ValidatorSet, cfg testVSetCfg, nMaxElections int) { // Run election up to nMaxElections times, sort validators by priorities - valSet.IncrementProposerPriority(cmn.RandInt()%nMaxElections + 1) + valSet.IncrementProposerPriority(rand.RandInt()%nMaxElections + 1) origValsPriSorted := validatorListCopy(valSet.Validators) sort.Sort(validatorsByPriority(origValsPriSorted)) diff --git a/types/vote_set_test.go b/types/vote_set_test.go index 3755d8c50..865815c76 100644 --- a/types/vote_set_test.go +++ b/types/vote_set_test.go @@ -7,7 +7,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/tendermint/tendermint/crypto" - cmn "github.com/tendermint/tendermint/libs/common" + "github.com/tendermint/tendermint/libs/rand" tmtime "github.com/tendermint/tendermint/types/time" ) @@ -142,7 +142,7 @@ func Test2_3Majority(t *testing.T) { { addr := privValidators[6].GetPubKey().Address() vote := withValidator(voteProto, addr, 6) - _, err := signAddVote(privValidators[6], withBlockHash(vote, cmn.RandBytes(32)), voteSet) + _, err := signAddVote(privValidators[6], withBlockHash(vote, rand.RandBytes(32)), voteSet) if err != nil { t.Error(err) } @@ -247,7 +247,7 @@ func Test2_3MajorityRedux(t *testing.T) { { addr := privValidators[69].GetPubKey().Address() vote := withValidator(voteProto, addr, 69) - _, err := signAddVote(privValidators[69], withBlockHash(vote, cmn.RandBytes(32)), voteSet) + _, err := signAddVote(privValidators[69], withBlockHash(vote, rand.RandBytes(32)), voteSet) if err != nil { t.Error(err) } @@ -300,7 +300,7 @@ func TestBadVotes(t *testing.T) { { addr := privValidators[0].GetPubKey().Address() vote := withValidator(voteProto, addr, 0) - added, err := signAddVote(privValidators[0], withBlockHash(vote, cmn.RandBytes(32)), voteSet) + added, err := signAddVote(privValidators[0], withBlockHash(vote, rand.RandBytes(32)), voteSet) if added || err == nil { t.Errorf("expected VoteSet.Add to fail, conflicting vote.") } @@ -340,8 +340,8 @@ func TestBadVotes(t *testing.T) { func TestConflicts(t *testing.T) { height, round := int64(1), 0 voteSet, _, privValidators := randVoteSet(height, round, PrevoteType, 4, 1) - blockHash1 := cmn.RandBytes(32) - blockHash2 := cmn.RandBytes(32) + blockHash1 := rand.RandBytes(32) + blockHash2 := rand.RandBytes(32) voteProto := &Vote{ ValidatorAddress: nil, @@ -503,8 +503,8 @@ func TestMakeCommit(t *testing.T) { { addr := privValidators[6].GetPubKey().Address() vote := withValidator(voteProto, addr, 6) - vote = withBlockHash(vote, cmn.RandBytes(32)) - vote = withBlockPartsHeader(vote, PartSetHeader{123, cmn.RandBytes(32)}) + vote = withBlockHash(vote, rand.RandBytes(32)) + vote = withBlockPartsHeader(vote, PartSetHeader{123, rand.RandBytes(32)}) _, err := signAddVote(privValidators[6], vote, voteSet) if err != nil {