Browse Source

lint: golint issue fixes (#4258)

* lint: golint issue fixes

- on my local machine golint is a lot stricter than the bot so slowly going through and fixing things.

Signed-off-by: Marko Baricevic <marbar3778@yahoo.com>

* more fixes from golint

* remove isPeerPersistentFn

* add changelog entry
pull/4259/head
Marko 4 years ago
committed by GitHub
parent
commit
9bd0f9e634
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
56 changed files with 246 additions and 246 deletions
  1. +1
    -0
      CHANGELOG_PENDING.md
  2. +2
    -2
      abci/client/socket_client_test.go
  3. +3
    -3
      abci/example/kvstore/helpers.go
  4. +3
    -3
      abci/tests/server/client.go
  5. +3
    -3
      blockchain/v0/pool_test.go
  6. +9
    -9
      blockchain/v1/peer_test.go
  7. +7
    -7
      blockchain/v1/reactor_fsm_test.go
  8. +2
    -2
      cmd/tendermint/commands/init.go
  9. +3
    -3
      cmd/tendermint/commands/testnet.go
  10. +3
    -3
      consensus/replay_test.go
  11. +2
    -2
      consensus/state_test.go
  12. +13
    -13
      consensus/types/round_state_test.go
  13. +2
    -2
      consensus/wal_generator.go
  14. +5
    -5
      crypto/merkle/simple_tree_test.go
  15. +1
    -1
      crypto/multisig/bitarray/compact_bit_array_test.go
  16. +1
    -2
      crypto/sr25519/privkey.go
  17. +1
    -2
      crypto/sr25519/pubkey.go
  18. +2
    -2
      libs/autofile/autofile.go
  19. +7
    -7
      libs/autofile/group_test.go
  20. +2
    -2
      libs/bits/bit_array.go
  21. +2
    -2
      libs/bits/bit_array_test.go
  22. +4
    -4
      libs/clist/clist_test.go
  23. +20
    -20
      libs/rand/random.go
  24. +17
    -17
      libs/rand/random_test.go
  25. +3
    -3
      libs/tempfile/tempfile_test.go
  26. +4
    -4
      libs/test/mutate.go
  27. +1
    -1
      lite/dbprovider.go
  28. +2
    -2
      lite2/client.go
  29. +3
    -3
      mempool/clist_mempool_test.go
  30. +4
    -4
      node/node_test.go
  31. +11
    -11
      p2p/conn/secret_connection_test.go
  32. +3
    -3
      p2p/fuzz.go
  33. +2
    -2
      p2p/key_test.go
  34. +1
    -1
      p2p/pex/addrbook.go
  35. +8
    -8
      p2p/pex/addrbook_test.go
  36. +4
    -3
      p2p/pex/pex_reactor.go
  37. +4
    -6
      p2p/switch.go
  38. +4
    -4
      p2p/switch_test.go
  39. +6
    -6
      p2p/test_util.go
  40. +2
    -2
      privval/signer_client_test.go
  41. +3
    -3
      privval/signer_listener_endpoint_test.go
  42. +4
    -4
      proxy/app_conn_test.go
  43. +3
    -3
      rpc/client/event_test.go
  44. +2
    -2
      rpc/lib/client/ws_client.go
  45. +3
    -3
      rpc/lib/rpc_test.go
  46. +2
    -2
      state/helpers_test.go
  47. +5
    -4
      state/state_test.go
  48. +7
    -7
      state/tx_filter_test.go
  49. +2
    -2
      state/txindex/kv/kv_test.go
  50. +1
    -1
      types/block_test.go
  51. +4
    -3
      types/event_bus_test.go
  52. +5
    -5
      types/part_set_test.go
  53. +3
    -3
      types/tx_test.go
  54. +2
    -2
      types/validator.go
  55. +15
    -15
      types/validator_set_test.go
  56. +8
    -8
      types/vote_set_test.go

+ 1
- 0
CHANGELOG_PENDING.md View File

@ -84,6 +84,7 @@ program](https://hackerone.com/tendermint).
- [libs/common] \#4240 Move async functions out of `libs/common` to `async` pkg
- [libs/common] \#4240 Move bit functions out of `libs/common` to `bits` pkg
- [libs/common] \#4240 Move cmap functions out of `libs/common` to `cmap` pkg
- [libs/common] \#4258 Remove `Rand` from all `rand` pkg functions
- Blockchain Protocol


+ 2
- 2
abci/client/socket_client_test.go View File

@ -12,7 +12,7 @@ import (
abcicli "github.com/tendermint/tendermint/abci/client"
"github.com/tendermint/tendermint/abci/server"
"github.com/tendermint/tendermint/abci/types"
"github.com/tendermint/tendermint/libs/rand"
tmrand "github.com/tendermint/tendermint/libs/rand"
"github.com/tendermint/tendermint/libs/service"
)
@ -97,7 +97,7 @@ func TestHangingSyncCalls(t *testing.T) {
func setupClientServer(t *testing.T, app types.Application) (
service.Service, abcicli.Client) {
// some port between 20k and 30k
port := 20000 + rand.RandInt32()%10000
port := 20000 + tmrand.Int32()%10000
addr := fmt.Sprintf("localhost:%d", port)
s, err := server.NewServer(addr, "socket", app)


+ 3
- 3
abci/example/kvstore/helpers.go View File

@ -2,14 +2,14 @@ package kvstore
import (
"github.com/tendermint/tendermint/abci/types"
"github.com/tendermint/tendermint/libs/rand"
tmrand "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 := rand.RandBytes(32)
power := rand.RandUint16() + 1
pubkey := tmrand.Bytes(32)
power := tmrand.Uint16() + 1
v := types.Ed25519ValidatorUpdate(pubkey, int64(power))
return v
}


+ 3
- 3
abci/tests/server/client.go View File

@ -7,15 +7,15 @@ import (
abcicli "github.com/tendermint/tendermint/abci/client"
"github.com/tendermint/tendermint/abci/types"
"github.com/tendermint/tendermint/libs/rand"
tmrand "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 := rand.RandBytes(33)
power := rand.RandInt()
pubkey := tmrand.Bytes(33)
power := tmrand.Int()
vals[i] = types.Ed25519ValidatorUpdate(pubkey, int64(power))
}
_, err := client.InitChainSync(types.RequestInitChain{


+ 3
- 3
blockchain/v0/pool_test.go View File

@ -9,7 +9,7 @@ import (
"github.com/stretchr/testify/require"
"github.com/tendermint/tendermint/libs/log"
"github.com/tendermint/tendermint/libs/rand"
tmrand "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(rand.RandStr(12))
height := minHeight + rand.RandInt63n(maxHeight-minHeight)
peerID := p2p.ID(tmrand.Str(12))
height := minHeight + tmrand.Int63n(maxHeight-minHeight)
peers[peerID] = testPeer{peerID, height, make(chan inputData, 10)}
}
return peers


+ 9
- 9
blockchain/v1/peer_test.go View File

@ -9,14 +9,14 @@ import (
"github.com/stretchr/testify/require"
"github.com/tendermint/tendermint/libs/log"
"github.com/tendermint/tendermint/libs/rand"
tmrand "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(rand.RandStr(12)), 10,
p2p.ID(tmrand.Str(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(rand.RandStr(12)), 10,
p2p.ID(tmrand.Str(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(rand.RandStr(12)), 10,
p2p.ID(tmrand.Str(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(rand.RandStr(12)), 100,
p2p.ID(tmrand.Str(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(rand.RandStr(12)), 100,
p2p.ID(tmrand.Str(12)), 100,
func(err error, _ p2p.ID) {},
nil)
@ -189,7 +189,7 @@ func TestPeerOnErrFuncCalledDueToExpiration(t *testing.T) {
)
peer := NewBpPeer(
p2p.ID(rand.RandStr(12)), 10,
p2p.ID(tmrand.Str(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(rand.RandStr(12)), 10,
p2p.ID(tmrand.Str(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(rand.RandStr(12)), 10,
p2p.ID(tmrand.Str(12)), 10,
func(err error, _ p2p.ID) {},
params)
peer.SetLogger(log.TestingLogger())


+ 7
- 7
blockchain/v1/reactor_fsm_test.go View File

@ -8,7 +8,7 @@ import (
"github.com/stretchr/testify/assert"
"github.com/tendermint/tendermint/libs/log"
tmmath "github.com/tendermint/tendermint/libs/math"
"github.com/tendermint/tendermint/libs/rand"
tmrand "github.com/tendermint/tendermint/libs/rand"
"github.com/tendermint/tendermint/p2p"
"github.com/tendermint/tendermint/types"
)
@ -736,7 +736,7 @@ func makeCorrectTransitionSequence(startingHeight int64, numBlocks int64, numPee
continue
}
if randomPeerHeights {
peerHeights[i] = int64(tmmath.MaxInt(rand.RandIntn(int(numBlocks)), int(startingHeight)+1))
peerHeights[i] = int64(tmmath.MaxInt(tmrand.Intn(int(numBlocks)), int(startingHeight)+1))
} else {
peerHeights[i] = numBlocks
}
@ -826,19 +826,19 @@ const (
func makeCorrectTransitionSequenceWithRandomParameters() testFields {
// Generate a starting height for fast sync.
startingHeight := int64(rand.RandIntn(maxStartingHeightTest) + 1)
startingHeight := int64(tmrand.Intn(maxStartingHeightTest) + 1)
// Generate the number of requests per peer.
maxRequestsPerPeer := rand.RandIntn(maxRequestsPerPeerTest) + 1
maxRequestsPerPeer := tmrand.Intn(maxRequestsPerPeerTest) + 1
// Generate the maximum number of total pending requests, >= maxRequestsPerPeer.
maxPendingRequests := rand.RandIntn(maxTotalPendingRequestsTest-maxRequestsPerPeer) + maxRequestsPerPeer
maxPendingRequests := tmrand.Intn(maxTotalPendingRequestsTest-maxRequestsPerPeer) + maxRequestsPerPeer
// Generate the number of blocks to be synced.
numBlocks := int64(rand.RandIntn(maxNumBlocksInChainTest)) + startingHeight
numBlocks := int64(tmrand.Intn(maxNumBlocksInChainTest)) + startingHeight
// Generate a number of peers.
numPeers := rand.RandIntn(maxNumPeersTest) + 1
numPeers := tmrand.Intn(maxNumPeersTest) + 1
return makeCorrectTransitionSequence(startingHeight, numBlocks, numPeers, true, maxRequestsPerPeer, maxPendingRequests)
}


+ 2
- 2
cmd/tendermint/commands/init.go View File

@ -6,7 +6,7 @@ import (
"github.com/spf13/cobra"
cfg "github.com/tendermint/tendermint/config"
tmos "github.com/tendermint/tendermint/libs/os"
"github.com/tendermint/tendermint/libs/rand"
tmrand "github.com/tendermint/tendermint/libs/rand"
"github.com/tendermint/tendermint/p2p"
"github.com/tendermint/tendermint/privval"
"github.com/tendermint/tendermint/types"
@ -56,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", rand.RandStr(6)),
ChainID: fmt.Sprintf("test-chain-%v", tmrand.Str(6)),
GenesisTime: tmtime.Now(),
ConsensusParams: types.DefaultConsensusParams(),
}


+ 3
- 3
cmd/tendermint/commands/testnet.go View File

@ -12,7 +12,7 @@ import (
cfg "github.com/tendermint/tendermint/config"
"github.com/tendermint/tendermint/libs/bytes"
"github.com/tendermint/tendermint/libs/rand"
tmrand "github.com/tendermint/tendermint/libs/rand"
"github.com/tendermint/tendermint/p2p"
"github.com/tendermint/tendermint/privval"
"github.com/tendermint/tendermint/types"
@ -168,7 +168,7 @@ func testnetFiles(cmd *cobra.Command, args []string) error {
// Generate genesis doc from generated validators
genDoc := &types.GenesisDoc{
ChainID: "chain-" + rand.RandStr(6),
ChainID: "chain-" + tmrand.Str(6),
ConsensusParams: types.DefaultConsensusParams(),
GenesisTime: tmtime.Now(),
Validators: genVals,
@ -262,5 +262,5 @@ func moniker(i int) string {
}
func randomMoniker() string {
return bytes.HexBytes(rand.RandBytes(8)).String()
return bytes.HexBytes(tmrand.Bytes(8)).String()
}

+ 3
- 3
consensus/replay_test.go View File

@ -22,7 +22,7 @@ import (
cfg "github.com/tendermint/tendermint/config"
"github.com/tendermint/tendermint/crypto"
"github.com/tendermint/tendermint/libs/log"
"github.com/tendermint/tendermint/libs/rand"
tmrand "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: rand.RandBytes(8)}
return abci.ResponseCommit{Data: tmrand.Bytes(8)}
}
return abci.ResponseCommit{Data: []byte{app.height}}
} else if app.allHashesAreWrong {
return abci.ResponseCommit{Data: rand.RandBytes(8)}
return abci.ResponseCommit{Data: tmrand.Bytes(8)}
}
panic("either allHashesAreWrong or onlyLastHashIsWrong must be set")


+ 2
- 2
consensus/state_test.go View File

@ -13,7 +13,7 @@ import (
cstypes "github.com/tendermint/tendermint/consensus/types"
"github.com/tendermint/tendermint/libs/log"
tmpubsub "github.com/tendermint/tendermint/libs/pubsub"
"github.com/tendermint/tendermint/libs/rand"
tmrand "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(rand.RandBytes(100), 10)
parts := types.NewPartSetFromData(tmrand.Bytes(100), 10)
msg := &BlockPartMessage{
Height: 1,
Round: 0,


+ 13
- 13
consensus/types/round_state_test.go View File

@ -6,7 +6,7 @@ import (
amino "github.com/tendermint/go-amino"
"github.com/tendermint/tendermint/crypto/ed25519"
"github.com/tendermint/tendermint/crypto/tmhash"
"github.com/tendermint/tendermint/libs/rand"
tmrand "github.com/tendermint/tendermint/libs/rand"
"github.com/tendermint/tendermint/types"
tmtime "github.com/tendermint/tendermint/types/time"
)
@ -19,16 +19,16 @@ func BenchmarkRoundStateDeepCopy(b *testing.B) {
vset, _ := types.RandValidatorSet(nval, 1)
commitSigs := make([]types.CommitSig, nval)
blockID := types.BlockID{
Hash: rand.RandBytes(tmhash.Size),
Hash: tmrand.Bytes(tmhash.Size),
PartsHeader: types.PartSetHeader{
Hash: rand.RandBytes(tmhash.Size),
Hash: tmrand.Bytes(tmhash.Size),
Total: 1000,
},
}
sig := make([]byte, ed25519.SignatureSize)
for i := 0; i < nval; i++ {
commitSigs[i] = (&types.Vote{
ValidatorAddress: types.Address(rand.RandBytes(20)),
ValidatorAddress: types.Address(tmrand.Bytes(20)),
Timestamp: tmtime.Now(),
BlockID: blockID,
Signature: sig,
@ -36,21 +36,21 @@ func BenchmarkRoundStateDeepCopy(b *testing.B) {
}
txs := make([]types.Tx, ntxs)
for i := 0; i < ntxs; i++ {
txs[i] = rand.RandBytes(100)
txs[i] = tmrand.Bytes(100)
}
// Random block
block := &types.Block{
Header: types.Header{
ChainID: rand.RandStr(12),
ChainID: tmrand.Str(12),
Time: tmtime.Now(),
LastBlockID: blockID,
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),
LastCommitHash: tmrand.Bytes(20),
DataHash: tmrand.Bytes(20),
ValidatorsHash: tmrand.Bytes(20),
ConsensusHash: tmrand.Bytes(20),
AppHash: tmrand.Bytes(20),
LastResultsHash: tmrand.Bytes(20),
EvidenceHash: tmrand.Bytes(20),
},
Data: types.Data{
Txs: txs,


+ 2
- 2
consensus/wal_generator.go View File

@ -14,7 +14,7 @@ import (
"github.com/tendermint/tendermint/abci/example/kvstore"
cfg "github.com/tendermint/tendermint/config"
"github.com/tendermint/tendermint/libs/log"
"github.com/tendermint/tendermint/libs/rand"
tmrand "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 + rand.RandIntn(spread)
return base + tmrand.Intn(spread)
}
func makeAddrs() (string, string, string) {


+ 5
- 5
crypto/merkle/simple_tree_test.go View File

@ -5,7 +5,7 @@ import (
"github.com/stretchr/testify/require"
"github.com/tendermint/tendermint/libs/rand"
tmrand "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(rand.RandBytes(tmhash.Size))
items[i] = testItem(tmrand.Bytes(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, rand.RandBytes(32))
proof.Aunts = append(proof.Aunts, tmrand.Bytes(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(rand.RandBytes(tmhash.Size))
items[i] = testItem(tmrand.Bytes(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(rand.RandBytes(tmhash.Size))
items[i] = testItem(tmrand.Bytes(tmhash.Size))
}
b.ResetTimer()


+ 1
- 1
crypto/multisig/bitarray/compact_bit_array_test.go View File

@ -12,7 +12,7 @@ import (
func randCompactBitArray(bits int) (*CompactBitArray, []byte) {
numBytes := (bits + 7) / 8
src := tmrand.RandBytes((bits + 7) / 8)
src := tmrand.Bytes((bits + 7) / 8)
bA := NewCompactBitArray(bits)
for i := 0; i < numBytes-1; i++ {


+ 1
- 2
crypto/sr25519/privkey.go View File

@ -59,9 +59,8 @@ func (privKey PrivKeySr25519) PubKey() crypto.PubKey {
func (privKey PrivKeySr25519) Equals(other crypto.PrivKey) bool {
if otherEd, ok := other.(PrivKeySr25519); ok {
return subtle.ConstantTimeCompare(privKey[:], otherEd[:]) == 1
} else {
return false
}
return false
}
// GenPrivKey generates a new sr25519 private key.


+ 1
- 2
crypto/sr25519/pubkey.go View File

@ -66,7 +66,6 @@ func (pubKey PubKeySr25519) String() string {
func (pubKey PubKeySr25519) Equals(other crypto.PubKey) bool {
if otherEd, ok := other.(PubKeySr25519); ok {
return bytes.Equal(pubKey[:], otherEd[:])
} else {
return false
}
return false
}

+ 2
- 2
libs/autofile/autofile.go View File

@ -7,7 +7,7 @@ import (
"syscall"
"time"
"github.com/tendermint/tendermint/libs/rand"
tmrand "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: rand.RandStr(12) + ":" + path,
ID: tmrand.Str(12) + ":" + path,
Path: path,
closeTicker: time.NewTicker(autoFileClosePeriod),
closeTickerStopc: make(chan struct{}),


+ 7
- 7
libs/autofile/group_test.go View File

@ -10,11 +10,11 @@ import (
"github.com/stretchr/testify/require"
tmos "github.com/tendermint/tendermint/libs/os"
"github.com/tendermint/tendermint/libs/rand"
tmrand "github.com/tendermint/tendermint/libs/rand"
)
func createTestGroupWithHeadSizeLimit(t *testing.T, headSizeLimit int64) *Group {
testID := rand.RandStr(12)
testID := tmrand.Str(12)
testDir := "_test_" + testID
err := tmos.EnsureDir(testDir, 0700)
require.NoError(t, err, "Error creating dir")
@ -49,7 +49,7 @@ func TestCheckHeadSizeLimit(t *testing.T) {
// Write 1000 bytes 999 times.
for i := 0; i < 999; i++ {
err := g.WriteLine(rand.RandStr(999))
err := g.WriteLine(tmrand.Str(999))
require.NoError(t, err, "Error appending to head")
}
g.FlushAndSync()
@ -60,7 +60,7 @@ func TestCheckHeadSizeLimit(t *testing.T) {
assertGroupInfo(t, g.ReadGroupInfo(), 0, 0, 999000, 999000)
// Write 1000 more bytes.
err := g.WriteLine(rand.RandStr(999))
err := g.WriteLine(tmrand.Str(999))
require.NoError(t, err, "Error appending to head")
g.FlushAndSync()
@ -69,7 +69,7 @@ func TestCheckHeadSizeLimit(t *testing.T) {
assertGroupInfo(t, g.ReadGroupInfo(), 0, 1, 1000000, 0)
// Write 1000 more bytes.
err = g.WriteLine(rand.RandStr(999))
err = g.WriteLine(tmrand.Str(999))
require.NoError(t, err, "Error appending to head")
g.FlushAndSync()
@ -79,7 +79,7 @@ func TestCheckHeadSizeLimit(t *testing.T) {
// Write 1000 bytes 999 times.
for i := 0; i < 999; i++ {
err = g.WriteLine(rand.RandStr(999))
err = g.WriteLine(tmrand.Str(999))
require.NoError(t, err, "Error appending to head")
}
g.FlushAndSync()
@ -90,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(rand.RandStr(999) + "\n"))
_, err = g.Head.Write([]byte(tmrand.Str(999) + "\n"))
require.NoError(t, err, "Error appending to head")
g.FlushAndSync()
assertGroupInfo(t, g.ReadGroupInfo(), 0, 2, 2001000, 1000)


+ 2
- 2
libs/bits/bit_array.go View File

@ -8,7 +8,7 @@ import (
"sync"
tmmath "github.com/tendermint/tendermint/libs/math"
"github.com/tendermint/tendermint/libs/rand"
tmrand "github.com/tendermint/tendermint/libs/rand"
)
// BitArray is a thread-safe implementation of a bit array.
@ -253,7 +253,7 @@ func (bA *BitArray) PickRandom() (int, bool) {
return 0, false
}
return trueIndices[rand.RandIntn(len(trueIndices))], true
return trueIndices[tmrand.Intn(len(trueIndices))], true
}
func (bA *BitArray) getTrueIndices() []int {


+ 2
- 2
libs/bits/bit_array_test.go View File

@ -9,11 +9,11 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/tendermint/tendermint/libs/rand"
tmrand "github.com/tendermint/tendermint/libs/rand"
)
func randBitArray(bits int) (*BitArray, []byte) {
src := rand.RandBytes((bits + 7) / 8)
src := tmrand.Bytes((bits + 7) / 8)
bA := NewBitArray(bits)
for i := 0; i < len(src); i++ {
for j := 0; j < 8; j++ {


+ 4
- 4
libs/clist/clist_test.go View File

@ -8,7 +8,7 @@ import (
"time"
"github.com/stretchr/testify/assert"
"github.com/tendermint/tendermint/libs/rand"
tmrand "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 rand.RandPerm(numElements) {
for _, i := range tmrand.Perm(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 := rand.RandIntn(len(els))
rmElIdx := tmrand.Intn(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(rand.RandIntn(25)) * time.Millisecond)
time.Sleep(time.Duration(tmrand.Intn(25)) * time.Millisecond)
}
// apply a deterministic pause so the counter has time to catch up
time.Sleep(25 * time.Millisecond)


+ 20
- 20
libs/rand/random.go View File

@ -57,83 +57,83 @@ func Seed(seed int64) {
grand.Seed(seed)
}
func RandStr(length int) string {
func Str(length int) string {
return grand.Str(length)
}
func RandUint16() uint16 {
func Uint16() uint16 {
return grand.Uint16()
}
func RandUint32() uint32 {
func Uint32() uint32 {
return grand.Uint32()
}
func RandUint64() uint64 {
func Uint64() uint64 {
return grand.Uint64()
}
func RandUint() uint {
func Uint() uint {
return grand.Uint()
}
func RandInt16() int16 {
func Int16() int16 {
return grand.Int16()
}
func RandInt32() int32 {
func Int32() int32 {
return grand.Int32()
}
func RandInt64() int64 {
func Int64() int64 {
return grand.Int64()
}
func RandInt() int {
func Int() int {
return grand.Int()
}
func RandInt31() int32 {
func Int31() int32 {
return grand.Int31()
}
func RandInt31n(n int32) int32 {
func Int31n(n int32) int32 {
return grand.Int31n(n)
}
func RandInt63() int64 {
func Int63() int64 {
return grand.Int63()
}
func RandInt63n(n int64) int64 {
func Int63n(n int64) int64 {
return grand.Int63n(n)
}
func RandBool() bool {
func Bool() bool {
return grand.Bool()
}
func RandFloat32() float32 {
func Float32() float32 {
return grand.Float32()
}
func RandFloat64() float64 {
func Float64() float64 {
return grand.Float64()
}
func RandTime() time.Time {
func Time() time.Time {
return grand.Time()
}
func RandBytes(n int) []byte {
func Bytes(n int) []byte {
return grand.Bytes(n)
}
func RandIntn(n int) int {
func Intn(n int) int {
return grand.Intn(n)
}
func RandPerm(n int) []int {
func Perm(n int) []int {
return grand.Perm(n)
}


+ 17
- 17
libs/rand/random_test.go View File

@ -14,20 +14,20 @@ import (
func TestRandStr(t *testing.T) {
l := 243
s := RandStr(l)
s := Str(l)
assert.Equal(t, l, len(s))
}
func TestRandBytes(t *testing.T) {
l := 243
b := RandBytes(l)
b := Bytes(l)
assert.Equal(t, l, len(b))
}
func TestRandIntn(t *testing.T) {
n := 243
for i := 0; i < 100; i++ {
x := RandIntn(n)
x := Intn(n)
assert.True(t, x < n)
}
}
@ -59,18 +59,18 @@ func testThemAll() string {
// Use it.
out := new(bytes.Buffer)
perm := RandPerm(10)
perm := Perm(10)
blob, _ := json.Marshal(perm)
fmt.Fprintf(out, "perm: %s\n", blob)
fmt.Fprintf(out, "randInt: %d\n", RandInt())
fmt.Fprintf(out, "randUint: %d\n", RandUint())
fmt.Fprintf(out, "randIntn: %d\n", RandIntn(97))
fmt.Fprintf(out, "randInt31: %d\n", RandInt31())
fmt.Fprintf(out, "randInt32: %d\n", RandInt32())
fmt.Fprintf(out, "randInt63: %d\n", RandInt63())
fmt.Fprintf(out, "randInt64: %d\n", RandInt64())
fmt.Fprintf(out, "randUint32: %d\n", RandUint32())
fmt.Fprintf(out, "randUint64: %d\n", RandUint64())
fmt.Fprintf(out, "randInt: %d\n", Int())
fmt.Fprintf(out, "randUint: %d\n", Uint())
fmt.Fprintf(out, "randIntn: %d\n", Intn(97))
fmt.Fprintf(out, "randInt31: %d\n", Int31())
fmt.Fprintf(out, "randInt32: %d\n", Int32())
fmt.Fprintf(out, "randInt63: %d\n", Int63())
fmt.Fprintf(out, "randInt64: %d\n", Int64())
fmt.Fprintf(out, "randUint32: %d\n", Uint32())
fmt.Fprintf(out, "randUint64: %d\n", Uint64())
return out.String()
}
@ -81,9 +81,9 @@ func TestRngConcurrencySafety(t *testing.T) {
go func() {
defer wg.Done()
_ = RandUint64()
<-time.After(time.Millisecond * time.Duration(RandIntn(100)))
_ = RandPerm(3)
_ = Uint64()
<-time.After(time.Millisecond * time.Duration(Intn(100)))
_ = Perm(3)
}()
}
wg.Wait()
@ -110,7 +110,7 @@ func BenchmarkRandBytes1MiB(b *testing.B) {
func benchmarkRandBytes(b *testing.B, n int) {
for i := 0; i < b.N; i++ {
_ = RandBytes(n)
_ = Bytes(n)
}
b.ReportAllocs()
}

+ 3
- 3
libs/tempfile/tempfile_test.go View File

@ -11,13 +11,13 @@ import (
"github.com/stretchr/testify/require"
"github.com/tendermint/tendermint/libs/rand"
tmrand "github.com/tendermint/tendermint/libs/rand"
)
func TestWriteFileAtomic(t *testing.T) {
var (
data = []byte(rand.RandStr(rand.RandIntn(2048)))
old = rand.RandBytes(rand.RandIntn(2048))
data = []byte(tmrand.Str(tmrand.Intn(2048)))
old = tmrand.Bytes(tmrand.Intn(2048))
perm os.FileMode = 0600
)


+ 4
- 4
libs/test/mutate.go View File

@ -1,7 +1,7 @@
package test
import (
"github.com/tendermint/tendermint/libs/rand"
tmrand "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 rand.RandInt() % 2 {
switch tmrand.Int() % 2 {
case 0: // Mutate a single byte
bytez[rand.RandInt()%len(bytez)] += byte(rand.RandInt()%255 + 1)
bytez[tmrand.Int()%len(bytez)] += byte(tmrand.Int()%255 + 1)
case 1: // Remove an arbitrary byte
pos := rand.RandInt() % len(bytez)
pos := tmrand.Int() % len(bytez)
bytez = append(bytez[:pos], bytez[pos+1:]...)
}
return bytez


+ 1
- 1
lite/dbprovider.go View File

@ -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 "+rand.RandStr(4), db)
//db = dbm.NewDebugDB("db provider "+tmrand.Str(4), db)
cdc := amino.NewCodec()
cryptoamino.RegisterAmino(cdc)


+ 2
- 2
lite2/client.go View File

@ -9,7 +9,7 @@ import (
"github.com/tendermint/tendermint/libs/log"
tmmath "github.com/tendermint/tendermint/libs/math"
"github.com/tendermint/tendermint/libs/rand"
tmrand "github.com/tendermint/tendermint/libs/rand"
"github.com/tendermint/tendermint/lite2/provider"
"github.com/tendermint/tendermint/lite2/store"
"github.com/tendermint/tendermint/types"
@ -422,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[rand.RandIntn(len(c.alternatives))]
p := c.alternatives[tmrand.Intn(len(c.alternatives))]
// 2. Fetch the header.
altHeader, err := p.SignedHeader(h.Height)


+ 3
- 3
mempool/clist_mempool_test.go View File

@ -456,7 +456,7 @@ func TestMempoolMaxMsgSize(t *testing.T) {
for i, testCase := range testCases {
caseString := fmt.Sprintf("case %d, len %d", i, testCase.len)
tx := tmrand.RandBytes(testCase.len)
tx := tmrand.Bytes(testCase.len)
err := mempl.CheckTx(tx, nil, TxInfo{})
msg := &TxMessage{tx}
encoded := cdc.MustMarshalBinaryBare(msg)
@ -543,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", tmrand.RandStr(6))
sockPath := fmt.Sprintf("unix:///tmp/echo_%v.sock", tmrand.Str(6))
app := kvstore.NewApplication()
cc, server := newRemoteApp(t, sockPath, app)
defer server.Stop()
@ -556,7 +556,7 @@ func TestMempoolRemoteAppConcurrency(t *testing.T) {
txLen := 200
txs := make([]types.Tx, nTxs)
for i := 0; i < nTxs; i++ {
txs[i] = tmrand.RandBytes(txLen)
txs[i] = tmrand.Bytes(txLen)
}
// simulate a group of peers sending them over and over


+ 4
- 4
node/node_test.go View File

@ -17,7 +17,7 @@ import (
"github.com/tendermint/tendermint/crypto/ed25519"
"github.com/tendermint/tendermint/evidence"
"github.com/tendermint/tendermint/libs/log"
"github.com/tendermint/tendermint/libs/rand"
tmrand "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." + rand.RandStr(6) + ".sock"
tmpfile := "/tmp/kms." + tmrand.Str(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, rand.RandBytes(minEvSize))
ev := types.NewMockRandomGoodEvidence(1, proposerAddr, tmrand.Bytes(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 := rand.RandBytes(txLength)
tx := tmrand.Bytes(txLength)
err := mempool.CheckTx(tx, nil, mempl.TxInfo{})
assert.NoError(t, err)
}


+ 11
- 11
p2p/conn/secret_connection_test.go View File

@ -21,7 +21,7 @@ import (
"github.com/tendermint/tendermint/crypto/secp256k1"
"github.com/tendermint/tendermint/libs/async"
tmos "github.com/tendermint/tendermint/libs/os"
"github.com/tendermint/tendermint/libs/rand"
tmrand "github.com/tendermint/tendermint/libs/rand"
)
type kvstoreConn struct {
@ -105,7 +105,7 @@ func TestSecretConnectionHandshake(t *testing.T) {
func TestConcurrentWrite(t *testing.T) {
fooSecConn, barSecConn := makeSecretConnPair(t)
fooWriteText := rand.RandStr(dataMaxSize)
fooWriteText := tmrand.Str(dataMaxSize)
// write from two routines.
// should be safe from race according to net.Conn:
@ -127,7 +127,7 @@ func TestConcurrentWrite(t *testing.T) {
func TestConcurrentRead(t *testing.T) {
fooSecConn, barSecConn := makeSecretConnPair(t)
fooWriteText := rand.RandStr(dataMaxSize)
fooWriteText := tmrand.Str(dataMaxSize)
n := 100
// read from two routines.
@ -174,8 +174,8 @@ func TestSecretConnectionReadWrite(t *testing.T) {
// Pre-generate the things to write (for foo & bar)
for i := 0; i < 100; i++ {
fooWrites = append(fooWrites, rand.RandStr((rand.RandInt()%(dataMaxSize*5))+1))
barWrites = append(barWrites, rand.RandStr((rand.RandInt()%(dataMaxSize*5))+1))
fooWrites = append(fooWrites, tmrand.Str((tmrand.Int()%(dataMaxSize*5))+1))
barWrites = append(barWrites, tmrand.Str((tmrand.Int()%(dataMaxSize*5))+1))
}
// A helper that will run with (fooConn, fooWrites, fooReads) and vice versa
@ -372,11 +372,11 @@ func TestNonEd25519Pubkey(t *testing.T) {
func createGoldenTestVectors(t *testing.T) string {
data := ""
for i := 0; i < 32; i++ {
randSecretVector := rand.RandBytes(32)
randSecretVector := tmrand.Bytes(32)
randSecret := new([32]byte)
copy((*randSecret)[:], randSecretVector)
data += hex.EncodeToString((*randSecret)[:]) + ","
locIsLeast := rand.RandBool()
locIsLeast := tmrand.Bool()
data += strconv.FormatBool(locIsLeast) + ","
recvSecret, sendSecret := deriveSecrets(randSecret, locIsLeast)
data += hex.EncodeToString((*recvSecret)[:]) + ","
@ -400,7 +400,7 @@ func BenchmarkWriteSecretConnection(b *testing.B) {
}
fooWriteBytes := make([][]byte, 0, len(randomMsgSizes))
for _, size := range randomMsgSizes {
fooWriteBytes = append(fooWriteBytes, rand.RandBytes(size))
fooWriteBytes = append(fooWriteBytes, tmrand.Bytes(size))
}
// Consume reads from bar's reader
go func() {
@ -418,7 +418,7 @@ func BenchmarkWriteSecretConnection(b *testing.B) {
b.StartTimer()
for i := 0; i < b.N; i++ {
idx := rand.RandIntn(len(fooWriteBytes))
idx := tmrand.Intn(len(fooWriteBytes))
_, err := fooSecConn.Write(fooWriteBytes[idx])
if err != nil {
b.Errorf("failed to write to fooSecConn: %v", err)
@ -448,11 +448,11 @@ func BenchmarkReadSecretConnection(b *testing.B) {
}
fooWriteBytes := make([][]byte, 0, len(randomMsgSizes))
for _, size := range randomMsgSizes {
fooWriteBytes = append(fooWriteBytes, rand.RandBytes(size))
fooWriteBytes = append(fooWriteBytes, tmrand.Bytes(size))
}
go func() {
for i := 0; i < b.N; i++ {
idx := rand.RandIntn(len(fooWriteBytes))
idx := tmrand.Intn(len(fooWriteBytes))
_, err := fooSecConn.Write(fooWriteBytes[idx])
if err != nil {
b.Errorf("failed to write to fooSecConn: %v, %v,%v", err, i, b.N)


+ 3
- 3
p2p/fuzz.go View File

@ -6,7 +6,7 @@ import (
"time"
"github.com/tendermint/tendermint/config"
"github.com/tendermint/tendermint/libs/rand"
tmrand "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(rand.RandInt()%maxDelayMillis) // nolint: gas
return time.Millisecond * time.Duration(tmrand.Int()%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 := rand.RandFloat64()
r := tmrand.Float64()
switch {
case r <= fc.config.ProbDropRW:
return true


+ 2
- 2
p2p/key_test.go View File

@ -7,11 +7,11 @@ import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/tendermint/tendermint/libs/rand"
tmrand "github.com/tendermint/tendermint/libs/rand"
)
func TestLoadOrGenNodeKey(t *testing.T) {
filePath := filepath.Join(os.TempDir(), rand.RandStr(12)+"_peer_id.json")
filePath := filepath.Join(os.TempDir(), tmrand.Str(12)+"_peer_id.json")
nodeKey, err := LoadOrGenNodeKey(filePath)
assert.Nil(t, err)


+ 1
- 1
p2p/pex/addrbook.go View File

@ -363,7 +363,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 := tmrand.RandIntn(len(allAddr)-i) + i
j := tmrand.Intn(len(allAddr)-i) + i
allAddr[i], allAddr[j] = allAddr[j], allAddr[i]
}


+ 8
- 8
p2p/pex/addrbook_test.go View File

@ -13,7 +13,7 @@ import (
"github.com/tendermint/tendermint/libs/log"
tmmath "github.com/tendermint/tendermint/libs/math"
"github.com/tendermint/tendermint/libs/rand"
tmrand "github.com/tendermint/tendermint/libs/rand"
"github.com/tendermint/tendermint/p2p"
)
@ -185,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",
rand.RandIntn(254)+1,
rand.RandIntn(255),
rand.RandIntn(255),
rand.RandIntn(255),
tmrand.Intn(254)+1,
tmrand.Intn(255),
tmrand.Intn(255),
tmrand.Intn(255),
)
port := rand.RandIntn(65535-1) + 1
id := p2p.ID(hex.EncodeToString(rand.RandBytes(p2p.IDByteLength)))
port := tmrand.Intn(65535-1) + 1
id := p2p.ID(hex.EncodeToString(tmrand.Bytes(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")
@ -538,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, rand.RandIntn(r[1]-r[0])+r[0])
bookSizes = append(bookSizes, tmrand.Intn(r[1]-r[0])+r[0])
}
t.Logf("Testing address selection for the following book sizes %v\n", bookSizes)
for _, bookSize := range bookSizes {


+ 4
- 3
p2p/pex/pex_reactor.go View File

@ -12,6 +12,7 @@ import (
"github.com/tendermint/tendermint/libs/cmap"
tmmath "github.com/tendermint/tendermint/libs/math"
"github.com/tendermint/tendermint/libs/rand"
tmrand "github.com/tendermint/tendermint/libs/rand"
"github.com/tendermint/tendermint/libs/service"
"github.com/tendermint/tendermint/p2p"
"github.com/tendermint/tendermint/p2p/conn"
@ -497,7 +498,7 @@ func (r *Reactor) ensurePeers() {
peers := r.Switch.Peers().List()
peersCount := len(peers)
if peersCount > 0 {
peer := peers[rand.RandInt()%peersCount]
peer := peers[tmrand.Int()%peersCount]
r.Logger.Info("We need more addresses. Sending pexRequest to random peer", "peer", peer)
r.RequestAddrs(peer)
}
@ -534,7 +535,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(rand.RandFloat64() * float64(time.Second)) // 1s == (1e9 ns)
jitterSeconds := time.Duration(tmrand.Float64() * float64(time.Second)) // 1s == (1e9 ns)
backoffDuration := jitterSeconds + ((1 << uint(attempts)) * time.Second)
backoffDuration = r.maxBackoffDurationForPeer(addr, backoffDuration)
sinceLastDialed := time.Since(lastDialed)
@ -600,7 +601,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 := rand.RandPerm(len(r.seedAddrs))
perm := tmrand.Perm(len(r.seedAddrs))
// perm := r.Switch.rng.Perm(lSeeds)
for _, i := range perm {
// dial a random seed


+ 4
- 6
p2p/switch.go View File

@ -585,9 +585,7 @@ func (sw *Switch) AddUnconditionalPeerIDs(ids []string) error {
}
func (sw *Switch) isPeerPersistentFn() func(*NetAddress) bool {
return func(na *NetAddress) bool {
return sw.IsPeerPersistent(na)
}
return sw.IsPeerPersistent
}
func (sw *Switch) IsPeerPersistent(na *NetAddress) bool {
@ -606,7 +604,7 @@ func (sw *Switch) acceptRoutine() {
onPeerError: sw.StopPeerForError,
reactorsByCh: sw.reactorsByCh,
metrics: sw.metrics,
isPersistent: sw.isPeerPersistentFn(),
isPersistent: sw.IsPeerPersistent,
})
if err != nil {
switch err := err.(type) {
@ -707,7 +705,7 @@ func (sw *Switch) addOutboundPeerWithConfig(
p, err := sw.transport.Dial(*addr, peerConfig{
chDescs: sw.chDescs,
onPeerError: sw.StopPeerForError,
isPersistent: sw.isPeerPersistentFn(),
isPersistent: sw.IsPeerPersistent,
reactorsByCh: sw.reactorsByCh,
metrics: sw.metrics,
})
@ -725,7 +723,7 @@ func (sw *Switch) addOutboundPeerWithConfig(
// retry persistent peers after
// any dial error besides IsSelf()
if sw.isPeerPersistentFn()(addr) {
if sw.IsPeerPersistent(addr) {
go sw.reconnectToPeer(addr)
}


+ 4
- 4
p2p/switch_test.go View File

@ -229,7 +229,7 @@ func TestSwitchPeerFilter(t *testing.T) {
p, err := sw.transport.Dial(*rp.Addr(), peerConfig{
chDescs: sw.chDescs,
onPeerError: sw.StopPeerForError,
isPersistent: sw.isPeerPersistentFn(),
isPersistent: sw.IsPeerPersistent,
reactorsByCh: sw.reactorsByCh,
})
if err != nil {
@ -274,7 +274,7 @@ func TestSwitchPeerFilterTimeout(t *testing.T) {
p, err := sw.transport.Dial(*rp.Addr(), peerConfig{
chDescs: sw.chDescs,
onPeerError: sw.StopPeerForError,
isPersistent: sw.isPeerPersistentFn(),
isPersistent: sw.IsPeerPersistent,
reactorsByCh: sw.reactorsByCh,
})
if err != nil {
@ -300,7 +300,7 @@ func TestSwitchPeerFilterDuplicate(t *testing.T) {
p, err := sw.transport.Dial(*rp.Addr(), peerConfig{
chDescs: sw.chDescs,
onPeerError: sw.StopPeerForError,
isPersistent: sw.isPeerPersistentFn(),
isPersistent: sw.IsPeerPersistent,
reactorsByCh: sw.reactorsByCh,
})
if err != nil {
@ -346,7 +346,7 @@ func TestSwitchStopsNonPersistentPeerOnError(t *testing.T) {
p, err := sw.transport.Dial(*rp.Addr(), peerConfig{
chDescs: sw.chDescs,
onPeerError: sw.StopPeerForError,
isPersistent: sw.isPeerPersistentFn(),
isPersistent: sw.IsPeerPersistent,
reactorsByCh: sw.reactorsByCh,
})
require.Nil(err)


+ 6
- 6
p2p/test_util.go View File

@ -11,7 +11,7 @@ import (
"github.com/tendermint/tendermint/crypto/ed25519"
"github.com/tendermint/tendermint/libs/log"
tmnet "github.com/tendermint/tendermint/libs/net"
"github.com/tendermint/tendermint/libs/rand"
tmrand "github.com/tendermint/tendermint/libs/rand"
"github.com/tendermint/tendermint/config"
"github.com/tendermint/tendermint/p2p/conn"
@ -53,11 +53,11 @@ func CreateRoutableAddr() (addr string, netAddr *NetAddress) {
for {
var err error
addr = fmt.Sprintf("%X@%v.%v.%v.%v:26656",
rand.RandBytes(20),
rand.RandInt()%256,
rand.RandInt()%256,
rand.RandInt()%256,
rand.RandInt()%256)
tmrand.Bytes(20),
tmrand.Int()%256,
tmrand.Int()%256,
tmrand.Int()%256,
tmrand.Int()%256)
netAddr, err = NewNetAddressString(addr)
if err != nil {
panic(err)


+ 2
- 2
privval/signer_client_test.go View File

@ -8,7 +8,7 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/tendermint/tendermint/libs/rand"
tmrand "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 := rand.RandStr(12)
chainID := tmrand.Str(12)
mockPV := types.NewMockPV()
// get a pair of signer listener, signer dialer endpoints


+ 3
- 3
privval/signer_listener_endpoint_test.go View File

@ -11,7 +11,7 @@ import (
"github.com/tendermint/tendermint/crypto/ed25519"
"github.com/tendermint/tendermint/libs/log"
tmnet "github.com/tendermint/tendermint/libs/net"
"github.com/tendermint/tendermint/libs/rand"
tmrand "github.com/tendermint/tendermint/libs/rand"
"github.com/tendermint/tendermint/types"
)
@ -67,7 +67,7 @@ func TestSignerRemoteRetryTCPOnly(t *testing.T) {
SignerDialerEndpointTimeoutReadWrite(time.Millisecond)(dialerEndpoint)
SignerDialerEndpointConnRetries(retries)(dialerEndpoint)
chainID := rand.RandStr(12)
chainID := tmrand.Str(12)
mockPV := types.NewMockPV()
signerServer := NewSignerServer(dialerEndpoint, chainID, mockPV)
@ -87,7 +87,7 @@ func TestRetryConnToRemoteSigner(t *testing.T) {
for _, tc := range getDialerTestCases(t) {
var (
logger = log.TestingLogger()
chainID = rand.RandStr(12)
chainID = tmrand.Str(12)
mockPV = types.NewMockPV()
endpointIsOpenCh = make(chan struct{})
thisConnTimeout = testTimeoutReadWrite


+ 4
- 4
proxy/app_conn_test.go View File

@ -10,7 +10,7 @@ import (
"github.com/tendermint/tendermint/abci/server"
"github.com/tendermint/tendermint/abci/types"
"github.com/tendermint/tendermint/libs/log"
"github.com/tendermint/tendermint/libs/rand"
tmrand "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", rand.RandStr(6))
sockPath := fmt.Sprintf("unix:///tmp/echo_%v.sock", tmrand.Str(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", rand.RandStr(6))
sockPath := fmt.Sprintf("unix:///tmp/echo_%v.sock", tmrand.Str(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", rand.RandStr(6))
sockPath := fmt.Sprintf("unix:///tmp/echo_%v.sock", tmrand.Str(6))
clientCreator := NewRemoteClientCreator(sockPath, SOCKET, true)
// Start server


+ 3
- 3
rpc/client/event_test.go View File

@ -9,7 +9,7 @@ import (
"github.com/stretchr/testify/require"
abci "github.com/tendermint/tendermint/abci/types"
"github.com/tendermint/tendermint/libs/rand"
tmrand "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(rand.RandStr(8))
v := []byte(rand.RandStr(8))
k := []byte(tmrand.Str(8))
v := []byte(tmrand.Str(8))
return k, v, append(k, append([]byte("="), v...)...)
}


+ 2
- 2
rpc/lib/client/ws_client.go View File

@ -14,7 +14,7 @@ import (
metrics "github.com/rcrowley/go-metrics"
amino "github.com/tendermint/go-amino"
"github.com/tendermint/tendermint/libs/rand"
tmrand "github.com/tendermint/tendermint/libs/rand"
"github.com/tendermint/tendermint/libs/service"
types "github.com/tendermint/tendermint/rpc/lib/types"
)
@ -289,7 +289,7 @@ func (c *WSClient) reconnect() error {
}()
for {
jitterSeconds := time.Duration(rand.RandFloat64() * float64(time.Second)) // 1s == (1e9 ns)
jitterSeconds := time.Duration(tmrand.Float64() * float64(time.Second)) // 1s == (1e9 ns)
backoffDuration := jitterSeconds + ((1 << uint(attempt)) * time.Second)
c.Logger.Info("reconnecting", "attempt", attempt+1, "backoff_duration", backoffDuration)


+ 3
- 3
rpc/lib/rpc_test.go View File

@ -19,7 +19,7 @@ import (
amino "github.com/tendermint/go-amino"
tmbytes "github.com/tendermint/tendermint/libs/bytes"
"github.com/tendermint/tendermint/libs/log"
"github.com/tendermint/tendermint/libs/rand"
tmrand "github.com/tendermint/tendermint/libs/rand"
client "github.com/tendermint/tendermint/rpc/lib/client"
server "github.com/tendermint/tendermint/rpc/lib/server"
@ -207,7 +207,7 @@ func testWithHTTPClient(t *testing.T, cl client.HTTPClient) {
require.Nil(t, err)
assert.Equal(t, got3, val3)
val4 := rand.RandIntn(10000)
val4 := tmrand.Intn(10000)
got4, err := echoIntViaHTTP(cl, val4)
require.Nil(t, err)
assert.Equal(t, got4, val4)
@ -371,7 +371,7 @@ func TestWSClientPingPong(t *testing.T) {
}
func randBytes(t *testing.T) []byte {
n := rand.RandIntn(10) + 2
n := tmrand.Intn(10) + 2
buf := make([]byte, n)
_, err := crand.Read(buf)
require.Nil(t, err)


+ 2
- 2
state/helpers_test.go View File

@ -9,7 +9,7 @@ import (
abci "github.com/tendermint/tendermint/abci/types"
"github.com/tendermint/tendermint/crypto"
"github.com/tendermint/tendermint/crypto/ed25519"
"github.com/tendermint/tendermint/libs/rand"
tmrand "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: rand.RandBytes(32)}}
PartsHeader: types.PartSetHeader{Total: 3, Hash: tmrand.Bytes(32)}}
state, err := blockExec.ApplyBlock(state, blockID, block)
if err != nil {
return state, types.BlockID{}, err


+ 5
- 4
state/state_test.go View File

@ -14,6 +14,7 @@ import (
"github.com/tendermint/tendermint/crypto/ed25519"
"github.com/tendermint/tendermint/libs/kv"
"github.com/tendermint/tendermint/libs/rand"
tmrand "github.com/tendermint/tendermint/libs/rand"
sm "github.com/tendermint/tendermint/state"
dbm "github.com/tendermint/tm-db"
@ -316,17 +317,17 @@ func TestProposerFrequency(t *testing.T) {
maxPower := 1000
nTestCases := 5
for i := 0; i < nTestCases; i++ {
N := rand.RandInt()%maxVals + 1
N := tmrand.Int()%maxVals + 1
vals := make([]*types.Validator, N)
totalVotePower := int64(0)
for j := 0; j < N; j++ {
// make sure votePower > 0
votePower := int64(rand.RandInt()%maxPower) + 1
votePower := int64(tmrand.Int()%maxPower) + 1
totalVotePower += votePower
privVal := types.NewMockPV()
pubKey := privVal.GetPubKey()
val := types.NewValidator(pubKey, votePower)
val.ProposerPriority = rand.RandInt64()
val.ProposerPriority = tmrand.Int64()
vals[j] = val
}
valSet := types.NewValidatorSet(vals)
@ -343,7 +344,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 = rand.RandInt64()
val.ProposerPriority = rand.Int64()
vals[i] = val
}
valSet := types.NewValidatorSet(vals)


+ 7
- 7
state/tx_filter_test.go View File

@ -7,7 +7,7 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/tendermint/tendermint/libs/rand"
tmrand "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(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},
{types.Tx(tmrand.Bytes(250)), false},
{types.Tx(tmrand.Bytes(1811)), false},
{types.Tx(tmrand.Bytes(1831)), false},
{types.Tx(tmrand.Bytes(1838)), true},
{types.Tx(tmrand.Bytes(1839)), true},
{types.Tx(tmrand.Bytes(3000)), true},
}
for i, tc := range testCases {


+ 2
- 2
state/txindex/kv/kv_test.go View File

@ -14,7 +14,7 @@ import (
abci "github.com/tendermint/tendermint/abci/types"
"github.com/tendermint/tendermint/libs/kv"
"github.com/tendermint/tendermint/libs/pubsub/query"
"github.com/tendermint/tendermint/libs/rand"
tmrand "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 := rand.RandBytes(250)
tx := tmrand.Bytes(250)
txResult := &types.TxResult{
Height: 1,
Index: txIndex,


+ 1
- 1
types/block_test.go View File

@ -81,7 +81,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 = tmrand.RandBytes(len(blk.DataHash))
blk.DataHash = tmrand.Bytes(len(blk.DataHash))
}, true},
{"Tampered EvidenceHash", func(blk *Block) {
blk.EvidenceHash = []byte("something else")


+ 4
- 3
types/event_bus_test.go View File

@ -3,6 +3,7 @@ package types
import (
"context"
"fmt"
"math/rand"
"testing"
"time"
@ -13,7 +14,7 @@ import (
"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"
tmrand "github.com/tendermint/tendermint/libs/rand"
)
func TestEventBusPublishEventTx(t *testing.T) {
@ -404,7 +405,7 @@ var events = []string{
EventVote}
func randEvent() string {
return events[rand.RandIntn(len(events))]
return events[tmrand.Intn(len(events))]
}
var queries = []tmpubsub.Query{
@ -422,5 +423,5 @@ var queries = []tmpubsub.Query{
EventQueryVote}
func randQuery() tmpubsub.Query {
return queries[rand.RandIntn(len(queries))]
return queries[tmrand.Intn(len(queries))]
}

+ 5
- 5
types/part_set_test.go View File

@ -8,7 +8,7 @@ import (
"github.com/stretchr/testify/require"
"github.com/tendermint/tendermint/crypto/merkle"
"github.com/tendermint/tendermint/libs/rand"
tmrand "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 := rand.RandBytes(testPartSize * 100)
data := tmrand.Bytes(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 := rand.RandBytes(testPartSize * 100)
data := tmrand.Bytes(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 := rand.RandBytes(testPartSize * 100)
data := tmrand.Bytes(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 := rand.RandBytes(testPartSize * 100)
data := tmrand.Bytes(testPartSize * 100)
ps := NewPartSetFromData(data, testPartSize)
part := ps.GetPart(0)
tc.malleatePart(part)


+ 3
- 3
types/tx_test.go View File

@ -6,20 +6,20 @@ import (
"github.com/stretchr/testify/assert"
"github.com/tendermint/tendermint/libs/rand"
tmrand "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] = rand.RandBytes(size)
txs[i] = tmrand.Bytes(size)
}
return txs
}
func randInt(low, high int) int {
off := rand.RandInt() % (high - low)
off := tmrand.Int() % (high - low)
return low + off
}


+ 2
- 2
types/validator.go View File

@ -6,7 +6,7 @@ import (
"strings"
"github.com/tendermint/tendermint/crypto"
"github.com/tendermint/tendermint/libs/rand"
tmrand "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(rand.RandUint32())
votePower += int64(tmrand.Uint32())
}
pubKey := privVal.GetPubKey()
val := NewValidator(pubKey, votePower)


+ 15
- 15
types/validator_set_test.go View File

@ -14,7 +14,7 @@ import (
"github.com/tendermint/tendermint/crypto"
"github.com/tendermint/tendermint/crypto/ed25519"
tmmath "github.com/tendermint/tendermint/libs/math"
"github.com/tendermint/tendermint/libs/rand"
tmrand "github.com/tendermint/tendermint/libs/rand"
tmtime "github.com/tendermint/tendermint/types/time"
)
@ -284,10 +284,10 @@ func TestProposerSelection3(t *testing.T) {
// times is usually 1
times := 1
mod := (rand.RandInt() % 5) + 1
if rand.RandInt()%mod > 0 {
mod := (tmrand.Int() % 5) + 1
if tmrand.Int()%mod > 0 {
// sometimes its up to 5
times = (rand.RandInt() % 4) + 1
times = (tmrand.Int() % 4) + 1
}
vset.IncrementProposerPriority(times)
@ -301,15 +301,15 @@ func newValidator(address []byte, power int64) *Validator {
func randPubKey() crypto.PubKey {
var pubKey [32]byte
copy(pubKey[:], rand.RandBytes(32))
copy(pubKey[:], tmrand.Bytes(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(rand.RandUint64()%uint64((MaxTotalVotingPower-totalVotingPower))))
val.ProposerPriority = rand.RandInt64() % (MaxTotalVotingPower - totalVotingPower)
val := NewValidator(randPubKey(), int64(tmrand.Uint64()%uint64((MaxTotalVotingPower-totalVotingPower))))
val.ProposerPriority = tmrand.Int64() % (MaxTotalVotingPower - totalVotingPower)
return val
}
@ -709,7 +709,7 @@ func permutation(valList []testVal) []testVal {
return nil
}
permList := make([]testVal, len(valList))
perm := rand.RandPerm(len(valList))
perm := tmrand.Perm(len(valList))
for i, v := range perm {
permList[v] = valList[i]
}
@ -1111,14 +1111,14 @@ func randTestVSetCfg(t *testing.T, nBase, nAddMax int) testVSetCfg {
const maxPower = 1000
var nOld, nDel, nChanged, nAdd int
nOld = int(rand.RandUint()%uint(nBase)) + 1
nOld = int(tmrand.Uint()%uint(nBase)) + 1
if nBase-nOld > 0 {
nDel = int(rand.RandUint() % uint(nBase-nOld))
nDel = int(tmrand.Uint() % uint(nBase-nOld))
}
nChanged = nBase - nOld - nDel
if nAddMax > 0 {
nAdd = rand.RandInt()%nAddMax + 1
nAdd = tmrand.Int()%nAddMax + 1
}
cfg := testVSetCfg{}
@ -1130,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(rand.RandUint()%maxPower + 1)}
cfg.startVals[i] = testVal{fmt.Sprintf("v%d", i), int64(tmrand.Uint()%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(rand.RandUint()%maxPower + 1)}
cfg.updatedVals[i-nOld] = testVal{fmt.Sprintf("v%d", i), int64(tmrand.Uint()%maxPower + 1)}
cfg.expectedVals[i] = cfg.updatedVals[i-nOld]
}
if i >= nOld+nChanged {
@ -1144,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(rand.RandUint()%maxPower + 1)}
cfg.addedVals[i-nBase] = testVal{fmt.Sprintf("v%d", i), int64(tmrand.Uint()%maxPower + 1)}
cfg.expectedVals[i-nDel] = cfg.addedVals[i-nBase]
}
@ -1225,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(rand.RandInt()%nMaxElections + 1)
valSet.IncrementProposerPriority(tmrand.Int()%nMaxElections + 1)
origValsPriSorted := validatorListCopy(valSet.Validators)
sort.Sort(validatorsByPriority(origValsPriSorted))


+ 8
- 8
types/vote_set_test.go View File

@ -7,7 +7,7 @@ import (
"github.com/stretchr/testify/assert"
"github.com/tendermint/tendermint/crypto"
"github.com/tendermint/tendermint/libs/rand"
tmrand "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, rand.RandBytes(32)), voteSet)
_, err := signAddVote(privValidators[6], withBlockHash(vote, tmrand.Bytes(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, rand.RandBytes(32)), voteSet)
_, err := signAddVote(privValidators[69], withBlockHash(vote, tmrand.Bytes(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, rand.RandBytes(32)), voteSet)
added, err := signAddVote(privValidators[0], withBlockHash(vote, tmrand.Bytes(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 := rand.RandBytes(32)
blockHash2 := rand.RandBytes(32)
blockHash1 := tmrand.Bytes(32)
blockHash2 := tmrand.Bytes(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, rand.RandBytes(32))
vote = withBlockPartsHeader(vote, PartSetHeader{123, rand.RandBytes(32)})
vote = withBlockHash(vote, tmrand.Bytes(32))
vote = withBlockPartsHeader(vote, PartSetHeader{123, tmrand.Bytes(32)})
_, err := signAddVote(privValidators[6], vote, voteSet)
if err != nil {


Loading…
Cancel
Save