kubo/test/cli/testutils/random_deterministic.go
Hector Sanjuan 6b55e64918
Some checks failed
CodeQL / codeql (push) Has been cancelled
Docker Build / docker-build (push) Has been cancelled
Gateway Conformance / gateway-conformance (push) Has been cancelled
Gateway Conformance / gateway-conformance-libp2p-experiment (push) Has been cancelled
Go Build / go-build (push) Has been cancelled
Go Check / go-check (push) Has been cancelled
Go Lint / go-lint (push) Has been cancelled
Go Test / go-test (push) Has been cancelled
Interop / interop-prep (push) Has been cancelled
Sharness / sharness-test (push) Has been cancelled
Spell Check / spellcheck (push) Has been cancelled
Interop / helia-interop (push) Has been cancelled
Interop / ipfs-webui (push) Has been cancelled
feat(config): ipfs add and Import options for controling UnixFS DAG Width (#10774)
Co-authored-by: Marcin Rataj <lidel@lidel.org>
2025-04-15 22:56:38 +02:00

47 lines
1.1 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
}
// createRandomReader produces specified number of pseudo-random bytes
// from a seed.
func DeterministicRandomReader(sizeStr string, seed string) (io.Reader, error) {
size, err := humanize.ParseBytes(sizeStr)
if err != nil {
return nil, err
}
// 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: int64(size)}, nil
}