You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

55 lines
1.2 KiB

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