OSDN Git Service

2579e2317b283047bd167378fabc1ea2c02c2700
[bytom/bytom.git] / rpc / core / generate.go
1 package core
2
3 import (
4         //"errors"
5         "math"
6         "math/big"
7         "runtime"
8         //"time"
9
10          //"github.com/blockchain/rpc/chainhash"
11          "github.com/blockchain/rpc/wire"
12 )
13
14 func solveBlock(header *wire.BlockHeader, targetDifficulty *big.Int) bool {
15         // sbResult is used by the solver goroutines to send results.
16         type sbResult struct {
17                 found bool
18                 nonce uint32
19         }
20
21         // solver accepts a block header and a nonce range to test. It is
22         // intended to be run as a goroutine.
23         quit := make(chan bool)
24         results := make(chan sbResult)
25         solver := func(hdr wire.BlockHeader, startNonce, stopNonce uint32) {
26                 // We need to modify the nonce field of the header, so make sure
27                 // we work with a copy of the original header.
28                 for i := startNonce; i >= startNonce && i <= stopNonce; i++ {
29                         select {
30                         case <-quit:
31                                 return
32                         default:
33                                 hdr.Nonce = i
34                                 hash := hdr.BlockHash()
35                                 if wire.HashToBig(&hash).Cmp(targetDifficulty) <= 0 {
36                                         results <- sbResult{true, i}
37                                         return
38                                 }
39                         }
40                 }
41                 results <- sbResult{false, 0}
42         }
43
44         startNonce := uint32(1)
45         stopNonce := uint32(math.MaxUint32)
46         numCores := uint32(runtime.NumCPU())
47         noncesPerCore := (stopNonce - startNonce) / numCores
48         for i := uint32(0); i < numCores; i++ {
49                 rangeStart := startNonce + (noncesPerCore * i)
50                 rangeStop := startNonce + (noncesPerCore * (i + 1)) - 1
51                 if i == numCores-1 {
52                         rangeStop = stopNonce
53                 }
54                 go solver(*header, rangeStart, rangeStop)
55         }
56         for i := uint32(0); i < numCores; i++ {
57                 result := <-results
58                 if result.found {
59                         close(quit)
60                         header.Nonce = result.nonce
61                         return true
62                 }
63         }
64
65         return false
66 }
67
68 func checkProofOfWork(header *wire.BlockHeader, targetDifficulty *big.Int) bool {
69      hash := hdr.BlockHash()
70      if wire.HashToBig(&hash).Cmp(targetDifficulty) <= 0 {
71              return true
72      }
73 }
74