OSDN Git Service

Miner - proof of work (#311)
[bytom/bytom.git] / cmd / miner / main.go
1 package main
2
3 import (
4         "context"
5         "fmt"
6
7         "github.com/bytom/blockchain"
8         "github.com/bytom/consensus/algorithm"
9         "github.com/bytom/consensus/difficulty"
10         "github.com/bytom/util"
11 )
12
13 const (
14         maxNonce = ^uint64(0) // 2^32 - 1
15 )
16
17 // do proof of work
18 func doWork(work *blockchain.WorkResp) {
19         fmt.Printf("work:%v\n", work)
20         for i := uint64(0); i <= maxNonce; i++ {
21                 work.Header.Nonce = i
22                 headerHash := work.Header.Hash()
23                 proofHash, err := algorithm.AIHash(work.Header.Height, &headerHash, work.Cache)
24                 if err != nil {
25                         fmt.Printf("Mining: failed on AIHash: %v\n", err)
26                         return
27                 }
28
29                 if difficulty.CheckProofOfWork(proofHash, work.Header.Bits) {
30                         // to do: submitWork
31                         fmt.Printf("Mining: successful-----proof hash:%v\n", proofHash)
32                         return
33                 }
34         }
35 }
36
37 func main() {
38         var work blockchain.WorkResp
39         client := util.MustRPCClient()
40         if err := client.Call(context.Background(), "/get-work", nil, &work); err == nil {
41                 doWork(&work)
42         } else {
43                 fmt.Printf("---err:%v\n", err)
44         }
45 }