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