Skip to content

Commit

Permalink
change math/rand to v2
Browse files Browse the repository at this point in the history
Signed-off-by: Fedor Partanskiy <fredprtnsk@gmail.com>
  • Loading branch information
pfi79 committed Sep 26, 2024
1 parent 63b5155 commit a2cda3e
Show file tree
Hide file tree
Showing 27 changed files with 148 additions and 102 deletions.
2 changes: 1 addition & 1 deletion cmd/common/cli_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ package common
import (
"bytes"
"fmt"
"math/rand"
"math/rand/v2"
"os"
"path/filepath"
"testing"
Expand Down
7 changes: 5 additions & 2 deletions cmd/common/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@ SPDX-License-Identifier: Apache-2.0
package common

import (
crand "crypto/rand"
"fmt"
"math/rand"
"math/rand/v2"
"os"
"path/filepath"
"testing"
Expand All @@ -20,7 +21,9 @@ import (
)

func TestConfig(t *testing.T) {
r := rand.New(rand.NewSource(time.Now().UnixNano()))
var seed [32]byte
_, _ = crand.Read(seed[:])
r := rand.New(rand.NewChaCha8(seed))
configFilePath := filepath.Join(os.TempDir(), fmt.Sprintf("config-%d.yaml", r.Int()))
fmt.Println(configFilePath)
t.Run("save and load a config", func(t *testing.T) {
Expand Down
6 changes: 3 additions & 3 deletions common/configtx/util_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ SPDX-License-Identifier: Apache-2.0
package configtx

import (
"math/rand"
"math/rand/v2"
"testing"

cb "github.com/hyperledger/fabric-protos-go-apiv2/common"
Expand Down Expand Up @@ -101,7 +101,7 @@ func randomLowerAlphaString(size int) string {
letters := []rune("abcdefghijklmnopqrstuvwxyz")
output := make([]rune, size)
for i := range output {
output[i] = letters[rand.Intn(len(letters))]
output[i] = letters[rand.IntN(len(letters))]
}
return string(output)
}
Expand All @@ -110,7 +110,7 @@ func randomAlphaString(size int) string {
letters := []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
output := make([]rune, size)
for i := range output {
output[i] = letters[rand.Intn(len(letters))]
output[i] = letters[rand.IntN(len(letters))]
}
return string(output)
}
Expand Down
4 changes: 2 additions & 2 deletions common/deliverclient/orderers/connection.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import (
"crypto/md5"
"crypto/sha256"
"fmt"
"math/rand"
"math/rand/v2"
"sync"

"github.com/hyperledger/fabric-lib-go/common/flogging"
Expand Down Expand Up @@ -73,7 +73,7 @@ func (cs *ConnectionSource) RandomEndpoint() (*Endpoint, error) {
if len(cs.allEndpoints) == 0 {
return nil, errors.Errorf("no endpoints currently defined")
}
return cs.allEndpoints[rand.Intn(len(cs.allEndpoints))], nil
return cs.allEndpoints[rand.IntN(len(cs.allEndpoints))], nil
}

func (cs *ConnectionSource) Endpoints() []*Endpoint {
Expand Down
10 changes: 6 additions & 4 deletions common/graph/perm.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,16 @@ SPDX-License-Identifier: Apache-2.0
package graph

import (
"math/rand"
"time"
crand "crypto/rand"
"math/rand/v2"
)

var r *rand.Rand

func init() {
r = rand.New(rand.NewSource(time.Now().UnixNano()))
var seed [32]byte
_, _ = crand.Read(seed[:])
r = rand.New(rand.NewChaCha8(seed))
}

// treePermutations represents possible permutations
Expand Down Expand Up @@ -112,7 +114,7 @@ func (tp *treePermutations) computeDescendantPermutations() {
// Ensure we don't have too much combinations of descendants
for CombinationsExceed(len(v.Descendants), v.Threshold, tp.combinationUpperBound) {
// Randomly pick a descendant, and remove it
victim := r.Intn(len(v.Descendants))
victim := r.IntN(len(v.Descendants))
v.Descendants = append(v.Descendants[:victim], v.Descendants[victim+1:]...)
}

Expand Down
10 changes: 6 additions & 4 deletions core/common/validation/fullflow_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@ SPDX-License-Identifier: Apache-2.0
package validation

import (
crand "crypto/rand"
"fmt"
"math/rand"
"math/rand/v2"
"os"
"testing"
"time"

"github.com/hyperledger/fabric-lib-go/bccsp/sw"
"github.com/hyperledger/fabric-protos-go-apiv2/common"
Expand Down Expand Up @@ -206,8 +206,10 @@ func TestTXWithTwoActionsRejected(t *testing.T) {
}

func corrupt(bytes []byte) {
r := rand.New(rand.NewSource(time.Now().UnixNano()))
bytes[r.Intn(len(bytes))]--
var seed [32]byte
_, _ = crand.Read(seed[:])
r := rand.New(rand.NewChaCha8(seed))
bytes[r.IntN(len(bytes))]--
}

func TestBadTx(t *testing.T) {
Expand Down
47 changes: 30 additions & 17 deletions core/common/validation/statebased/vpmanager_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,13 @@ SPDX-License-Identifier: Apache-2.0
package statebased

import (
crand "crypto/rand"
"fmt"
"math/rand"
"math/rand/v2"
"runtime"
"strconv"
"sync"
"testing"
"time"

"github.com/hyperledger/fabric-protos-go-apiv2/ledger/rwset"
"github.com/hyperledger/fabric-protos-go-apiv2/ledger/rwset/kvrwset"
Expand Down Expand Up @@ -169,8 +169,8 @@ func pvtRwsetUpdatingMetadataFor(cc, coll, key string) []byte {
})
}

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

func TestTranslatorBadPolicy(t *testing.T) {
t.Parallel()
seed := time.Now().Unix()
var seed [32]byte
_, _ = crand.Read(seed[:])

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

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

func TestTranslatorBadPolicyPvt(t *testing.T) {
t.Parallel()
seed := time.Now().Unix()
var seed [32]byte
_, _ = crand.Read(seed[:])

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

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

func TestDependencyNoConflict(t *testing.T) {
t.Parallel()
seed := time.Now().Unix()
var seed [32]byte
_, _ = crand.Read(seed[:])

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

func TestDependencyConflict(t *testing.T) {
t.Parallel()
seed := time.Now().Unix()
var seed [32]byte
_, _ = crand.Read(seed[:])

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

func TestMultipleDependencyNoConflict(t *testing.T) {
t.Parallel()
seed := time.Now().Unix()
var seed [32]byte
_, _ = crand.Read(seed[:])

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

func TestMultipleDependencyConflict(t *testing.T) {
t.Parallel()
seed := time.Now().Unix()
var seed [32]byte
_, _ = crand.Read(seed[:])

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

func TestPvtDependencyNoConflict(t *testing.T) {
t.Parallel()
seed := time.Now().Unix()
var seed [32]byte
_, _ = crand.Read(seed[:])

// Scenario: like TestDependencyNoConflict but for private data

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

func TestPvtDependencyConflict(t *testing.T) {
t.Parallel()
seed := time.Now().Unix()
var seed [32]byte
_, _ = crand.Read(seed[:])

// Scenario: like TestDependencyConflict but for private data

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

func TestLedgerErrors(t *testing.T) {
t.Parallel()
seed := time.Now().Unix()
var seed [32]byte
_, _ = crand.Read(seed[:])

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

func TestBadRwsetIsNoDependency(t *testing.T) {
t.Parallel()
seed := time.Now().Unix()
var seed [32]byte
_, _ = crand.Read(seed[:])

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

func TestWritesIntoDifferentNamespaces(t *testing.T) {
t.Parallel()
seed := time.Now().Unix()
var seed [32]byte
_, _ = crand.Read(seed[:])

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

func TestCombinedCalls(t *testing.T) {
t.Parallel()
seed := time.Now().Unix()
var seed [32]byte
_, _ = crand.Read(seed[:])

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

func TestForRaces(t *testing.T) {
seed := time.Now().Unix()
var seed [32]byte
_, _ = crand.Read(seed[:])

// scenario to stress test the parallel validation
// this is an extended combined test
Expand Down
25 changes: 10 additions & 15 deletions core/ledger/kvledger/benchmark/experiments/readwrite_txs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@ SPDX-License-Identifier: Apache-2.0
package experiments

import (
crand "crypto/rand"
"fmt"
"math/rand"
"math/rand/v2"
"sync"
"testing"
"time"

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

for i := 0; i < numTx; i++ {
for range numTx {
simulator, err := chain.NewTxSimulator(util.GenerateUUID())
panicOnError(err)
maxKeys := max(numReadsPerTx, numWritesPerTx)
keysToOperateOn := []int{}
for i := 0; i < maxKeys; i++ {
keysToOperateOn = append(keysToOperateOn, rand.Intn(maxKeyNumber))
for range maxKeys {
keysToOperateOn = append(keysToOperateOn, rand.IntN(maxKeyNumber))
}

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

for i := 0; i < numWritesPerTx; i++ {
for i := range numWritesPerTx {
keyNumber := keysToOperateOn[i]
key := constructKey(keyNumber)
if useJSON {
Expand All @@ -109,10 +111,3 @@ func runReadWriteClient(chain *chainmgmt.Chain, rand *rand.Rand, numTx int, wg *
}
wg.Done()
}

func max(a, b int) int {
if a > b {
return a
}
return b
}
17 changes: 10 additions & 7 deletions core/ledger/kvledger/benchmark/experiments/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@ package experiments

import (
"bytes"
crypto "crypto/rand"
crand "crypto/rand"
"encoding/json"
"fmt"
"math/rand"
"math/rand/v2"
"strconv"
)

Expand Down Expand Up @@ -64,10 +64,13 @@ func constructValue(keyNumber int, kvSize int) []byte {
func constructJSONValue(keyNumber int, kvSize int) []byte {
prefix := constructValuePrefix(keyNumber)

r := rand.New(rand.NewSource(int64(keyNumber)))
color := colors[r.Intn(len(colors))]
size := r.Intn(len(colors))*10 + 10
owner := owners[r.Intn(len(owners))]
var seed [32]byte
_, _ = crand.Read(seed[:])
r := rand.New(rand.NewChaCha8(seed))

color := colors[r.IntN(len(colors))]
size := r.IntN(len(colors))*10 + 10
owner := owners[r.IntN(len(owners))]
assetName := "marble" + strconv.Itoa(keyNumber)

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

func constructRandomBytes(length int) []byte {
b := make([]byte, length)
crypto.Read(b)
crand.Read(b)
return b
}

Expand Down
Loading

0 comments on commit a2cda3e

Please sign in to comment.