Skip to content

Commit

Permalink
migrate math/rand to v2
Browse files Browse the repository at this point in the history
  • Loading branch information
LuisPH3 committed Nov 12, 2024
1 parent 293a777 commit e3b0e47
Show file tree
Hide file tree
Showing 22 changed files with 122 additions and 108 deletions.
2 changes: 1 addition & 1 deletion evmcore/tx_list_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ package evmcore

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

"github.com/ethereum/go-ethereum/core/types"
Expand Down
4 changes: 2 additions & 2 deletions evmcore/tx_pool.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import (
"errors"
"math"
"math/big"
"math/rand"
"math/rand/v2"
"sort"
"sync"
"time"
Expand Down Expand Up @@ -594,7 +594,7 @@ func sampleTxHashes(txListsMap map[common.Address]*txList, max int) (out []commo
first := 0
last := len(txListsMap) - 1
if len(txListsMap) > max {
first = rand.Intn(len(txListsMap))
first = rand.IntN(len(txListsMap))
last = (first + max) % len(txListsMap)
}

Expand Down
12 changes: 7 additions & 5 deletions evmcore/tx_pool_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import (
"errors"
"fmt"
"math/big"
"math/rand"
"math/rand/v2"
"os"
"sync"
"testing"
Expand Down Expand Up @@ -158,7 +158,9 @@ func pricedTransaction(nonce uint64, gaslimit uint64, gasprice *big.Int, key *ec

func pricedDataTransaction(nonce uint64, gaslimit uint64, gasprice *big.Int, key *ecdsa.PrivateKey, bytes uint64) *types.Transaction {
data := make([]byte, bytes)
rand.Read(data)
for i := range data {
data[i] = byte(rand.IntN(256))
}

tx, _ := types.SignTx(types.NewTransaction(nonce, common.Address{}, big.NewInt(0), gaslimit, gasprice, data), types.HomesteadSigner{}, key)
return tx
Expand Down Expand Up @@ -1054,7 +1056,7 @@ func testTransactionQueueGlobalLimiting(t *testing.T, nolocals bool) {

txs := make(types.Transactions, 0, 3*config.GlobalQueue)
for len(txs) < cap(txs) {
key := keys[rand.Intn(len(keys)-1)] // skip adding transactions with the local account
key := keys[rand.IntN(len(keys)-1)] // skip adding transactions with the local account
addr := crypto.PubkeyToAddress(key.PublicKey)

txs = append(txs, transaction(nonces[addr]+1, 100000, key))
Expand Down Expand Up @@ -1440,15 +1442,15 @@ func TestTransactionAllowedTxSize(t *testing.T) {
t.Fatalf("failed to add transaction of size %d, close to maximal: %v", int(tx.Size()), err)
}
// Try adding a transaction with random allowed size
if err := pool.addRemoteSync(pricedDataTransaction(1, pool.currentMaxGas, big.NewInt(1), key, uint64(rand.Intn(int(dataSize))))); err != nil {
if err := pool.addRemoteSync(pricedDataTransaction(1, pool.currentMaxGas, big.NewInt(1), key, uint64(rand.IntN(int(dataSize))))); err != nil {
t.Fatalf("failed to add transaction of random allowed size: %v", err)
}
// Try adding a transaction of minimal not allowed size
if err := pool.addRemoteSync(pricedDataTransaction(2, pool.currentMaxGas, big.NewInt(1), key, txMaxSize)); err == nil {
t.Fatalf("expected rejection on slightly oversize transaction")
}
// Try adding a transaction of random not allowed size
if err := pool.addRemoteSync(pricedDataTransaction(2, pool.currentMaxGas, big.NewInt(1), key, dataSize+1+uint64(rand.Intn(10*txMaxSize)))); err == nil {
if err := pool.addRemoteSync(pricedDataTransaction(2, pool.currentMaxGas, big.NewInt(1), key, dataSize+1+uint64(rand.IntN(10*txMaxSize)))); err == nil {
t.Fatalf("expected rejection on oversize transaction")
}
// Run some sanity checks on the pool internals
Expand Down
4 changes: 2 additions & 2 deletions gossip/dummy_tx_pool.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ package gossip

import (
"math/big"
"math/rand"
"math/rand/v2"
"sort"
"sync"

Expand Down Expand Up @@ -134,7 +134,7 @@ func (p *dummyTxPool) SampleHashes(max int) []common.Hash {
res := make([]common.Hash, 0, max)
skip := 0
if len(p.pool) > max {
skip = rand.Intn(len(p.pool) - max)
skip = rand.IntN(len(p.pool) - max)
}
for _, tx := range p.pool {
if len(res) >= max {
Expand Down
11 changes: 6 additions & 5 deletions gossip/emitter/config.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
package emitter

import (
"github.com/Fantom-foundation/go-opera/version"
"math/rand"
"math/rand/v2"
"time"

"github.com/Fantom-foundation/go-opera/version"

"github.com/Fantom-foundation/go-opera/inter/validatorpk"
"github.com/Fantom-foundation/go-opera/opera"
"github.com/Fantom-foundation/lachesis-base/inter/idx"
Expand Down Expand Up @@ -79,15 +80,15 @@ func DefaultConfig() Config {
}

// RandomizeEmitTime and return new config
func (cfg EmitIntervals) RandomizeEmitTime(r *rand.Rand) EmitIntervals {
func (cfg EmitIntervals) RandomizeEmitTime(rand *rand.Rand) EmitIntervals {
config := cfg
// value = value - 0.1 * value + 0.1 * random value
if config.Max > 10 {
config.Max = config.Max - config.Max/10 + time.Duration(r.Int63n(int64(config.Max/10)))
config.Max = config.Max - config.Max/10 + time.Duration(rand.Int64N(int64(config.Max/10)))
}
// value = value + 0.33 * random value
if config.DoublesignProtection > 3 {
config.DoublesignProtection = config.DoublesignProtection + time.Duration(r.Int63n(int64(config.DoublesignProtection/3)))
config.DoublesignProtection = config.DoublesignProtection + time.Duration(rand.Int64N(int64(config.DoublesignProtection/3)))
}
return config
}
Expand Down
6 changes: 3 additions & 3 deletions gossip/emitter/emitter.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package emitter
import (
"errors"
"fmt"
"math/rand"
"math/rand/v2"
"os"
"strings"
"sync"
Expand Down Expand Up @@ -112,8 +112,8 @@ func NewEmitter(
) *Emitter {
// Randomize event time to decrease chance of 2 parallel instances emitting event at the same time
// It increases the chance of detecting parallel instances
r := rand.New(rand.NewSource(time.Now().UnixNano()))
config.EmitIntervals = config.EmitIntervals.RandomizeEmitTime(r)
rand := rand.New(rand.NewPCG(uint64(os.Getpid()), uint64(time.Now().UnixNano())))
config.EmitIntervals = config.EmitIntervals.RandomizeEmitTime(rand)

return &Emitter{
config: config,
Expand Down
6 changes: 3 additions & 3 deletions gossip/emitter/ordering_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ package emitter
import (
"crypto/ecdsa"
"math/big"
"math/rand"
"math/rand/v2"
"testing"
"time"

Expand Down Expand Up @@ -61,7 +61,7 @@ func testTransactionPriceNonceSort(t *testing.T, baseFee *big.Int) {
count := 25
for i := 0; i < 25; i++ {
var tx *types.Transaction
gasFeeCap := rand.Intn(50)
gasFeeCap := rand.IntN(50)
if baseFee == nil {
tx = types.NewTx(&types.LegacyTx{
Nonce: uint64(start + i),
Expand All @@ -78,7 +78,7 @@ func testTransactionPriceNonceSort(t *testing.T, baseFee *big.Int) {
Value: big.NewInt(100),
Gas: 100,
GasFeeCap: big.NewInt(int64(gasFeeCap)),
GasTipCap: big.NewInt(int64(rand.Intn(gasFeeCap + 1))),
GasTipCap: big.NewInt(int64(rand.IntN(gasFeeCap + 1))),
Data: nil,
})
if count == 25 && int64(gasFeeCap) < baseFee.Int64() {
Expand Down
4 changes: 2 additions & 2 deletions gossip/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import (
"errors"
"fmt"
"math"
"math/rand"
"math/rand/v2"
"strings"
"sync"
"time"
Expand Down Expand Up @@ -1024,7 +1024,7 @@ func (h *handler) txBroadcastLoop() {
if len(peers) == 0 {
continue
}
randPeer := peers[rand.Intn(len(peers))]
randPeer := peers[rand.IntN(len(peers))]
h.syncTransactions(randPeer, h.txpool.SampleHashes(h.config.Protocol.MaxRandomTxHashesSend))
}
}
Expand Down
4 changes: 2 additions & 2 deletions gossip/handler_fuzz.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ package gossip
import (
"bytes"
"errors"
"math/rand"
"math/rand/v2"
"sync"

"github.com/Fantom-foundation/lachesis-base/utils/cachescale"
Expand Down Expand Up @@ -123,7 +123,7 @@ func makeFuzzedHandler() (h *handler, err error) {

func randomID() (id enode.ID) {
for i := range id {
id[i] = byte(rand.Intn(255))
id[i] = byte(rand.IntN(255))
}
return id
}
Expand Down
6 changes: 3 additions & 3 deletions gossip/protocols/dag/dagstream/dagstreamleecher/leecher.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package dagstreamleecher

import (
"math/rand"
"math/rand/v2"
"slices"
"time"

Expand Down Expand Up @@ -140,8 +140,8 @@ func getSessionID(epoch idx.Epoch, try uint32) uint32 {
}

func (d *Leecher) startSession(candidates []string) {
peer := candidates[rand.Intn(len(candidates))]
if d.session.try == 0 && rand.Intn(50) != 0 {
peer := candidates[rand.IntN(len(candidates))]
if d.session.try == 0 && rand.IntN(50) != 0 {
// try previous successful peer first
if slices.Contains(candidates, d.session.peer) {
peer = d.session.peer
Expand Down
22 changes: 11 additions & 11 deletions gossip/protocols/dag/dagstream/dagstreamleecher/leecher_test.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package dagstreamleecher

import (
"math/rand"
"math/rand/v2"
"strconv"
"testing"
"time"
Expand All @@ -16,7 +16,7 @@ import (

func TestLeecherNoDeadlocks(t *testing.T) {
for try := 0; try < 10; try++ {
testLeecherNoDeadlocks(t, 1+rand.Intn(500))
testLeecherNoDeadlocks(t, 1+rand.IntN(500))
}
}

Expand All @@ -34,25 +34,25 @@ func testLeecherNoDeadlocks(t *testing.T, maxPeers int) {
config.BaseProgressWatchdog = 3 * time.Millisecond * 5
config.Session.RecheckInterval = time.Millisecond
epoch := idx.Epoch(1)
leecher := New(epoch, rand.Intn(2) == 0, config, Callbacks{
leecher := New(epoch, rand.IntN(2) == 0, config, Callbacks{
IsProcessed: func(id hash.Event) bool {
return rand.Intn(2) == 0
return rand.IntN(2) == 0
},
RequestChunk: func(peer string, r dagstream.Request) error {
requests <- peerRequest{peer, r}
return nil
},
Suspend: func(peer string) bool {
return rand.Intn(10) == 0
return rand.IntN(10) == 0
},
PeerEpoch: func(peer string) idx.Epoch {
return 1 + epoch/2 + idx.Epoch(rand.Intn(int(epoch*2)))
return 1 + epoch/2 + idx.Epoch(rand.IntN(int(epoch*2)))
},
})
terminated := false
for i := 0; i < maxPeers*2; i++ {
peer := strconv.Itoa(rand.Intn(maxPeers))
coin := rand.Intn(100)
peer := strconv.Itoa(rand.IntN(maxPeers))
coin := rand.IntN(100)
if coin <= 50 {
err := leecher.RegisterPeer(peer)
if !terminated {
Expand All @@ -73,15 +73,15 @@ func testLeecherNoDeadlocks(t *testing.T, maxPeers int) {
}
select {
case req := <-requests:
if rand.Intn(10) != 0 {
err := leecher.NotifyChunkReceived(req.request.Session.ID, hash.FakeEvent(), rand.Intn(5) == 0)
if rand.IntN(10) != 0 {
err := leecher.NotifyChunkReceived(req.request.Session.ID, hash.FakeEvent(), rand.IntN(5) == 0)
if !terminated {
require.NoError(t, err)
}
}
default:
}
if !terminated && rand.Intn(maxPeers*2) == 0 {
if !terminated && rand.IntN(maxPeers*2) == 0 {
terminated = true
leecher.Terminate()
}
Expand Down
2 changes: 1 addition & 1 deletion gossip/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import (
"errors"
"fmt"
"math/big"
"math/rand"
"math/rand/v2"
"sync"
"sync/atomic"
"time"
Expand Down
7 changes: 4 additions & 3 deletions gossip/sync.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
package gossip

import (
"math/rand/v2"
"sync/atomic"

"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/metrics"
"github.com/ethereum/go-ethereum/p2p/enode"
"math/rand"
"sync/atomic"
)

var isMaybeSyncedGauge = metrics.GetOrRegisterGauge("chain/maybeSynced", nil)
Expand Down Expand Up @@ -97,7 +98,7 @@ func (h *handler) txsyncLoop() {
if len(pending) == 0 {
return nil
}
n := rand.Intn(len(pending)) + 1
n := rand.IntN(len(pending)) + 1
for _, s := range pending {
if n--; n == 0 {
return s
Expand Down
15 changes: 8 additions & 7 deletions gossip/tx_scrambler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@ package gossip
import (
"cmp"
"fmt"
"github.com/ethereum/go-ethereum/common"
"golang.org/x/exp/rand"
"math/rand/v2"
"slices"
"testing"

"github.com/ethereum/go-ethereum/common"
)

func TestTxScrambler_AnalyseEntryList_RemovesDuplicateTransactions(t *testing.T) {
Expand Down Expand Up @@ -123,7 +124,7 @@ func TestTxScrambler_ScrambleTransactions_ScrambleIsDeterministic(t *testing.T)
res2 := slices.Clone(res1)

for i := 0; i < 10; i++ {
salt := createRandomSalt(t)
salt := createRandomSalt()
scrambleTransactions(res1, salt)
for j := 0; j < 10; j++ {
shuffleEntries(res2)
Expand Down Expand Up @@ -633,7 +634,7 @@ func createRandomScramblerTestInput(size int64) []ScramblerEntry {
var entries []ScramblerEntry
for i := int64(0); i < size; i++ {
// same hashes must have same data
r := rand.Intn(100 - 1)
r := rand.IntN(100 - 1)
entries = append(entries, &dummyScramblerEntry{
hash: common.Hash{byte(r)},
sender: common.Address{byte(r)},
Expand Down Expand Up @@ -663,10 +664,10 @@ func checkDuplicateHashes(t *testing.T, entries []ScramblerEntry) {
}
}

func createRandomSalt(t *testing.T) [32]byte {
func createRandomSalt() [32]byte {
var salt = [32]byte{}
if _, err := rand.Read(salt[:]); err != nil {
t.Fatalf("cannot create random salt: %v", err)
for i := 0; i < 32; i++ {
salt[i] = byte(rand.IntN(256))
}
return salt
}
Expand Down
Loading

0 comments on commit e3b0e47

Please sign in to comment.