hash-of-wisdom/internal/pow/challenge/test_utils.go

64 lines
1.4 KiB
Go

package challenge
import (
"crypto/rand"
"encoding/hex"
"time"
)
// TestConfig returns a configuration suitable for testing
func TestConfig() *Config {
secret := make([]byte, 32)
rand.Read(secret)
config, err := NewConfig(
WithHMACSecret(secret),
WithDefaultDifficulty(4),
WithRandomBytes(6),
)
if err != nil {
panic("Failed to create test config: " + err.Error())
}
return config
}
// TestChallenge returns a valid challenge for testing
func TestChallenge() *Challenge {
return &Challenge{
Timestamp: time.Now().Unix(),
Difficulty: 4,
Resource: "quotes",
Random: []byte{0xa1, 0xb2, 0xc3, 0xd4, 0xe5, 0xf6},
HMAC: nil, // To be filled by generator
}
}
// TestSolution returns a valid solution for testing
func TestSolution() *Solution {
return &Solution{
Challenge: *TestChallenge(),
Nonce: 42,
}
}
// RandomHex generates a random hex string of given length
func RandomHex(length int) string {
bytes := make([]byte, length/2)
rand.Read(bytes)
return hex.EncodeToString(bytes)
}
// ExpiredChallenge returns a challenge that has expired
func ExpiredChallenge() *Challenge {
challenge := TestChallenge()
challenge.Timestamp = time.Now().Add(-10 * time.Minute).Unix()
return challenge
}
// FutureChallenge returns a challenge with future timestamp
func FutureChallenge() *Challenge {
challenge := TestChallenge()
challenge.Timestamp = time.Now().Add(10 * time.Minute).Unix()
return challenge
}