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.

51 lines
1.1 KiB

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