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