github.com/quinndk/ethereum_read@v0.0.0-20181211143958-29c55eec3237/go-ethereum-master_read/consensus/ethash/sealer.go (about) 1 // Copyright 2017 The go-ethereum Authors 2 // This file is part of the go-ethereum library. 3 // 4 // The go-ethereum library is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU Lesser General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // The go-ethereum library is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU Lesser General Public License for more details. 13 // 14 // You should have received a copy of the GNU Lesser General Public License 15 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 16 17 package ethash 18 19 import ( 20 crand "crypto/rand" 21 "math" 22 "math/big" 23 "math/rand" 24 "runtime" 25 "sync" 26 27 "github.com/ethereum/go-ethereum/common" 28 "github.com/ethereum/go-ethereum/consensus" 29 "github.com/ethereum/go-ethereum/core/types" 30 "github.com/ethereum/go-ethereum/log" 31 ) 32 33 // Seal implements consensus.Engine, attempting to find a nonce that satisfies 34 // the block's difficulty requirements. 35 // Seal实现了共识引擎,找到满足块的难度要求的Nonce值。 36 func (ethash *Ethash) Seal(chain consensus.ChainReader, block *types.Block, stop <-chan struct{}) (*types.Block, error) { 37 // If we're running a fake PoW, simply return a 0 nonce immediately 38 // ModeFake模式立即返回 39 if ethash.config.PowMode == ModeFake || ethash.config.PowMode == ModeFullFake { 40 header := block.Header() 41 header.Nonce, header.MixDigest = types.BlockNonce{}, common.Hash{} 42 return block.WithSeal(header), nil 43 } 44 // If we're running a shared PoW, delegate sealing to it 45 // 共享模式,转到它的共享对象执行Seal操作 46 if ethash.shared != nil { 47 return ethash.shared.Seal(chain, block, stop) 48 } 49 // Create a runner and the multiple search threads it directs 50 // 创建runner和它指挥的多重搜索线程 51 abort := make(chan struct{}) 52 found := make(chan *types.Block) 53 54 // 线程锁 55 ethash.lock.Lock() 56 // 获取挖矿线程 57 threads := ethash.threads 58 if ethash.rand == nil { 59 // 获取种子seed 60 seed, err := crand.Int(crand.Reader, big.NewInt(math.MaxInt64)) 61 if err != nil { 62 ethash.lock.Unlock() 63 return nil, err 64 } 65 // 执行成功,拿到合法种子seed,通过其获得rand对象,赋值 66 ethash.rand = rand.New(rand.NewSource(seed.Int64())) 67 } 68 ethash.lock.Unlock() 69 if threads == 0 { 70 // 如果设定的线程数为0,则实际线程数同CPU数 71 threads = runtime.NumCPU() 72 } 73 if threads < 0 { 74 // 允许在本地/远程周围禁用本地挖掘而无需额外的逻辑 75 threads = 0 // Allows disabling local mining without extra logic around local/remote 76 } 77 78 // 创建一个计数的信号量 79 var pend sync.WaitGroup 80 for i := 0; i < threads; i++ { 81 //信号量赋值 82 pend.Add(1) 83 go func(id int, nonce uint64) { 84 // 信号量值减1 85 defer pend.Done() 86 // 挖矿工作 87 ethash.mine(block, id, nonce, abort, found) 88 }(i, uint64(ethash.rand.Int63())) 89 } 90 // Wait until sealing is terminated or a nonce is found 91 // 一直等到找到符合条件的nonce值 92 var result *types.Block 93 select { 94 case <-stop: 95 // Outside abort, stop all miner threads 96 // 停止信号 97 close(abort) 98 case result = <-found: 99 // One of the threads found a block, abort all others 100 // 其中有线程找到了合法区块 101 close(abort) 102 case <-ethash.update: 103 // Thread count was changed on user request, restart 104 // 重启信号 105 close(abort) 106 pend.Wait() 107 return ethash.Seal(chain, block, stop) 108 } 109 // Wait for all miners to terminate and return the block 110 // 等待所有矿工终止并返回该区块 111 // Wait判断信号量计数器大于0,就会阻塞 112 pend.Wait() 113 return result, nil 114 } 115 116 // mine is the actual proof-of-work miner that searches for a nonce starting from 117 // seed that results in correct final block difficulty. 118 // 实际的POW,从种子开始搜索一个nonce,直到正确的合法区块出现 119 func (ethash *Ethash) mine(block *types.Block, id int, seed uint64, abort chan struct{}, found chan *types.Block) { 120 // Extract some data from the header 121 // 从区块头中取出一些数据 122 var ( 123 header = block.Header() 124 hash = header.HashNoNonce().Bytes() 125 // 难度目标值 126 target = new(big.Int).Div(maxUint256, header.Difficulty) 127 number = header.Number.Uint64() 128 dataset = ethash.dataset(number) 129 ) 130 // Start generating random nonces until we abort or find a good one 131 // 开始生成随机的随机数,直到我们中止或找到一个合法的 132 var ( 133 // 初始化一个变量来表示尝试次数 134 attempts = int64(0) 135 // 初始化nonce值,后面该值会递增 136 nonce = seed 137 ) 138 logger := log.New("miner", id) 139 logger.Trace("Started ethash search for new nonces", "seed", seed) 140 search: 141 for { 142 select { 143 case <-abort: 144 // Mining terminated, update stats and abort 145 // 停止信号 146 logger.Trace("Ethash nonce search aborted", "attempts", nonce-seed) 147 ethash.hashrate.Mark(attempts) 148 break search 149 150 default: 151 // We don't have to update hash rate on every nonce, so update after after 2^X nonces 152 // 不必更新每个nonce的哈希率,所以在2 ^ X nonces之后更新 153 attempts++ 154 if (attempts % (1 << 15)) == 0 { 155 // 尝试次数达到2^15,更新hashrate 156 ethash.hashrate.Mark(attempts) 157 attempts = 0 158 } 159 // Compute the PoW value of this nonce 160 // 计算当前nonce的pow值 161 digest, result := hashimotoFull(dataset.dataset, hash, nonce) 162 if new(big.Int).SetBytes(result).Cmp(target) <= 0 { 163 // Correct nonce found, create a new header with it 164 // 找到合法的nonce值,为header赋值 165 header = types.CopyHeader(header) 166 header.Nonce = types.EncodeNonce(nonce) 167 header.MixDigest = common.BytesToHash(digest) 168 169 // Seal and return a block (if still needed) 170 select { 171 case found <- block.WithSeal(header): 172 logger.Trace("Ethash nonce found and reported", "attempts", nonce-seed, "nonce", nonce) 173 case <-abort: 174 logger.Trace("Ethash nonce found but discarded", "attempts", nonce-seed, "nonce", nonce) 175 } 176 break search 177 } 178 nonce++ 179 } 180 } 181 // Datasets are unmapped in a finalizer. Ensure that the dataset stays live 182 // during sealing so it's not unmapped while being read. 183 runtime.KeepAlive(dataset) 184 }