之所以把这部分提前到这里来,也是想对比分析一下和比特币以及EOS的DPOS有什么不同。其实主要是前者,毕竟DPOS是不需要挖矿这个过程的。即使后来改成BFT-DPOS,也是只增加一个超级节点的分布式判定。
比特币的POW使用的是块头哈希,算最小值,以太坊与其原理基本一样,不同的是,以太坊不再使用CPU算力,改用了DAG有向无环图。所以自成体系的来了一个ethash.一个个的分析,不要乱。
一、挖矿
先看一下代码的分布,在miner路径下,有agent.go,miner.go,remote_agent.go,uncomfirmed.go,worker.go.
其中agent.go,remote_agent.go是真正挖矿的,miner.go是整个挖矿的接口,负责管理worker和各种外部消息的收发,余下两个一个是启动本地代理挖矿一个是启动远程的代理挖矿。worker.go负责分发调度任务,包括上面提到的两类agent,同时还负责构建区块和对象。最后一个uncomfirmed.go主要是处理中间状态,即从挖出块到块真正上链前的各种情况。
从头到开始:(miner.go)
前面的源码可以看到在makeFullNode—RegisterEthService—New(eth/backend.go)--- miner.New:
func New(eth Backend, config *params.ChainConfig, mux *event.TypeMux, engine consensus.Engine) *Miner {
miner := &Miner{
eth: eth,
mux: mux,
engine: engine,
worker: newWorker(config, engine, common.Address{}, eth, mux),//调用WORKER
canStart: 1,
}
//生成一个新的CPUAGENT
miner.Register(NewCpuAgent(eth.BlockChain(), engine))
go miner.update() //启动update协程,只操作一次,具体看下面分析
return miner
}
这里会生成一个Miner的挖矿的对象:
// Backend wraps all methods required for mining.
type Backend interface {
AccountManager() *accounts.Manager
BlockChain() *core.BlockChain
TxPool() *core.TxPool
ChainDb() ethdb.Database
}
// Miner creates blocks and searches for proof-of-work values.
type Miner struct {
mux *event.TypeMux //落后了,准备在新版本换掉
worker *worker //提到的控制分发的Workers
coinbase common.Address //创币交易地址
mining int32
eth Backend
engine consensus.Engine //共识引擎
//控制挖矿的启动
canStart int32 // can start indicates whether we can start the mining operation
shouldStart int32 // should start indicates whether we should start after sync
}
下面是注释中提到的update函数:
// update keeps track of the downloader events. Please be aware that this is a one shot type of update loop.
// It's entered once and as soon as `Done` or `Failed` has been broadcasted the events are unregistered and
// the loop is exited. This to prevent a major security vuln where external parties can DOS you with blocks
// and halt your mining operation for as long as the DOS continues.
func (self *Miner) update() {
events := self.mux.Subscribe(downloader.StartEvent{}, downloader.DoneEvent{}, downloader.FailedEvent{})
out:
for ev := range events.Chan() {
switch ev.Data.(type) {
case downloader.StartEvent:
atomic.StoreInt32(&self.canStart, 0)
if self.Mining() {
self.Stop()
atomic.StoreInt32(&self.shouldStart, 1)
log.Info("Mining aborted due to sync")
}
case downloader.DoneEvent, downloader.FailedEvent:
shouldStart := atomic.LoadInt32(&self.shouldStart) == 1
atomic.StoreInt32(&self.canStart, 1)
atomic.StoreInt32(&self.shouldStart, 0)
if shouldStart {
self.Start(self.coinbase)
}
// unsubscribe. we're only interested in this event once
events.Unsubscribe() //只操作一次,然后取消
// stop immediately and ignore all further pending events
break out
}
}
}
注释中说得很清楚,其Subscribe了下载事件,它只处理一次,原因是为了防止黑客进行DOS攻击。之所以不允许在下载块的时候儿挖矿,是为了防止挖矿成功后的块无法连接到最新的链尾,导致无用功。
开始启动挖矿,在使用geth命令中,有miner.Start,它最终会调用:
func (self *Miner) Start(coinbase common.Address) {
atomic.StoreInt32(&self.shouldStart, 1)//设置是否允许启动
self.worker.setEtherbase(coinbase)
self.coinbase = coinbase
if atomic.LoadInt32(&self.canStart) == 0 {
log.Info("Network syncing, will start miner afterwards")
return
}
atomic.StoreInt32(&self.mining, 1)
log.Info("Starting mining operation")
self.worker.start() //启动挖矿
//提交挖矿任务即再次启动新的挖矿,前面的miner调用有一小段时间等待
//这样就形成miner启动挖矿到这里再次挖矿,不断重复的过程
self.worker.commitNewWork()
}
这时候儿就进入了worker的管理,即worker.go文件中:
// Agent can register themself with the worker
type Agent interface {
Work() chan<- *Work
SetReturnCh(chan<- *Result)
Stop()
Start()
GetHashRate() int64
}
注释说得明白,Agent可以注册到他们自己的worker中去。这个接口中也没有什么特殊的东西。然后看一下另外与work有关的数据结构:
// Work is the workers current environment and holds
// all of the current state information
type Work struct {
config *params.ChainConfig
signer types.Signer
state *state.StateDB // apply state changes here状态数据库
ancestors *set.Set // ancestor set (used for checking uncle parent validity)祖先集合
family *set.Set // family set (used for checking uncle invalidity)家庭集合
uncles *set.Set // uncle set 叔块集合
tcount int // tx count in cycle 交易周期内的数量
Block *types.Block // the new block
header *types.Header
txs []*types.Transaction
receipts []*types.Receipt
createdAt time.Time
}
工作者工作时的工作区的环境,这里把这个直接叫作工作区,更容易理解。它主要提供了工作者在工作时需要的外部变量和状态。
下面的是工作者的自己持有的数据相关控制动作。
// worker is the main object which takes care of applying messages to the new state
type worker struct {
config *params.ChainConfig
engine consensus.Engine
mu sync.Mutex
// update loop
mux *event.TypeMux
txCh chan core.TxPreEvent //接收txPool中tx的通道
txSub event.Subscription
chainHeadCh chan core.ChainHeadEvent //接收区块头的通信
chainHeadSub event.Subscription
chainSideCh chan core.ChainSideEvent //接收主备链变更通道
chainSideSub event.Subscription
wg sync.WaitGroup
agents map[Agent]struct{} //Agent的全部映射
recv chan *Result //agent结果发送通道
eth Backend
chain *core.BlockChain
proc core.Validator
chainDb ethdb.Database //存储数据库
coinbase common.Address //创币地址即挖矿者本身设置的地址
extra []byte
currentMu sync.Mutex
current *Work
uncleMu sync.Mutex
possibleUncles map[common.Hash]*types.Block
unconfirmed *unconfirmedBlocks // set of locally mined blocks pending canonicalness confirmations
// atomic status counters
mining int32
atWork int32
}
看一下在前面调用的生成方法:
func newWorker(config *params.ChainConfig, engine consensus.Engine, coinbase common.Address, eth Backend, mux *event.TypeMux) *worker {
worker := &worker{
config: config,
engine: engine,
eth: eth,
mux: mux,
txCh: make(chan core.TxPreEvent, txChanSize),
chainHeadCh: make(chan core.ChainHeadEvent, chainHeadChanSize),
chainSideCh: make(chan core.ChainSideEvent, chainSideChanSize),
chainDb: eth.ChainDb(),
recv: make(chan *Result, resultQueueSize),
chain: eth.BlockChain(),
proc: eth.BlockChain().Validator(),
possibleUncles: make(map[common.Hash]*types.Block),
coinbase: coinbase,
agents: make(map[Agent]struct{}),
unconfirmed: newUnconfirmedBlocks(eth.BlockChain(), miningLogAtDepth),
}
// Subscribe TxPreEvent for tx pool
worker.txSub = eth.TxPool().SubscribeTxPreEvent(worker.txCh)
// Subscribe events for blockchain
worker.chainHeadSub = eth.BlockChain().SubscribeChainHeadEvent(worker.chainHeadCh)
worker.chainSideSub = eth.BlockChain().SubscribeChainSideEvent(worker.chainSideCh)
go worker.update() //有一个类似于miner的update
go worker.wait()
worker.commitNewWork()
return worker
}
看一下update:
func (self *worker) update() {
defer self.txSub.Unsubscribe()
defer self.chainHeadSub.Unsubscribe()
defer self.chainSideSub.Unsubscribe()
for {
// A real event arrived, process interesting content
select {
// Handle ChainHeadEvent
case <-self.chainHeadCh:
self.commitNewWork() //开始挖矿
// Handle ChainSideEvent
case ev := <-self.chainSideCh:
self.uncleMu.Lock()
self.possibleUncles[ev.Block.Hash()] = ev.Block
self.uncleMu.Unlock()
// Handle TxPreEvent
case ev := <-self.txCh:
// Apply transaction to the pending state if we're not mining
if atomic.LoadInt32(&self.mining) == 0 {
self.currentMu.Lock()
acc, _ := types.Sender(self.current.signer, ev.Tx)
txs := map[common.Address]types.Transactions{acc: {ev.Tx}}
txset := types.NewTransactionsByPriceAndNonce(self.current.signer, txs)
self.current.commitTransactions(self.mux, txset, self.chain, self.coinbase)
self.currentMu.Unlock()
} else {
// If we're mining, but nothing is being processed, wake on new transactions
if self.config.Clique != nil && self.config.Clique.Period == 0 {
self.commitNewWork()
}
}
// System stopped
case <-self.txSub.Err():
return
case <-self.chainHeadSub.Err():
return
case <-self.chainSideSub.Err():
return
}
}
}
也没啥,注释还是比较清楚,当接收到一个区块头信息的时候儿,启动挖矿,当接收到主备链变化变化事件时,将区块放到叔块里。当接收到交易处理时,如果还没有挖矿则将其放到当前的映射中,准备在挖矿时将其打包到块上。类似于比特币的挖矿模块中的交易处理。
开始挖矿:
func (self *worker) commitNewWork() {
……
//时间判断,下面注释说明时间不能超过现在太远,否则休息等待。怀疑可能是为了防//止分叉
tstamp := tstart.Unix()
if parent.Time().Cmp(new(big.Int).SetInt64(tstamp)) >= 0 {
tstamp = parent.Time().Int64() + 1
}
// this will ensure we're not going off too far in the future
if now := time.Now().Unix(); tstamp > now+1 {
wait := time.Duration(tstamp-now) * time.Second
log.Info("Mining too far in the future", "wait", common.PrettyDuration(wait))
time.Sleep(wait)
}
num := parent.Number()
header := &types.Header{
ParentHash: parent.Hash(),
Number: num.Add(num, common.Big1),
GasLimit: core.CalcGasLimit(parent),
Extra: self.extra,
Time: big.NewInt(tstamp),
}
// Only set the coinbase if we are mining (avoid spurious block rewards)
//只有挖矿才有奖励,所以设置创币交易
if atomic.LoadInt32(&self.mining) == 1 {
header.Coinbase = self.coinbase
}
//初始化共识引擎
if err := self.engine.Prepare(self.chain, header); err != nil {
log.Error("Failed to prepare header for mining", "err", err)
return
}
// If we are care about TheDAO hard-fork check whether to override the extra-data or not
//处理DAP硬分叉,历史有名的攻击,可以在网上查查
if daoBlock := self.config.DAOForkBlock; daoBlock != nil {
// Check whether the block is among the fork extra-override range
limit := new(big.Int).Add(daoBlock, params.DAOForkExtraRange)
if header.Number.Cmp(daoBlock) >= 0 && header.Number.Cmp(limit) < 0 {
// Depending whether we support or oppose the fork, override differently
if self.config.DAOForkSupport {
header.Extra = common.CopyBytes(params.DAOForkBlockExtra)
} else if bytes.Equal(header.Extra, params.DAOForkBlockExtra) {
header.Extra = []byte{} // If miner opposes, don't let it use the reserved extra-data
}
}
}
// Could potentially happen if starting to mine in an odd state.
err := self.makeCurrent(parent, header) //设置新状态
if err != nil {
log.Error("Failed to create mining context", "err", err)
return
}
// Create the current work task and check any fork transitions needed
work := self.current
if self.config.DAOForkSupport && self.config.DAOForkBlock != nil && self.config.DAOForkBlock.Cmp(header.Number) == 0 {
misc.ApplyDAOHardFork(work.state) //将硬分叉后的资金转称到新户头
}
pending, err := self.eth.TxPool().Pending()
if err != nil {
log.Error("Failed to fetch pending transactions", "err", err)
return
}
//处理结果,其实就是将结果打到包里创建并提交交易
//TransactionsByPriceAndNonce这个结构中包含一个heads字段,把交易按照gas price
//进行排序
txs := types.NewTransactionsByPriceAndNonce(self.current.signer, pending)
work.commitTransactions(self.mux, txs, self.chain, self.coinbase)
// compute uncles for the new block.
//创建叔块的空间
var (
uncles []*types.Header
badUncles []common.Hash
)
for hash, uncle := range self.possibleUncles {
if len(uncles) == 2 {
break
}
if err := self.commitUncle(work, uncle.Header()); err != nil {
log.Trace("Bad uncle found and will be removed", "hash", hash)
log.Trace(fmt.Sprint(uncle))
badUncles = append(badUncles, hash)
} else {
log.Debug("Committing new uncle to block", "hash", hash)
uncles = append(uncles, uncle.Header())
}
}
for _, hash := range badUncles {
delete(self.possibleUncles, hash)
}
// Create the new block to seal with the consensus engine
//开始挖矿,或者说向挖矿提供标准的数据模板
if work.Block, err = self.engine.Finalize(self.chain, header, work.state, work.txs, uncles, work.receipts); err != nil {
log.Error("Failed to finalize block for sealing", "err", err)
return
}
// We only care about logging if we're actually mining.
if atomic.LoadInt32(&self.mining) == 1 {
log.Info("Commit new mining work", "number", work.Block.Number(), "txs", work.tcount, "uncles", len(uncles), "elapsed", common.PrettyDuration(time.Since(tstart)))
self.unconfirmed.Shift(work.Block.NumberU64() - 1)
}
self.push(work) //启动Agent挖矿
}
先看一下makeCurrent:
// makeCurrent creates a new environment for the current cycle.
func (self *worker) makeCurrent(parent *types.Block, header *types.Header) error {
state, err := self.chain.StateAt(parent.Root())
if err != nil {
return err
}
work := &Work{
config: self.config,
signer: types.NewEIP155Signer(self.config.ChainId),
state: state,
ancestors: set.New(),
family: set.New(),
uncles: set.New(),
header: header,
createdAt: time.Now(),
}
// when 08 is processed ancestors contain 07 (quick block)
for _, ancestor := range self.chain.GetBlocksFromHash(parent.Hash(), 7) {
for _, uncle := range ancestor.Uncles() {
work.family.Add(uncle.Hash())
}
work.family.Add(ancestor.Hash())
work.ancestors.Add(ancestor.Hash())
}
// Keep track of transactions which return errors so they can be removed
work.tcount = 0
self.current = work
return nil
}
这个没啥,就是创建自己块的环境,类似于一个人,他的祖先,叔伯,家族,头等。也就是前面提到工作环境,这里给定了出来。
然后就是提交交易:
func (env *Work) commitTransactions(mux *event.TypeMux, txs *types.TransactionsByPriceAndNonce, bc *core.BlockChain, coinbase common.Address) {
gp := new(core.GasPool).AddGas(env.header.GasLimit)
var coalescedLogs []*types.Log
for {
// If we don't have enough gas for any further transactions then we're done
//以太坊就是个钱串子,到处要钱,不但要钱,有的时候儿要了钱,不够还不干活也//不退钱
if gp.Gas() < params.TxGas {
log.Trace("Not enough gas for further transactions", "gp", gp)
break
}
// Retrieve the next transaction and abort if all done
tx := txs.Peek()
if tx == nil {
break
}
// Error may be ignored here. The error has already been checked
// during transaction acceptance is the transaction pool.
//又涉及到硬分叉了,DAO攻击影响非常大,所以出来一个EIP155,防止分叉后的//重放攻击
// We use the eip155 signer regardless of the current hf.
from, _ := types.Sender(env.signer, tx)
// Check whether the tx is replay protected. If we're not in the EIP155 hf
// phase, start ignoring the sender until we do.
if tx.Protected() && !env.config.IsEIP155(env.header.Number) {
log.Trace("Ignoring reply protected transaction", "hash", tx.Hash(), "eip155", env.config.EIP155Block)
txs.Pop()
continue
}
// Start executing the transaction
env.state.Prepare(tx.Hash(), common.Hash{}, env.tcount)
//提交交易
err, logs := env.commitTransaction(tx, bc, coinbase, gp)
switch err {
case core.ErrGasLimitReached:
// Pop the current out-of-gas transaction without shifting in the next from the account
log.Trace("Gas limit exceeded for current block", "sender", from)
txs.Pop()
case core.ErrNonceTooLow:
// New head notification data race between the transaction pool and miner, shift
log.Trace("Skipping transaction with low nonce", "sender", from, "nonce", tx.Nonce())
txs.Shift()
case core.ErrNonceTooHigh:
// Reorg notification data race between the transaction pool and miner, skip account =
log.Trace("Skipping account with hight nonce", "sender", from, "nonce", tx.Nonce())
txs.Pop()
case nil:
// Everything ok, collect the logs and shift in the next transaction from the same account
coalescedLogs = append(coalescedLogs, logs...)
env.tcount++
txs.Shift()
default:
// Strange error, discard the transaction and get the next in line (note, the
// nonce-too-high clause will prevent us from executing in vain).
log.Debug("Transaction failed, account skipped", "hash", tx.Hash(), "err", err)
txs.Shift()
}
}
if len(coalescedLogs) > 0 || env.tcount > 0 {
// make a copy, the state caches the logs and these logs get "upgraded" from pending to mined
// logs by filling in the block hash when the block was mined by the local miner. This can
// cause a race condition if a log was "upgraded" before the PendingLogsEvent is processed.
cpy := make([]*types.Log, len(coalescedLogs))
for i, l := range coalescedLogs {
cpy[i] = new(types.Log)
*cpy[i] = *l
}
go func(logs []*types.Log, tcount int) {
if len(logs) > 0 {
mux.Post(core.PendingLogsEvent{Logs: logs})
}
if tcount > 0 {
mux.Post(core.PendingStateEvent{})
}
}(cpy, env.tcount)
}
}
随机值太高和太低,都代表这些交易是异常的。注意,在第一个GAS判断中,再次证明了以太坊是个钱串子。
func (env *Work) commitTransaction(tx *types.Transaction, bc *core.BlockChain, coinbase common.Address, gp *core.GasPool) (error, []*types.Log) {
snap := env.state.Snapshot()
receipt, _, err := core.ApplyTransaction(env.config, bc, &coinbase, gp, env.state, env.header, tx, &env.header.GasUsed, vm.Config{})
if err != nil {
env.state.RevertToSnapshot(snap)
return err, nil
}
env.txs = append(env.txs, tx)
env.receipts = append(env.receipts, receipt)
return nil, receipt.Logs
}
// ApplyTransaction attempts to apply a transaction to the given state database
// and uses the input parameters for its environment. It returns the receipt
// for the transaction, gas used and an error if the transaction failed,
// indicating the block was invalid.
func ApplyTransaction(config *params.ChainConfig, bc *BlockChain, author *common.Address, gp *GasPool, statedb *state.StateDB, header *types.Header, tx *types.Transaction, usedGas *uint64, cfg vm.Config) (*types.Receipt, uint64, error) {
msg, err := tx.AsMessage(types.MakeSigner(config, header.Number))
if err != nil {
return nil, 0, err
}
// Create a new context to be used in the EVM environment
context := NewEVMContext(msg, header, bc, author)
// Create a new environment which holds all relevant information
// about the transaction and calling mechanisms.
vmenv := vm.NewEVM(context, statedb, config, cfg)
// Apply the transaction to the current state (included in the env)
_, gas, failed, err := ApplyMessage(vmenv, msg, gp)
if err != nil {
return nil, 0, err
}
// Update the state with pending changes
var root []byte
if config.IsByzantium(header.Number) {
statedb.Finalise(true)
} else {
//生成MPT树,回头专门分析一下
root = statedb.IntermediateRoot(config.IsEIP158(header.Number)).Bytes()
}
*usedGas += gas
// Create a new receipt for the transaction, storing the intermediate root and gas used by the tx
// based on the eip phase, we're passing wether the root touch-delete accounts.
receipt := types.NewReceipt(root, failed, *usedGas)
receipt.TxHash = tx.Hash()
receipt.GasUsed = gas
// if the transaction created a contract, store the creation address in the receipt.
if msg.To() == nil {
receipt.ContractAddress = crypto.CreateAddress(vmenv.Context.Origin, tx.Nonce())
}
// Set the receipt logs and create a bloom for filtering
receipt.Logs = statedb.GetLogs(tx.Hash())
receipt.Bloom = types.CreateBloom(types.Receipts{receipt})
return receipt, gas, err
}
最后将实际的任务分发给应的work,并在其中启动实际挖矿的代码:
// push sends a new work task to currently live miner agents.
func (self *worker) push(work *Work) {
if atomic.LoadInt32(&self.mining) != 1 {
return
}
for agent := range self.agents {
atomic.AddInt32(&self.atWork, 1)
if ch := agent.Work(); ch != nil {
ch <- work
}
}
}
这里回头看一下上面创建worker提到的等待时间函数wait:
func (self *worker) wait() {
for {
mustCommitNewWork := true
for result := range self.recv {
atomic.AddInt32(&self.atWork, -1)
if result == nil {
continue
}
block := result.Block
work := result.Work
// Update the block hash in all logs since it is now available and not when the
// receipt/log of individual transactions were created.
//记录智能合约的事件event日志,重点是更新一下HASH值。
for _, r := range work.receipts {
for _, l := range r.Logs {
l.BlockHash = block.Hash()
}
}
for _, log := range work.state.Logs() {
log.BlockHash = block.Hash()
}
//更新主链的状态进入数据库
stat, err := self.chain.WriteBlockWithState(block, work.receipts, work.state)
if err != nil {
log.Error("Failed writing block to chain", "err", err)
continue
}
// check if canon block and write transactions已经在主链上
if stat == core.CanonStatTy {
// implicit by posting ChainHeadEvent
//显示发送ChainHeadEvent,触发commitNewWork,这里不再直接调用
mustCommitNewWork = false
}
// Broadcast the block and announce chain insertion event
//广播区块
self.mux.Post(core.NewMinedBlockEvent{Block: block})
var (
events []interface{}
logs = work.state.Logs()
)
events = append(events, core.ChainEvent{Block: block, Hash: block.Hash(), Logs: logs})
if stat == core.CanonStatTy {
events = append(events, core.ChainHeadEvent{Block: block})
}
self.chain.PostChainEvents(events, logs) //发送上链事件
// Insert the block into the set of pending ones to wait for confirmations
self.unconfirmed.Insert(block.NumberU64(), block.Hash())
//如果非主链上则提交新的work
if mustCommitNewWork {
self.commitNewWork()
}
}
}
}
走了这么久,终于到了真正搞事情的地方,挖矿。前面说过,挖矿是通过代理来实现的,一个本地,一个远程。其实远程就是为了矿机而生。
不知道还记不记得前面讲矿工代码时miner.go中的Start调用worker.start里面有:
// spin up agents
for agent := range self.agents {
agent.Start()
}
还记不记得NewCpuAgent。CpuAgent继承了前面提到的Agent这个接口。其实和比特币类似,不过是使用随机数nonnce的不断变化来计算最小的哈希值,然后如果成功返回相关的结果。
不过目前都使用专门矿机了,CPU挖矿得不偿失,不过用它来说明挖矿过程比用GPU矿机说得清楚。
Agent.go的代码不多:
type CpuAgent struct {
mu sync.Mutex
workCh chan *Work 挖矿任务通道
stop chan struct{}
quitCurrentOp chan struct{}
returnCh chan<- *Result 挖矿成功返回通道
chain consensus.ChainReader 获取区块信息
engine consensus.Engine 共识引擎
isMining int32 // isMining indicates whether the agent is currently mining
}
func NewCpuAgent(chain consensus.ChainReader, engine consensus.Engine) *CpuAgent {
miner := &CpuAgent{
chain: chain,
engine: engine,
stop: make(chan struct{}, 1),
workCh: make(chan *Work, 1),
}
return miner
}
func (self *CpuAgent) Work() chan<- *Work { return self.workCh }
func (self *CpuAgent) SetReturnCh(ch chan<- *Result) { self.returnCh = ch }
func (self *CpuAgent) Stop() {
if !atomic.CompareAndSwapInt32(&self.isMining, 1, 0) {
return // agent already stopped
}
self.stop <- struct{}{}
done:
// Empty work channel
for {
select {
case <-self.workCh:
default:
break done
}
}
}
func (self *CpuAgent) Start() {
if !atomic.CompareAndSwapInt32(&self.isMining, 0, 1) {
return // agent already started
}
go self.update()
}
func (self *CpuAgent) update() {
out:
for {
select {
case work := <-self.workCh:
self.mu.Lock()
if self.quitCurrentOp != nil {
close(self.quitCurrentOp)
}
self.quitCurrentOp = make(chan struct{})
//专心挖矿,看下面的函数
go self.mine(work, self.quitCurrentOp)
self.mu.Unlock()
case <-self.stop:
self.mu.Lock()
if self.quitCurrentOp != nil {
close(self.quitCurrentOp)
self.quitCurrentOp = nil
}
self.mu.Unlock()
break out
}
}
}
//挖矿的主角
func (self *CpuAgent) mine(work *Work, stop <-chan struct{}) {
if result, err := self.engine.Seal(self.chain, work.Block, stop); result != nil {
log.Info("Successfully sealed new block", "number", result.Number(), "hash", result.Hash())
self.returnCh <- &Result{work, result}
} else {
if err != nil {
log.Warn("Block sealing failed", "err", err)
}
self.returnCh <- nil
}
}
func (self *CpuAgent) GetHashRate() int64 {
if pow, ok := self.engine.(consensus.PoW); ok {
return int64(pow.Hashrate())
}
return 0
}
Start的代码其实就是判断是不是在挖矿,没有就起来。Update中的代码类似,如果启动成功就开始从挖矿通道接收挖矿任务,否则退出。
RemoteAgent这里就不赘述,基本和比特币差不多,循环获取模板,然后开始挖矿。只不过多几个获取任务和处理任务的步骤。
这挖矿的过程中就需要unconfirmed.go中的各种状态控制了:
比如在提交commitNewWork中(worker.go)一用到了shift。在前面提到处理wiat时用到了insert.
Insert就是把新块插入到当前的链的最后
// Insert adds a new block to the set of unconfirmed ones.
func (set *unconfirmedBlocks) Insert(index uint64, hash common.Hash) {
// If a new block was mined locally, shift out any old enough blocks
set.Shift(index) //移除老的块
// Create the new item as its own ring
item := ring.New(1)
item.Value = &unconfirmedBlock{
index: index,
hash: hash,
}
// Set as the initial ring or append to the end
set.lock.Lock()
defer set.lock.Unlock()
if set.blocks == nil {
set.blocks = item
} else {
set.blocks.Move(-1).Link(item)
}
// Display a log for the user to notify ofa new mined block unconfirmed
log.Info("mined potentialblock", "number", index, "hash", hash)
}
// Shift drops all unconfirmed blocks fromthe set which exceed the unconfirmed sets depth
// allowance, checking them against thecanonical chain for inclusion or staleness
// report.
func (set *unconfirmedBlocks) Shift(heightuint64) {
set.lock.Lock()
deferset.lock.Unlock()
forset.blocks != nil {
//Retrieve the next unconfirmed block and abort if too fresh
next:= set.blocks.Value.(*unconfirmedBlock)
ifnext.index+uint64(set.depth) > height {
break
}
//Block seems to exceed depth allowance, check for canonical status
//判断区块是否合规,否则移除
header:= set.chain.GetHeaderByNumber(next.index)
switch{
caseheader == nil:
log.Warn("Failedto retrieve header of mined block", "number", next.index,"hash", next.hash)
caseheader.Hash() == next.hash:
log.Info("block reachedcanonical chain", "number", next.index, "hash",next.hash)
default:
log.Info("⑂ block became a sidefork", "number", next.index, "hash", next.hash)
}
//Drop the block out of the ring
ifset.blocks.Value == set.blocks.Next().Value {
set.blocks= nil
}else {
set.blocks= set.blocks.Move(-1)
set.blocks.Unlink(1)
set.blocks= set.blocks.Move(1)
}
}
}
判断是在主链还是在备用链上。然后做个体的块的处理。其实就是一个判断高度的问题,如果超过指定的高度,那么区块就正式的挂到区块链上了。
当这一切都处理完成,一个初步的挖矿流程就具备了,具体到挖矿的POW和生产新块和计算费用等放到下一篇里分析,这篇太大了。