Skip to content

Commit 4d35256

Browse files
authored
all: remove deprecated uses of math.rand (#26710)
This PR is a (superior) alternative to ethereum/go-ethereum#26708, it handles deprecation, primarily two specific cases. `rand.Seed` is typically used in two ways - `rand.Seed(time.Now().UnixNano())` -- we seed it, just to be sure to get some random, and not always get the same thing on every run. This is not needed, with global seeding, so those are just removed. - `rand.Seed(1)` this is typically done to ensure we have a stable test. If we rely on this, we need to fix up the tests to use a deterministic prng-source. A few occurrences like this has been replaced with a proper custom source. `rand.Read` has been replaced by `crypto/rand`.`Read` in this PR.
1 parent e9d4249 commit 4d35256

28 files changed

+75
-75
lines changed

accounts/keystore/account_cache_test.go

-2
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,6 @@ func TestWatchNewFile(t *testing.T) {
113113
func TestWatchNoDir(t *testing.T) {
114114
t.Parallel()
115115
// Create ks but not the directory that it watches.
116-
rand.Seed(time.Now().UnixNano())
117116
dir := filepath.Join(os.TempDir(), fmt.Sprintf("eth-keystore-watchnodir-test-%d-%d", os.Getpid(), rand.Int()))
118117
ks := NewKeyStore(dir, LightScryptN, LightScryptP)
119118
list := ks.Accounts()
@@ -322,7 +321,6 @@ func TestUpdatedKeyfileContents(t *testing.T) {
322321
t.Parallel()
323322

324323
// Create a temporary keystore to test with
325-
rand.Seed(time.Now().UnixNano())
326324
dir := filepath.Join(os.TempDir(), fmt.Sprintf("eth-keystore-updatedkeyfilecontents-test-%d-%d", os.Getpid(), rand.Int()))
327325
ks := NewKeyStore(dir, LightScryptN, LightScryptP)
328326

common/lru/basiclru_test.go

+3-2
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
package lru
1818

1919
import (
20+
crand "crypto/rand"
2021
"fmt"
2122
"io"
2223
"math/rand"
@@ -181,9 +182,9 @@ func BenchmarkLRU(b *testing.B) {
181182
}
182183
for i := range keys {
183184
b := make([]byte, 32)
184-
rand.Read(b)
185+
crand.Read(b)
185186
keys[i] = string(b)
186-
rand.Read(b)
187+
crand.Read(b)
187188
values[i] = b
188189
}
189190

common/prque/lazyqueue_test.go

-1
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,6 @@ func testSetIndex(a interface{}, i int) {
5656
}
5757

5858
func TestLazyQueue(t *testing.T) {
59-
rand.Seed(time.Now().UnixNano())
6059
clock := &mclock.Simulated{}
6160
q := NewLazyQueue(testSetIndex, testPriority, testMaxPriority, clock, testQueueRefresh)
6261

consensus/ethash/consensus_test.go

+3-3
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
package ethash
1818

1919
import (
20+
crand "crypto/rand"
2021
"encoding/binary"
2122
"encoding/json"
2223
"math/big"
@@ -90,16 +91,15 @@ func TestCalcDifficulty(t *testing.T) {
9091

9192
func randSlice(min, max uint32) []byte {
9293
var b = make([]byte, 4)
93-
rand.Read(b)
94+
crand.Read(b)
9495
a := binary.LittleEndian.Uint32(b)
9596
size := min + a%(max-min)
9697
out := make([]byte, size)
97-
rand.Read(out)
98+
crand.Read(out)
9899
return out
99100
}
100101

101102
func TestDifficultyCalculators(t *testing.T) {
102-
rand.Seed(2)
103103
for i := 0; i < 5000; i++ {
104104
// 1 to 300 seconds diff
105105
var timeDelta = uint64(1 + rand.Uint32()%3000)

core/bloombits/generator_test.go

+2-1
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ package bloombits
1818

1919
import (
2020
"bytes"
21+
crand "crypto/rand"
2122
"math/rand"
2223
"testing"
2324

@@ -78,7 +79,7 @@ func BenchmarkGenerator(b *testing.B) {
7879
}
7980
})
8081
for i := 0; i < types.BloomBitLength; i++ {
81-
rand.Read(input[i][:])
82+
crand.Read(input[i][:])
8283
}
8384
b.Run("random", func(b *testing.B) {
8485
b.ReportAllocs()

core/rawdb/freezer_table_test.go

-5
Original file line numberDiff line numberDiff line change
@@ -27,17 +27,12 @@ import (
2727
"sync/atomic"
2828
"testing"
2929
"testing/quick"
30-
"time"
3130

3231
"github.com/davecgh/go-spew/spew"
3332
"github.com/ethereum/go-ethereum/metrics"
3433
"github.com/stretchr/testify/require"
3534
)
3635

37-
func init() {
38-
rand.Seed(time.Now().Unix())
39-
}
40-
4136
// TestFreezerBasics test initializing a freezertable from scratch, writing to the table,
4237
// and reading it back.
4338
func TestFreezerBasics(t *testing.T) {

core/state/snapshot/difflayer_test.go

+5-4
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ package snapshot
1818

1919
import (
2020
"bytes"
21+
crand "crypto/rand"
2122
"math/rand"
2223
"testing"
2324

@@ -73,7 +74,7 @@ func TestMergeBasics(t *testing.T) {
7374
if rand.Intn(2) == 0 {
7475
accStorage := make(map[common.Hash][]byte)
7576
value := make([]byte, 32)
76-
rand.Read(value)
77+
crand.Read(value)
7778
accStorage[randomHash()] = value
7879
storage[h] = accStorage
7980
}
@@ -294,7 +295,7 @@ func BenchmarkSearchSlot(b *testing.B) {
294295
accStorage := make(map[common.Hash][]byte)
295296
for i := 0; i < 5; i++ {
296297
value := make([]byte, 32)
297-
rand.Read(value)
298+
crand.Read(value)
298299
accStorage[randomHash()] = value
299300
storage[accountKey] = accStorage
300301
}
@@ -330,7 +331,7 @@ func BenchmarkFlatten(b *testing.B) {
330331
accStorage := make(map[common.Hash][]byte)
331332
for i := 0; i < 20; i++ {
332333
value := make([]byte, 32)
333-
rand.Read(value)
334+
crand.Read(value)
334335
accStorage[randomHash()] = value
335336
}
336337
storage[accountKey] = accStorage
@@ -379,7 +380,7 @@ func BenchmarkJournal(b *testing.B) {
379380
accStorage := make(map[common.Hash][]byte)
380381
for i := 0; i < 200; i++ {
381382
value := make([]byte, 32)
382-
rand.Read(value)
383+
crand.Read(value)
383384
accStorage[randomHash()] = value
384385
}
385386
storage[accountKey] = accStorage

core/state/snapshot/iterator_test.go

+3-2
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ package snapshot
1818

1919
import (
2020
"bytes"
21+
crand "crypto/rand"
2122
"encoding/binary"
2223
"fmt"
2324
"math/rand"
@@ -47,7 +48,7 @@ func TestAccountIteratorBasics(t *testing.T) {
4748
if rand.Intn(2) == 0 {
4849
accStorage := make(map[common.Hash][]byte)
4950
value := make([]byte, 32)
50-
rand.Read(value)
51+
crand.Read(value)
5152
accStorage[randomHash()] = value
5253
storage[h] = accStorage
5354
}
@@ -79,7 +80,7 @@ func TestStorageIteratorBasics(t *testing.T) {
7980

8081
var nilstorage int
8182
for i := 0; i < 100; i++ {
82-
rand.Read(value)
83+
crand.Read(value)
8384
if rand.Intn(2) == 0 {
8485
accStorage[randomHash()] = common.CopyBytes(value)
8586
} else {

core/state/snapshot/snapshot_test.go

+2-1
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
package snapshot
1818

1919
import (
20+
crand "crypto/rand"
2021
"encoding/binary"
2122
"fmt"
2223
"math/big"
@@ -33,7 +34,7 @@ import (
3334
// randomHash generates a random blob of data and returns it as a hash.
3435
func randomHash() common.Hash {
3536
var hash common.Hash
36-
if n, err := rand.Read(hash[:]); n != common.HashLength || err != nil {
37+
if n, err := crand.Read(hash[:]); n != common.HashLength || err != nil {
3738
panic(err)
3839
}
3940
return hash

core/txpool/txpool_test.go

+2-1
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ package txpool
1818

1919
import (
2020
"crypto/ecdsa"
21+
crand "crypto/rand"
2122
"errors"
2223
"fmt"
2324
"math/big"
@@ -92,7 +93,7 @@ func pricedTransaction(nonce uint64, gaslimit uint64, gasprice *big.Int, key *ec
9293

9394
func pricedDataTransaction(nonce uint64, gaslimit uint64, gasprice *big.Int, key *ecdsa.PrivateKey, bytes uint64) *types.Transaction {
9495
data := make([]byte, bytes)
95-
rand.Read(data)
96+
crand.Read(data)
9697

9798
tx, _ := types.SignTx(types.NewTransaction(nonce, common.Address{}, big.NewInt(0), gaslimit, gasprice, data), types.HomesteadSigner{}, key)
9899
return tx

crypto/signify/signify_test.go

+1-10
Original file line numberDiff line numberDiff line change
@@ -20,10 +20,9 @@
2020
package signify
2121

2222
import (
23-
"math/rand"
23+
"crypto/rand"
2424
"os"
2525
"testing"
26-
"time"
2726

2827
"github.com/jedisct1/go-minisign"
2928
)
@@ -41,8 +40,6 @@ func TestSignify(t *testing.T) {
4140
defer os.Remove(tmpFile.Name())
4241
defer tmpFile.Close()
4342

44-
rand.Seed(time.Now().UnixNano())
45-
4643
data := make([]byte, 1024)
4744
rand.Read(data)
4845
tmpFile.Write(data)
@@ -85,8 +82,6 @@ func TestSignifyTrustedCommentTooManyLines(t *testing.T) {
8582
defer os.Remove(tmpFile.Name())
8683
defer tmpFile.Close()
8784

88-
rand.Seed(time.Now().UnixNano())
89-
9085
data := make([]byte, 1024)
9186
rand.Read(data)
9287
tmpFile.Write(data)
@@ -110,8 +105,6 @@ func TestSignifyTrustedCommentTooManyLinesLF(t *testing.T) {
110105
defer os.Remove(tmpFile.Name())
111106
defer tmpFile.Close()
112107

113-
rand.Seed(time.Now().UnixNano())
114-
115108
data := make([]byte, 1024)
116109
rand.Read(data)
117110
tmpFile.Write(data)
@@ -135,8 +128,6 @@ func TestSignifyTrustedCommentEmpty(t *testing.T) {
135128
defer os.Remove(tmpFile.Name())
136129
defer tmpFile.Close()
137130

138-
rand.Seed(time.Now().UnixNano())
139-
140131
data := make([]byte, 1024)
141132
rand.Read(data)
142133
tmpFile.Write(data)

ethdb/dbtest/testsuite.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ package dbtest
1818

1919
import (
2020
"bytes"
21-
"math/rand"
21+
"crypto/rand"
2222
"reflect"
2323
"sort"
2424
"testing"

event/event_test.go

-1
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,6 @@ func TestSubscribeDuplicateType(t *testing.T) {
100100
}
101101

102102
func TestMuxConcurrent(t *testing.T) {
103-
rand.Seed(time.Now().Unix())
104103
mux := new(TypeMux)
105104
defer mux.Stop()
106105

les/api_test.go

+2-1
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ package les
1818

1919
import (
2020
"context"
21+
crand "crypto/rand"
2122
"errors"
2223
"flag"
2324
"math/rand"
@@ -326,7 +327,7 @@ func getHead(ctx context.Context, t *testing.T, client *rpc.Client) (uint64, com
326327
func testRequest(ctx context.Context, t *testing.T, client *rpc.Client) bool {
327328
var res string
328329
var addr common.Address
329-
rand.Read(addr[:])
330+
crand.Read(addr[:])
330331
c, cancel := context.WithTimeout(ctx, time.Second*12)
331332
defer cancel()
332333
err := client.CallContext(c, &res, "eth_getBalance", addr, "latest")

les/benchmark.go

+5-4
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
package les
1818

1919
import (
20+
crand "crypto/rand"
2021
"encoding/binary"
2122
"fmt"
2223
"math/big"
@@ -114,7 +115,7 @@ func (b *benchmarkProofsOrCode) init(h *serverHandler, count int) error {
114115

115116
func (b *benchmarkProofsOrCode) request(peer *serverPeer, index int) error {
116117
key := make([]byte, 32)
117-
rand.Read(key)
118+
crand.Read(key)
118119
if b.code {
119120
return peer.requestCode(0, []CodeReq{{BHash: b.headHash, AccKey: key}})
120121
}
@@ -176,7 +177,7 @@ func (b *benchmarkTxSend) init(h *serverHandler, count int) error {
176177

177178
for i := range b.txs {
178179
data := make([]byte, txSizeCostLimit)
179-
rand.Read(data)
180+
crand.Read(data)
180181
tx, err := types.SignTx(types.NewTransaction(0, addr, new(big.Int), 0, new(big.Int), data), signer, key)
181182
if err != nil {
182183
panic(err)
@@ -200,7 +201,7 @@ func (b *benchmarkTxStatus) init(h *serverHandler, count int) error {
200201

201202
func (b *benchmarkTxStatus) request(peer *serverPeer, index int) error {
202203
var hash common.Hash
203-
rand.Read(hash[:])
204+
crand.Read(hash[:])
204205
return peer.requestTxStatus(0, []common.Hash{hash})
205206
}
206207

@@ -278,7 +279,7 @@ func (h *serverHandler) measure(setup *benchmarkSetup, count int) error {
278279
clientMeteredPipe := &meteredPipe{rw: clientPipe}
279280
serverMeteredPipe := &meteredPipe{rw: serverPipe}
280281
var id enode.ID
281-
rand.Read(id[:])
282+
crand.Read(id[:])
282283

283284
peer1 := newServerPeer(lpv2, NetworkId, false, p2p.NewPeer(id, "client", nil), clientMeteredPipe)
284285
peer2 := newClientPeer(lpv2, NetworkId, p2p.NewPeer(id, "server", nil), serverMeteredPipe)

les/utils/limiter_test.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
package utils
1818

1919
import (
20-
"math/rand"
20+
"crypto/rand"
2121
"testing"
2222

2323
"github.com/ethereum/go-ethereum/p2p/enode"

les/vflux/client/fillset_test.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
package client
1818

1919
import (
20-
"math/rand"
20+
"crypto/rand"
2121
"testing"
2222
"time"
2323

les/vflux/server/clientpool_test.go

-1
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,6 @@ func alwaysTrueFn() bool {
135135
}
136136

137137
func testClientPool(t *testing.T, activeLimit, clientCount, paidCount int, randomDisconnect bool) {
138-
rand.Seed(time.Now().UnixNano())
139138
var (
140139
clock mclock.Simulated
141140
db = rawdb.NewMemoryDatabase()

0 commit comments

Comments
 (0)