kubo/test/cli/testutils/random_deterministic.go
Marcin Rataj 6a008fc74c
refactor: apply go fix modernizers from Go 1.26 (#11190)
* chore: apply go fix modernizers from Go 1.26

automated refactoring: interface{} to any, slices.Contains,
and other idiomatic updates.

* feat(ci): add `go fix` check to Go analysis workflow

ensures Go 1.26 modernizers are applied, fails CI if `go fix ./...`
produces any changes (similar to existing `go fmt` enforcement)
2026-02-11 01:01:32 +01:00

50 lines
1.4 KiB
Go

package testutils
import (
"crypto/sha256"
"io"
"github.com/dustin/go-humanize"
"golang.org/x/crypto/chacha20"
)
type randomReader struct {
cipher *chacha20.Cipher
remaining int64
}
func (r *randomReader) Read(p []byte) (int, error) {
if r.remaining <= 0 {
return 0, io.EOF
}
n := min(int64(len(p)), r.remaining)
// Generate random bytes directly into the provided buffer
r.cipher.XORKeyStream(p[:n], make([]byte, n))
r.remaining -= n
return int(n), nil
}
// DeterministicRandomReader produces specified number of pseudo-random bytes
// from a seed. Size can be specified as a humanize string (e.g., "256KiB", "1MiB").
func DeterministicRandomReader(sizeStr string, seed string) (io.Reader, error) {
size, err := humanize.ParseBytes(sizeStr)
if err != nil {
return nil, err
}
return DeterministicRandomReaderBytes(int64(size), seed)
}
// DeterministicRandomReaderBytes produces exactly `size` pseudo-random bytes
// from a seed. Use this when exact byte precision is needed.
func DeterministicRandomReaderBytes(size int64, seed string) (io.Reader, error) {
// Hash the seed string to a 32-byte key for ChaCha20
key := sha256.Sum256([]byte(seed))
// Use ChaCha20 for deterministic random bytes
var nonce [chacha20.NonceSize]byte // Zero nonce for simplicity
cipher, err := chacha20.NewUnauthenticatedCipher(key[:chacha20.KeySize], nonce[:])
if err != nil {
return nil, err
}
return &randomReader{cipher: cipher, remaining: size}, nil
}