pow.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. package ezp
  2. import (
  3. "encoding/binary"
  4. "math/big"
  5. "math/rand"
  6. "time"
  7. "github.com/ethereum/go-ethereum/crypto/sha3"
  8. "github.com/ethereum/go-ethereum/common"
  9. "github.com/ethereum/go-ethereum/logger"
  10. "github.com/ethereum/go-ethereum/pow"
  11. )
  12. var powlogger = logger.NewLogger("POW")
  13. type EasyPow struct {
  14. hash *big.Int
  15. HashRate int64
  16. turbo bool
  17. }
  18. func New() *EasyPow {
  19. return &EasyPow{turbo: false}
  20. }
  21. func (pow *EasyPow) GetHashrate() int64 {
  22. return pow.HashRate
  23. }
  24. func (pow *EasyPow) Turbo(on bool) {
  25. pow.turbo = on
  26. }
  27. func (pow *EasyPow) Search(block pow.Block, stop <-chan struct{}) (uint64, []byte, []byte) {
  28. r := rand.New(rand.NewSource(time.Now().UnixNano()))
  29. hash := block.HashNoNonce()
  30. diff := block.Difficulty()
  31. //i := int64(0)
  32. // TODO fix offset
  33. i := rand.Int63()
  34. starti := i
  35. start := time.Now().UnixNano()
  36. defer func() { pow.HashRate = 0 }()
  37. // Make sure stop is empty
  38. empty:
  39. for {
  40. select {
  41. case <-stop:
  42. default:
  43. break empty
  44. }
  45. }
  46. for {
  47. select {
  48. case <-stop:
  49. return 0, nil, nil
  50. default:
  51. i++
  52. elapsed := time.Now().UnixNano() - start
  53. hashes := ((float64(1e9) / float64(elapsed)) * float64(i-starti)) / 1000
  54. pow.HashRate = int64(hashes)
  55. sha := uint64(r.Int63())
  56. if verify(hash, diff, sha) {
  57. return sha, nil, nil
  58. }
  59. }
  60. if !pow.turbo {
  61. time.Sleep(20 * time.Microsecond)
  62. }
  63. }
  64. return 0, nil, nil
  65. }
  66. func (pow *EasyPow) Verify(block pow.Block) bool {
  67. return Verify(block)
  68. }
  69. func verify(hash []byte, diff *big.Int, nonce uint64) bool {
  70. sha := sha3.NewKeccak256()
  71. n := make([]byte, 8)
  72. binary.PutUvarint(n, nonce)
  73. d := append(hash, n...)
  74. sha.Write(d)
  75. verification := new(big.Int).Div(common.BigPow(2, 256), diff)
  76. res := common.BigD(sha.Sum(nil))
  77. return res.Cmp(verification) <= 0
  78. }
  79. func Verify(block pow.Block) bool {
  80. return verify(block.HashNoNonce(), block.Difficulty(), block.Nonce())
  81. }