github.com/ethereum/go-ethereum@v1.14.3/internal/testrand/rand.go (about)

     1  // Copyright 2023 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package testrand
    18  
    19  import (
    20  	crand "crypto/rand"
    21  	"encoding/binary"
    22  	mrand "math/rand"
    23  
    24  	"github.com/ethereum/go-ethereum/common"
    25  )
    26  
    27  // prng is a pseudo random number generator seeded by strong randomness.
    28  // The randomness is printed on startup in order to make failures reproducible.
    29  var prng = initRand()
    30  
    31  func initRand() *mrand.Rand {
    32  	var seed [8]byte
    33  	crand.Read(seed[:])
    34  	rnd := mrand.New(mrand.NewSource(int64(binary.LittleEndian.Uint64(seed[:]))))
    35  	return rnd
    36  }
    37  
    38  // Bytes generates a random byte slice with specified length.
    39  func Bytes(n int) []byte {
    40  	r := make([]byte, n)
    41  	prng.Read(r)
    42  	return r
    43  }
    44  
    45  // Hash generates a random hash.
    46  func Hash() common.Hash {
    47  	return common.BytesToHash(Bytes(common.HashLength))
    48  }
    49  
    50  // Address generates a random address.
    51  func Address() common.Address {
    52  	return common.BytesToAddress(Bytes(common.AddressLength))
    53  }