kubo/test/cli/testutils/random_deterministic.go
Marcin Rataj 9500a5289b test(cli): consolidate profile tests into cid_profiles_test.go
remove duplicate profile threshold tests from add_test.go since they
are fully covered by the data-driven tests in cid_profiles_test.go.

changes:
- improve test names to describe what threshold is being tested
- add inline documentation explaining each test's purpose
- add byte-precise helper IPFSAddDeterministicBytes for threshold tests
- remove ~200 lines of duplicated test code from add_test.go
- keep non-profile tests (pinning, symlinks, hidden files) in add_test.go
2026-01-27 23:35:14 +01:00

53 lines
1.5 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 := int64(len(p))
if n > r.remaining {
n = 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
}