以太坊源码分析(三):以太坊服务的初始化流程

栏目: 编程工具 · 发布时间: 7年前

内容简介:本章节介绍以太坊服务的模块的初始化流程,以太坊服务模块Ethereum中包含了以太坊的核心模块,BlockChain、ProtocolManager、Mananger、Miner等,Ethereum模块本身作为一个服务被注册到了上一节中提到的Node模块中,Node模块初始化时会调用Ethereum模块初始化函数New函数,本章节主要分析New函数的流程。Ethereum模块定义在eth/backend.go中, Ethereum在backend.go的62行。

原文链接: 以太坊源码分析(三):以太坊服务的初始化流程

一、 前言

本章节介绍以太坊服务的模块的初始化流程,以太坊服务模块Ethereum中包含了以太坊的核心模块,BlockChain、ProtocolManager、Mananger、Miner等,Ethereum模块本身作为一个服务被注册到了上一节中提到的Node模块中,Node模块初始化时会调用Ethereum模块初始化函数New函数,本章节主要分析New函数的流程。

二、Ethereum数据结构

Ethereum模块定义在eth/backend.go中, Ethereum在backend.go的62行。

type Ethereum struct {
    //Ethereum的配置文件,包括用户可以命令行输入的配置或者一些默认配置
config      *Config  
    //区块链的相关配置,包括ChainID、分叉点相关的配置。 
chainConfig *params.ChainConfig
//服务关闭管道,Ethereum模块关闭时会通过这个管道通知其管理的子模块退出。
shutdownChan chan bool // Channel for shutting down the Ethereum
//交易池管理模块
txPool          *core.TxPool
 //以太坊区块链最核心的功能模块,区块链管理模块
blockchain      *core.BlockChain
//协议管理模块, 负责区块、交易的广播和接收、区块同步等。
protocolManager *ProtocolManager
//轻节点服务, ethereum是全节点服务,全节点服务中也可以包含轻节点服务
lesServer       LesServer
//区块存储的数据库接口
chainDb ethdb.Database // Block chain database
eventMux       *event.TypeMux
//一致性模块包好区块的pow和pow验证等
engine         consensus.Engine
//钱包管理器, 管理以太坊中的用户的钱包,主要管理用户私钥,另外还负责交易签名等
accountManager *accounts.Manager
bloomRequests chan chan *bloombits.Retrieval // Channel receiving bloom data retrieval requests
bloomIndexer  *core.ChainIndexer             // Bloom indexer operating during block imports
APIBackend *EthAPIBackend
//挖矿模块,用户在以太坊交互式命令行中输入miner.start(),会调用Miner模块的Start方法
miner     *miner.Miner
gasPrice  *big.Int
etherbase common.Address
networkID     uint64
//RPC服务
netRPCService *ethapi.PublicNetAPI
lock sync.RWMutex // Protects the variadic fields (e.g. gas price and etherbase)
}

从上面的数据结构可以看出,Ethereum这个模块包含的以太坊重要的模块,BlockChain、ProtocolManager、TxPool等等,在后面的文章我们会详细分析这些模块中重要的流程和方法。

三、New函数

func New(ctx *node.ServiceContext, config *Config) (*Ethereum, error) {
//1如果配置config中指定的同步模式是LightSync模块直接报错返回
if config.SyncMode == downloader.LightSync {
return nil, errors.New("can't run eth.Ethereum in light sync mode, use les.LightEthereum")
}
//2如果配置config中同步模式是无效的,则直接报错返回
if !config.SyncMode.IsValid() {
return nil, fmt.Errorf("invalid sync mode %d", config.SyncMode)
}
//3如果配置中MinerGasPrice为空或者值是负数,则使用默认值初始化MinerGasPrice,交易池不会接s收低于MinerGasPrice的交易
if config.MinerGasPrice == nil || config.MinerGasPrice.Cmp(common.Big0) <= 0 {
log.Warn("Sanitizing invalid miner gas price", "provided", config.MinerGasPrice, "updated", DefaultConfig.MinerGasPrice)
config.MinerGasPrice = new(big.Int).Set(DefaultConfig.MinerGasPrice)
}
//4创建区块存储数据库
chainDb, err := CreateDB(ctx, config, "chaindata")
if err != nil {
return nil, err
}
//5更新创世区块配置
chainConfig, genesisHash, genesisErr := core.SetupGenesisBlock(chainDb, config.Genesis)
if _, ok := genesisErr.(*params.ConfigCompatError); genesisErr != nil && !ok {
return nil, genesisErr
}
log.Info("Initialised chain configuration", "config", chainConfig)
//6初始化Ethereum对象
eth := &Ethereum{
config:         config,
chainDb:        chainDb,
chainConfig:    chainConfig,
eventMux:       ctx.EventMux,
accountManager: ctx.AccountManager,
engine:         CreateConsensusEngine(ctx, chainConfig, &config.Ethash, config.MinerNotify, config.MinerNoverify, chainDb),
shutdownChan:   make(chan bool),
networkID:      config.NetworkId,
gasPrice:       config.MinerGasPrice,
etherbase:      config.Etherbase,
bloomRequests:  make(chan chan *bloombits.Retrieval),
bloomIndexer:   NewBloomIndexer(chainDb, params.BloomBitsBlocks, params.BloomConfirms),
}

log.Info("Initialising Ethereum protocol", "versions", ProtocolVersions, "network", config.NetworkId)

if !config.SkipBcVersionCheck {
bcVersion := rawdb.ReadDatabaseVersion(chainDb)
if bcVersion != core.BlockChainVersion && bcVersion != 0 {
return nil, fmt.Errorf("Blockchain DB version mismatch (%d / %d).n", bcVersion, core.BlockChainVersion)
}
rawdb.WriteDatabaseVersion(chainDb, core.BlockChainVersion)
}
var (
vmConfig = vm.Config{
EnablePreimageRecording: config.EnablePreimageRecording,
EWASMInterpreter:        config.EWASMInterpreter,
EVMInterpreter:          config.EVMInterpreter,
}
cacheConfig = &core.CacheConfig{Disabled: config.NoPruning, TrieNodeLimit: config.TrieCache, TrieTimeLimit: config.TrieTimeout}
)
//7初始化BlockChain模块
eth.blockchain, err = core.NewBlockChain(chainDb, cacheConfig, eth.chainConfig, eth.engine, vmConfig, eth.shouldPreserve)
if err != nil {
return nil, err
}
// Rewind the chain in case of an incompatible config upgrade.
if compat, ok := genesisErr.(*params.ConfigCompatError); ok {
log.Warn("Rewinding chain to upgrade configuration", "err", compat)
eth.blockchain.SetHead(compat.RewindTo)
rawdb.WriteChainConfig(chainDb, genesisHash, chainConfig)
}
//布隆过滤器启动
eth.bloomIndexer.Start(eth.blockchain)

if config.TxPool.Journal != "" {
config.TxPool.Journal = ctx.ResolvePath(config.TxPool.Journal)
}
//8初始化BlockChain模块
eth.txPool = core.NewTxPool(config.TxPool, eth.chainConfig, eth.blockchain)

if eth.protocolManager, err = NewProtocolManager(eth.chainConfig, config.SyncMode, config.NetworkId, eth.eventMux, eth.txPool, eth.engine, eth.blockchain, chainDb); err != nil {
return nil, err
}
//9初始化BlockChain模块
eth.miner = miner.New(eth, eth.chainConfig, eth.EventMux(), eth.engine, config.MinerRecommit, config.MinerGasFloor, config.MinerGasCeil, eth.isLocalBlock)
//用配置中的extranData初始化miner模块中的extra域,旷工模块在打包区块时会将这个extra data设置给区块头的extra域
eth.miner.SetExtra(makeExtraData(config.MinerExtraData))
eth.APIBackend = &EthAPIBackend{eth, nil}
gpoParams := config.GPO
if gpoParams.Default == nil {
gpoParams.Default = config.MinerGasPrice
}
eth.APIBackend.gpo = gasprice.NewOracle(eth.APIBackend, gpoParams)

return eth, nil
}

上面第 5 步主要是从数据库中读出创世区块,用这个创世区块来初始化chainConfig中的相关域,如果数据库中没有创世区块,且用户没有指定私链创世区块配置,则使用主网的创世区块,如果数据库中有创世区块则使用数据库中的创世区块,如果用户指定了,则使用用户指定的创世区块。]

四、总结

E thereum 模块的初始化函数是以太坊核心模块的初始化入口,后的章节我们会着重分析这些的模块的功能和方法。下一章节我们介绍 B lock Chain 模块的主要功能和部分方法函数。

-END-

以太坊源码分析(三):以太坊服务的初始化流程

以太坊源码分析(三):以太坊服务的初始化流程

以太坊源码分析(三):以太坊服务的初始化流程

来源:链块学院

本文由布洛克专栏作者发布,不代表布洛克观点,版权归作者所有

——TheEnd——

关注“布洛克科技”

以太坊源码分析(三):以太坊服务的初始化流程


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Measure What Matters

Measure What Matters

John Doerr / Portfolio / 2018-4-24 / GBP 19.67

In the fall of 1999, John Doerr met with the founders of a start-up he’d just given $11.8 million, the biggest investment of his career. Larry Page and Sergey Brin had amazing technology, entrepreneur......一起来看看 《Measure What Matters》 这本书的介绍吧!

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具