Section1.2 engine
geth启动后, 经过一系列过程, 在cmd/utils/flags.go中会通过func RegisterEthService(stack *node.Node, cfg *eth.Config)调用eth.New()生成type Ethereum struct实例, 其中包含了关于协议的各种信息, 包括consensus, miner, blockchain等.
// Ethereum implements the Ethereum full node service.
type Ethereum struct {
chainConfig *params.ChainConfig
// Channel for shutting down the service
shutdownChan chan bool // Channel for shutting down the ethereum
stopDbUpgrade func() // stop chain db sequential key upgrade
// Handlers
txPool *core.TxPool
txMu sync.Mutex
blockchain *core.BlockChain
protocolManager *ProtocolManager
lesServer LesServer
// DB interfaces
chainDb ethdb.Database // Block chain database
eventMux *event.TypeMux
engine consensus.Engine
accountManager *accounts.Manager
ApiBackend *EthApiBackend
miner *miner.Miner
gasPrice *big.Int
etherbase common.Address
networkId uint64
netRPCService *ethapi.PublicNetAPI
lock sync.RWMutex // Protects the variadic fields (e.g. gas price and etherbase)
}其中engine储存了consensus.Engine实例, 在New()中由CreateConsensusEngine(ctx, config, chainConfig, chainDb)生成.
在New()接下来的部分, 有以下命令与engine相关.
blockchain
在core/blockchain.go描述了blockchain. BlockChain结构体定义如下
注意到, 里面包含
这些是与共识机制相关的. BlockChain由func NewBlockChain(chainDb ethdb.Database, config *params.ChainConfig, engine consensus.Engine, mux *event.TypeMux, vmConfig vm.Config) (*BlockChain, error)生成. 在内部, 除了将从eth获得的engine保存到自己的结构体内, 还通过调用
定义了processor和validator.
func NewBlockValidator()在core/block_validator.go中定义. 在后面的写块等处, 使用了形如bc.Validator().ValidateBody(block)的方式来验证块的合法性, BlockValidator使用了consensus.VerifyUncles().
NewStateProcessor()在core/state_processor.go中定义, StateProcessor在func Process()中使用了func consensus.Finalize().
processor在func (bc *BlockChain) InsertChain(chain types.Blocks) (int, error)处有调用(BlockChain内部只有这一处调用),
用来根据待插入的块来更新状态.
protocolManager
protocolManager仅使用engine生成validator, 使用了接口的func VerifyHeader().
validator进一步生成fetcher, fetcher是protocolManager的成员变量.
fetcher是用来从获取块的
Fetcher is responsible for accumulating block announcements from various peers and scheduling them for retrieval.
使用engine来验证头部.
miner
miner内部对engine判断, 若为PoW则可以获取HashRate, 该接口也是在consensus.go里定义. miner用engine生成worker. 除此miner本身对engine没有别的使用.
在worker中, 有两处使用engine, 分别为
分别来准备新块的头部和验证块.
Last updated
Was this helpful?