arnaucube
arnaucube/slowlorisdbPublic Self-hosted repository
slowlorisdb/core/common.go
core/common.goRaw
 1package core
 2
 3import (
 4	"bytes"
 5	"crypto/sha256"
 6)
 7
 8// Hash is the type for a hash data packet
 9type Hash [32]byte
10
11// IsZero returns true if the Hash is empty (all zeroes)
12func (h *Hash) IsZero() bool {
13	z := Hash{}
14	if bytes.Equal(z[:], h[:]) {
15		return true
16	}
17	return false
18}
19
20// HashBytes performs a hash over a given byte array
21func HashBytes(b []byte) Hash {
22	h := sha256.Sum256(b)
23	return h
24}
25
26// PoWData is the interface for the data that have the Nonce parameter to calculate the Proof-of-Work
27type PoWData interface {
28	Bytes() []byte
29	GetNonce() uint64
30	IncrementNonce()
31}
32
33// CheckPoW verifies the PoW difficulty of a Hash
34func CheckPoW(hash Hash, difficulty uint64) bool {
35	var empty [32]byte
36	if !bytes.Equal(hash[:][0:difficulty], empty[0:difficulty]) {
37		return false
38	}
39	return true
40}
41
42// CalculatePoW calculates the nonce for the given data in order to fit in the current Proof of Work difficulty
43func CalculatePoW(data PoWData, difficulty uint64) (uint64, error) {
44	hash := HashBytes(data.Bytes())
45	for !CheckPoW(hash, difficulty) {
46		data.IncrementNonce()
47
48		hash = HashBytes(data.Bytes())
49	}
50	return data.GetNonce(), nil
51}