Skip to content

Commit 5aeda4f

Browse files
denyeartpfi79
andauthored
change math/rand to v2 (release-2.5) (#5170)
* Remove usage of deprecated rand.Seed() (release-2.5) Backport of math/rand portion of #4372 Signed-off-by: David Enyeart <[email protected]> * change math/rand to v2 Signed-off-by: Fedor Partanskiy <[email protected]> Signed-off-by: David Enyeart <[email protected]> --------- Signed-off-by: David Enyeart <[email protected]> Signed-off-by: Fedor Partanskiy <[email protected]> Co-authored-by: Fedor Partanskiy <[email protected]>
1 parent 5180f30 commit 5aeda4f

File tree

27 files changed

+173
-113
lines changed

27 files changed

+173
-113
lines changed

cmd/common/cli_test.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ package common
99
import (
1010
"bytes"
1111
"fmt"
12-
"math/rand"
12+
"math/rand/v2"
1313
"os"
1414
"path/filepath"
1515
"testing"

cmd/common/config_test.go

+6-3
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,9 @@ SPDX-License-Identifier: Apache-2.0
77
package common
88

99
import (
10+
crand "crypto/rand"
1011
"fmt"
11-
"math/rand"
12+
"math/rand/v2"
1213
"os"
1314
"path/filepath"
1415
"testing"
@@ -20,8 +21,10 @@ import (
2021
)
2122

2223
func TestConfig(t *testing.T) {
23-
rand.Seed(time.Now().UnixNano())
24-
configFilePath := filepath.Join(os.TempDir(), fmt.Sprintf("config-%d.yaml", rand.Int()))
24+
var seed [32]byte
25+
_, _ = crand.Read(seed[:])
26+
r := rand.New(rand.NewChaCha8(seed))
27+
configFilePath := filepath.Join(os.TempDir(), fmt.Sprintf("config-%d.yaml", r.Int()))
2528
fmt.Println(configFilePath)
2629
t.Run("save and load a config", func(t *testing.T) {
2730
c := Config{

common/configtx/util_test.go

+3-3
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ SPDX-License-Identifier: Apache-2.0
77
package configtx
88

99
import (
10-
"math/rand"
10+
"math/rand/v2"
1111
"testing"
1212

1313
cb "github.com/hyperledger/fabric-protos-go/common"
@@ -101,7 +101,7 @@ func randomLowerAlphaString(size int) string {
101101
letters := []rune("abcdefghijklmnopqrstuvwxyz")
102102
output := make([]rune, size)
103103
for i := range output {
104-
output[i] = letters[rand.Intn(len(letters))]
104+
output[i] = letters[rand.IntN(len(letters))]
105105
}
106106
return string(output)
107107
}
@@ -110,7 +110,7 @@ func randomAlphaString(size int) string {
110110
letters := []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
111111
output := make([]rune, size)
112112
for i := range output {
113-
output[i] = letters[rand.Intn(len(letters))]
113+
output[i] = letters[rand.IntN(len(letters))]
114114
}
115115
return string(output)
116116
}

common/graph/perm.go

+8-4
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,16 @@ SPDX-License-Identifier: Apache-2.0
77
package graph
88

99
import (
10-
"math/rand"
11-
"time"
10+
crand "crypto/rand"
11+
"math/rand/v2"
1212
)
1313

14+
var r *rand.Rand
15+
1416
func init() {
15-
rand.Seed(time.Now().UnixNano())
17+
var seed [32]byte
18+
_, _ = crand.Read(seed[:])
19+
r = rand.New(rand.NewChaCha8(seed))
1620
}
1721

1822
// treePermutations represents possible permutations
@@ -110,7 +114,7 @@ func (tp *treePermutations) computeDescendantPermutations() {
110114
// Ensure we don't have too much combinations of descendants
111115
for CombinationsExceed(len(v.Descendants), v.Threshold, tp.combinationUpperBound) {
112116
// Randomly pick a descendant, and remove it
113-
victim := rand.Intn(len(v.Descendants))
117+
victim := r.IntN(len(v.Descendants))
114118
v.Descendants = append(v.Descendants[:victim], v.Descendants[victim+1:]...)
115119
}
116120

core/common/validation/fullflow_test.go

+6-4
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,11 @@ SPDX-License-Identifier: Apache-2.0
77
package validation
88

99
import (
10+
crand "crypto/rand"
1011
"fmt"
11-
"math/rand"
12+
"math/rand/v2"
1213
"os"
1314
"testing"
14-
"time"
1515

1616
"github.com/hyperledger/fabric-protos-go/common"
1717
"github.com/hyperledger/fabric-protos-go/peer"
@@ -206,8 +206,10 @@ func TestTXWithTwoActionsRejected(t *testing.T) {
206206
}
207207

208208
func corrupt(bytes []byte) {
209-
rand.Seed(time.Now().UnixNano())
210-
bytes[rand.Intn(len(bytes))]--
209+
var seed [32]byte
210+
_, _ = crand.Read(seed[:])
211+
r := rand.New(rand.NewChaCha8(seed))
212+
bytes[r.IntN(len(bytes))]--
211213
}
212214

213215
func TestBadTx(t *testing.T) {

core/common/validation/statebased/vpmanager_test.go

+30-17
Original file line numberDiff line numberDiff line change
@@ -7,13 +7,13 @@ SPDX-License-Identifier: Apache-2.0
77
package statebased
88

99
import (
10+
crand "crypto/rand"
1011
"fmt"
11-
"math/rand"
12+
"math/rand/v2"
1213
"runtime"
1314
"strconv"
1415
"sync"
1516
"testing"
16-
"time"
1717

1818
"github.com/hyperledger/fabric-protos-go/ledger/rwset"
1919
"github.com/hyperledger/fabric-protos-go/ledger/rwset/kvrwset"
@@ -169,8 +169,8 @@ func pvtRwsetUpdatingMetadataFor(cc, coll, key string) []byte {
169169
})
170170
}
171171

172-
func runFunctions(t *testing.T, seed int64, funcs ...func()) {
173-
r := rand.New(rand.NewSource(seed))
172+
func runFunctions(t *testing.T, seed [32]byte, funcs ...func()) {
173+
r := rand.New(rand.NewChaCha8(seed))
174174
c := make(chan struct{})
175175
for _, i := range r.Perm(len(funcs)) {
176176
iLcl := i
@@ -186,7 +186,8 @@ func runFunctions(t *testing.T, seed int64, funcs ...func()) {
186186

187187
func TestTranslatorBadPolicy(t *testing.T) {
188188
t.Parallel()
189-
seed := time.Now().Unix()
189+
var seed [32]byte
190+
_, _ = crand.Read(seed[:])
190191

191192
// Scenario: we verify that translation from SignaturePolicyEnvelope to ApplicationPolicy fails appropriately
192193

@@ -226,7 +227,8 @@ func TestTranslatorBadPolicy(t *testing.T) {
226227

227228
func TestTranslatorBadPolicyPvt(t *testing.T) {
228229
t.Parallel()
229-
seed := time.Now().Unix()
230+
var seed [32]byte
231+
_, _ = crand.Read(seed[:])
230232

231233
// Scenario: we verify that translation from SignaturePolicyEnvelope to ApplicationPolicy fails appropriately with private data
232234

@@ -266,7 +268,8 @@ func TestTranslatorBadPolicyPvt(t *testing.T) {
266268

267269
func TestDependencyNoConflict(t *testing.T) {
268270
t.Parallel()
269-
seed := time.Now().Unix()
271+
var seed [32]byte
272+
_, _ = crand.Read(seed[:])
270273

271274
// Scenario: validation parameter is retrieved successfully
272275
// for a ledger key for transaction (1,1) after waiting for
@@ -309,7 +312,8 @@ func TestDependencyNoConflict(t *testing.T) {
309312

310313
func TestDependencyConflict(t *testing.T) {
311314
t.Parallel()
312-
seed := time.Now().Unix()
315+
var seed [32]byte
316+
_, _ = crand.Read(seed[:])
313317

314318
// Scenario: validation parameter is retrieved
315319
// for a ledger key for transaction (1,1) after waiting for
@@ -353,7 +357,8 @@ func TestDependencyConflict(t *testing.T) {
353357

354358
func TestMultipleDependencyNoConflict(t *testing.T) {
355359
t.Parallel()
356-
seed := time.Now().Unix()
360+
var seed [32]byte
361+
_, _ = crand.Read(seed[:])
357362

358363
// Scenario: validation parameter is retrieved successfully
359364
// for a ledger key for transaction (1,2) after waiting for
@@ -402,7 +407,8 @@ func TestMultipleDependencyNoConflict(t *testing.T) {
402407

403408
func TestMultipleDependencyConflict(t *testing.T) {
404409
t.Parallel()
405-
seed := time.Now().Unix()
410+
var seed [32]byte
411+
_, _ = crand.Read(seed[:])
406412

407413
// Scenario: validation parameter is retrieved
408414
// for a ledger key for transaction (1,2) after waiting for
@@ -452,7 +458,8 @@ func TestMultipleDependencyConflict(t *testing.T) {
452458

453459
func TestPvtDependencyNoConflict(t *testing.T) {
454460
t.Parallel()
455-
seed := time.Now().Unix()
461+
var seed [32]byte
462+
_, _ = crand.Read(seed[:])
456463

457464
// Scenario: like TestDependencyNoConflict but for private data
458465

@@ -490,7 +497,8 @@ func TestPvtDependencyNoConflict(t *testing.T) {
490497

491498
func TestPvtDependencyConflict(t *testing.T) {
492499
t.Parallel()
493-
seed := time.Now().Unix()
500+
var seed [32]byte
501+
_, _ = crand.Read(seed[:])
494502

495503
// Scenario: like TestDependencyConflict but for private data
496504

@@ -553,7 +561,8 @@ func TestBlockValidationTerminatesBeforeNewBlock(t *testing.T) {
553561

554562
func TestLedgerErrors(t *testing.T) {
555563
t.Parallel()
556-
seed := time.Now().Unix()
564+
var seed [32]byte
565+
_, _ = crand.Read(seed[:])
557566

558567
// Scenario: we check that if a ledger error occurs,
559568
// GetValidationParameterForKey returns an error
@@ -625,7 +634,8 @@ func TestLedgerErrors(t *testing.T) {
625634

626635
func TestBadRwsetIsNoDependency(t *testing.T) {
627636
t.Parallel()
628-
seed := time.Now().Unix()
637+
var seed [32]byte
638+
_, _ = crand.Read(seed[:])
629639

630640
// Scenario: a transaction has a bogus read-write set.
631641
// While the transaction will fail eventually, we check
@@ -663,7 +673,8 @@ func TestBadRwsetIsNoDependency(t *testing.T) {
663673

664674
func TestWritesIntoDifferentNamespaces(t *testing.T) {
665675
t.Parallel()
666-
seed := time.Now().Unix()
676+
var seed [32]byte
677+
_, _ = crand.Read(seed[:])
667678

668679
// Scenario: transaction (1,0) writes to namespace cc1.
669680
// Transaction (1,1) attempts to retrieve validation
@@ -701,7 +712,8 @@ func TestWritesIntoDifferentNamespaces(t *testing.T) {
701712

702713
func TestCombinedCalls(t *testing.T) {
703714
t.Parallel()
704-
seed := time.Now().Unix()
715+
var seed [32]byte
716+
_, _ = crand.Read(seed[:])
705717

706718
// Scenario: transaction (1,3) requests validation parameters
707719
// for different keys - one succeeds and one fails.
@@ -760,7 +772,8 @@ func TestCombinedCalls(t *testing.T) {
760772
}
761773

762774
func TestForRaces(t *testing.T) {
763-
seed := time.Now().Unix()
775+
var seed [32]byte
776+
_, _ = crand.Read(seed[:])
764777

765778
// scenario to stress test the parallel validation
766779
// this is an extended combined test

core/ledger/kvledger/benchmark/experiments/readwrite_txs_test.go

+10-15
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,11 @@ SPDX-License-Identifier: Apache-2.0
77
package experiments
88

99
import (
10+
crand "crypto/rand"
1011
"fmt"
11-
"math/rand"
12+
"math/rand/v2"
1213
"sync"
1314
"testing"
14-
"time"
1515

1616
"github.com/hyperledger/fabric/common/util"
1717
"github.com/hyperledger/fabric/core/ledger/kvledger/benchmark/chainmgmt"
@@ -51,7 +51,9 @@ func runReadWriteClientsForChain(chain *chainmgmt.Chain) {
5151
wg.Add(numClients)
5252
for i := 0; i < numClients; i++ {
5353
numTxForClient := calculateShare(numTxForChain, numClients, i)
54-
randomNumGen := rand.New(rand.NewSource(int64(time.Now().Nanosecond()) + int64(chain.ID)))
54+
var seed [32]byte
55+
_, _ = crand.Read(seed[:])
56+
randomNumGen := rand.New(rand.NewChaCha8(seed))
5557
go runReadWriteClient(chain, randomNumGen, numTxForClient, wg)
5658
}
5759
wg.Wait()
@@ -66,16 +68,16 @@ func runReadWriteClient(chain *chainmgmt.Chain, rand *rand.Rand, numTx int, wg *
6668
useJSON := conf.dataConf.useJSON
6769
var value []byte
6870

69-
for i := 0; i < numTx; i++ {
71+
for range numTx {
7072
simulator, err := chain.NewTxSimulator(util.GenerateUUID())
7173
panicOnError(err)
7274
maxKeys := max(numReadsPerTx, numWritesPerTx)
7375
keysToOperateOn := []int{}
74-
for i := 0; i < maxKeys; i++ {
75-
keysToOperateOn = append(keysToOperateOn, rand.Intn(maxKeyNumber))
76+
for range maxKeys {
77+
keysToOperateOn = append(keysToOperateOn, rand.IntN(maxKeyNumber))
7678
}
7779

78-
for i := 0; i < numReadsPerTx; i++ {
80+
for i := range numReadsPerTx {
7981
keyNumber := keysToOperateOn[i]
8082
value, err = simulator.GetState(chaincodeName, constructKey(keyNumber))
8183
panicOnError(err)
@@ -90,7 +92,7 @@ func runReadWriteClient(chain *chainmgmt.Chain, rand *rand.Rand, numTx int, wg *
9092
}
9193
}
9294

93-
for i := 0; i < numWritesPerTx; i++ {
95+
for i := range numWritesPerTx {
9496
keyNumber := keysToOperateOn[i]
9597
key := constructKey(keyNumber)
9698
if useJSON {
@@ -109,10 +111,3 @@ func runReadWriteClient(chain *chainmgmt.Chain, rand *rand.Rand, numTx int, wg *
109111
}
110112
wg.Done()
111113
}
112-
113-
func max(a, b int) int {
114-
if a > b {
115-
return a
116-
}
117-
return b
118-
}

core/ledger/kvledger/benchmark/experiments/util.go

+10-6
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,10 @@ package experiments
88

99
import (
1010
"bytes"
11+
crand "crypto/rand"
1112
"encoding/json"
1213
"fmt"
13-
"math/rand"
14+
"math/rand/v2"
1415
"strconv"
1516
)
1617

@@ -63,10 +64,13 @@ func constructValue(keyNumber int, kvSize int) []byte {
6364
func constructJSONValue(keyNumber int, kvSize int) []byte {
6465
prefix := constructValuePrefix(keyNumber)
6566

66-
rand.Seed(int64(keyNumber))
67-
color := colors[rand.Intn(len(colors))]
68-
size := rand.Intn(len(colors))*10 + 10
69-
owner := owners[rand.Intn(len(owners))]
67+
var seed [32]byte
68+
_, _ = crand.Read(seed[:])
69+
r := rand.New(rand.NewChaCha8(seed))
70+
71+
color := colors[r.IntN(len(colors))]
72+
size := r.IntN(len(colors))*10 + 10
73+
owner := owners[r.IntN(len(owners))]
7074
assetName := "marble" + strconv.Itoa(keyNumber)
7175

7276
testRecord := marbleRecord{Prefix: string(prefix), AssetType: "marble", AssetName: assetName, Color: color, Size: size, Owner: owner}
@@ -126,7 +130,7 @@ func calculateShare(total int, numParts int, partNum int) int {
126130

127131
func constructRandomBytes(length int) []byte {
128132
b := make([]byte, length)
129-
rand.Read(b)
133+
crand.Read(b)
130134
return b
131135
}
132136

core/peer/peer_test.go

+2-3
Original file line numberDiff line numberDiff line change
@@ -9,18 +9,17 @@ package peer
99
import (
1010
"fmt"
1111
"io/ioutil"
12-
"math/rand"
12+
"math/rand/v2"
1313
"os"
1414
"path/filepath"
1515
"runtime"
1616
"testing"
1717
"time"
1818

19-
"github.com/hyperledger/fabric/common/channelconfig"
20-
2119
"github.com/hyperledger/fabric-protos-go/common"
2220
pb "github.com/hyperledger/fabric-protos-go/peer"
2321
"github.com/hyperledger/fabric/bccsp/sw"
22+
"github.com/hyperledger/fabric/common/channelconfig"
2423
configtxtest "github.com/hyperledger/fabric/common/configtx/test"
2524
"github.com/hyperledger/fabric/common/crypto/tlsgen"
2625
"github.com/hyperledger/fabric/common/metrics/disabled"

0 commit comments

Comments
 (0)