aboutsummaryrefslogtreecommitdiffstats
path: root/pow/ezp/pow.go
blob: 540381243fb761be11c5028e349c46f42b3bfb71 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package ezp

import (
    "math/big"
    "math/rand"
    "time"

    "github.com/ethereum/go-ethereum/crypto"
    "github.com/ethereum/go-ethereum/crypto/sha3"
    "github.com/ethereum/go-ethereum/ethutil"
    "github.com/ethereum/go-ethereum/logger"
    "github.com/ethereum/go-ethereum/pow"
)

var powlogger = logger.NewLogger("POW")

type EasyPow struct {
    hash     *big.Int
    HashRate int64
    turbo    bool
}

func New() *EasyPow {
    return &EasyPow{turbo: false}
}

func (pow *EasyPow) GetHashrate() int64 {
    return pow.HashRate
}

func (pow *EasyPow) Turbo(on bool) {
    pow.turbo = on
}

func (pow *EasyPow) Search(block pow.Block, stop <-chan struct{}) []byte {
    r := rand.New(rand.NewSource(time.Now().UnixNano()))
    hash := block.HashNoNonce()
    diff := block.Difficulty()
    //i := int64(0)
    // TODO fix offset
    i := rand.Int63()
    starti := i
    start := time.Now().UnixNano()

    defer func() { pow.HashRate = 0 }()

    // Make sure stop is empty
empty:
    for {
        select {
        case <-stop:
        default:
            break empty
        }
    }

    for {
        select {
        case <-stop:
            return nil
        default:
            i++

            elapsed := time.Now().UnixNano() - start
            hashes := ((float64(1e9) / float64(elapsed)) * float64(i-starti)) / 1000
            pow.HashRate = int64(hashes)

            sha := crypto.Sha3(big.NewInt(r.Int63()).Bytes())
            if verify(hash, diff, sha) {
                return sha
            }
        }

        if !pow.turbo {
            time.Sleep(20 * time.Microsecond)
        }
    }

    return nil
}

func (pow *EasyPow) Verify(block pow.Block) bool {
    return Verify(block)
}

func verify(hash []byte, diff *big.Int, nonce []byte) bool {
    sha := sha3.NewKeccak256()

    d := append(hash, nonce...)
    sha.Write(d)

    verification := new(big.Int).Div(ethutil.BigPow(2, 256), diff)
    res := ethutil.BigD(sha.Sum(nil))

    return res.Cmp(verification) <= 0
}

func Verify(block pow.Block) bool {
    return verify(block.HashNoNonce(), block.Difficulty(), block.N())
}