this has taken quite a while (8 ish hours) but reports and proof of work challenges are completely implemented the proof of work challenges are bit iffy and could be gpu accelerated which is bad, so i plan to eventually switch to something memory hard like argon2id references used for pow: https://dev.to/ratmd/simple-proof-of-work-in-javascript-3kgm https://anubis.techaro.lol/docs/design/how-anubis-works https://anubis.techaro.lol/docs/design/why-proof-of-work as well as some other posts or repos found when searching
125 lines
3.0 KiB
Go
125 lines
3.0 KiB
Go
package main
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"crypto/sha256"
|
|
"crypto/subtle"
|
|
"encoding/hex"
|
|
"fmt"
|
|
"log"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
type Challenge struct {
|
|
Data []byte
|
|
Difficulty int
|
|
ExpiresAt time.Time
|
|
}
|
|
|
|
type ChallengeStore struct {
|
|
mu sync.Mutex
|
|
challenges map[string]Challenge
|
|
ttl time.Duration
|
|
}
|
|
|
|
const MaxChallenges = 10000
|
|
|
|
func NewChallengeStore(ttl time.Duration) *ChallengeStore {
|
|
if ttl <= 0 || ttl > 10*time.Minute {
|
|
panic("invalid challenge ttl")
|
|
}
|
|
return &ChallengeStore{
|
|
challenges: make(map[string]Challenge),
|
|
ttl: ttl,
|
|
}
|
|
}
|
|
|
|
func (store *ChallengeStore) Issue(difficulty int) (id string, challenge Challenge, err error) {
|
|
if difficulty < 0 || difficulty > 256 {
|
|
return "", Challenge{}, fmt.Errorf("invalid difficulty")
|
|
}
|
|
if len(store.challenges) >= MaxChallenges {
|
|
return "", Challenge{}, fmt.Errorf("challenge store is full")
|
|
}
|
|
|
|
id = generateId(16)
|
|
data := make([]byte, 32)
|
|
if _, err := rand.Read(data); err != nil {
|
|
log.Println("failed to generate PoW challenge:", err)
|
|
return "", Challenge{}, err
|
|
}
|
|
challenge = Challenge{
|
|
Data: data,
|
|
Difficulty: difficulty,
|
|
ExpiresAt: time.Now().UTC().Add(store.ttl),
|
|
}
|
|
store.mu.Lock()
|
|
store.deleteExpired(time.Now().UTC())
|
|
store.challenges[id] = challenge
|
|
store.mu.Unlock()
|
|
return id, challenge, nil
|
|
}
|
|
|
|
func (store *ChallengeStore) Verify(id string, result string, nonce int) (clientError bool, err error) {
|
|
if len(id) != 16 {
|
|
return true, fmt.Errorf("invalid id")
|
|
}
|
|
if nonce < 0 {
|
|
return true, fmt.Errorf("invalid nonce")
|
|
}
|
|
store.mu.Lock()
|
|
defer store.mu.Unlock()
|
|
challenge, exists := store.challenges[id]
|
|
if !exists {
|
|
return true, fmt.Errorf("challenge not found")
|
|
}
|
|
if challenge.Difficulty < 0 || challenge.Difficulty > 256 {
|
|
return true, fmt.Errorf("invalid difficulty")
|
|
}
|
|
if !time.Now().Before(challenge.ExpiresAt) {
|
|
delete(store.challenges, id)
|
|
return true, fmt.Errorf("challenge expired")
|
|
}
|
|
if len(result) != 64 {
|
|
return true, fmt.Errorf("invalid length")
|
|
}
|
|
hashBytes, err := hex.DecodeString(result)
|
|
if err != nil {
|
|
log.Println("failed to decode result:", err)
|
|
return false, err
|
|
}
|
|
if !hasLeadingZeroBits(hashBytes, challenge.Difficulty) {
|
|
return true, fmt.Errorf("proof-of-work is not complete")
|
|
}
|
|
input := fmt.Appendf(nil, "%s%d", hex.EncodeToString(challenge.Data), nonce)
|
|
localResult := sha256.Sum256(input)
|
|
if subtle.ConstantTimeCompare(localResult[:], hashBytes) != 1 {
|
|
return true, fmt.Errorf("results do not match")
|
|
}
|
|
delete(store.challenges, id)
|
|
return true, nil
|
|
}
|
|
|
|
func (store *ChallengeStore) deleteExpired(now time.Time) {
|
|
for id, challenge := range store.challenges {
|
|
if !now.Before(challenge.ExpiresAt) {
|
|
delete(store.challenges, id)
|
|
}
|
|
}
|
|
}
|
|
|
|
func hasLeadingZeroBits(hash []byte, requiredBits int) bool {
|
|
if requiredBits < 0 || requiredBits > len(hash)*8 {
|
|
return false
|
|
}
|
|
whole, remaining := requiredBits/8, requiredBits%8
|
|
for _, b := range hash[:whole] {
|
|
if b != 0 {
|
|
return false
|
|
}
|
|
}
|
|
|
|
return remaining == 0 || hash[whole]>>(8-remaining) == 0
|
|
}
|