Official Go implementation of the Ethereum protocol
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.
go-ethereum/pow/ezp/pow.go

101 lines
1.8 KiB

10 years ago
package ezp
import (
"math/big"
"math/rand"
"time"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/crypto/sha3"
10 years ago
"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 {
10 years ago
return &EasyPow{turbo: false}
10 years ago
}
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
10 years ago
start := time.Now().UnixNano()
defer func() { pow.HashRate = 0 }()
// Make sure stop is empty
empty:
for {
select {
case <-stop:
default:
break empty
}
}
10 years ago
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)
10 years ago
sha := crypto.Sha3(big.NewInt(r.Int63()).Bytes())
10 years ago
if verify(hash, diff, sha) {
10 years ago
return sha
}
}
if !pow.turbo {
time.Sleep(20 * time.Microsecond)
}
}
return nil
}
10 years ago
func (pow *EasyPow) Verify(block pow.Block) bool {
return Verify(block)
}
func verify(hash []byte, diff *big.Int, nonce []byte) bool {
10 years ago
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))
10 years ago
return res.Cmp(verification) <= 0
}
10 years ago
func Verify(block pow.Block) bool {
return verify(block.HashNoNonce(), block.Difficulty(), block.Nonce())
10 years ago
}