您好,欢迎访问三七文档
当前位置:首页 > 金融/证券 > 投融资/租赁 > 兄弟连Go语言+区块链技术培训以太坊源码分析(37)eth以太坊协议分析
1/34兄弟连Go语言+区块链技术培训以太坊源码分析(37)eth以太坊协议分析node中的服务的定义,eth其实就是实现了一个服务。typeServiceinterface{//ProtocolsretrievestheP2Pprotocolstheservicewishestostart.Protocols()[]p2p.Protocol//APIsretrievesthelistofRPCdescriptorstheserviceprovidesAPIs()[]rpc.API//Startiscalledafterallserviceshavebeenconstructedandthenetworking//layerwasalsoinitializedtospawnanygoroutinesrequiredbytheservice.Start(server*p2p.Server)error//Stopterminatesallgoroutinesbelongingtotheservice,blockinguntilthey//areallterminated.Stop()error}goethereum的eth目录是以太坊服务的实现。以太坊协议是通过node的Register方法注入的。//RegisterEthServiceaddsanEthereumclienttothestack.funcRegisterEthService(stack*node.Node,cfg*eth.Config){varerrerrorifcfg.SyncMode==downloader.LightSync{err=stack.Register(func(ctx*node.ServiceContext)(node.Service,error){returnles.New(ctx,cfg)})}else{err=stack.Register(func(ctx*node.ServiceContext)(node.Service,error){2/34fullNode,err:=eth.New(ctx,cfg)iffullNode!=nil&&cfg.LightServ0{ls,_:=les.NewLesServer(fullNode,cfg)fullNode.AddLesServer(ls)}returnfullNode,err})}iferr!=nil{Fatalf(FailedtoregistertheEthereumservice:%v,err)}}以太坊协议的数据结构//EthereumimplementstheEthereumfullnodeservice.typeEthereumstruct{config*Config配置chainConfig*params.ChainConfig链配置//ChannelforshuttingdowntheserviceshutdownChanchanbool//ChannelforshuttingdowntheethereumstopDbUpgradefunc()error//stopchaindbsequentialkeyupgrade//HandlerstxPool*core.TxPool交易池blockchain*core.BlockChain区块链protocolManager*ProtocolManager协议管理lesServerLesServer轻量级客户端服务器//DBinterfaceschainDbethdb.Database//Blockchaindatabase区块链数据库eventMux*event.TypeMuxengineconsensus.Engine一致性引擎。应该是Pow部分accountManager*accounts.Manager账号管理bloomRequestschanchan*bloombits.Retrieval//Channelreceivingbloomdataretrievalrequests接收bloom过滤器数据请求的通道3/34bloomIndexer*core.ChainIndexer//Bloomindexeroperatingduringblockimports//在区块import的时候执行Bloomindexer操作暂时不清楚是什么ApiBackend*EthApiBackend//提供给RPC服务使用的API后端miner*miner.Miner//矿工gasPrice*big.Int//节点接收的gasPrice的最小值。比这个值更小的交易会被本节点拒绝etherbasecommon.Address//矿工地址networkIduint64//网络IDtestnet是0mainnet是1netRPCService*ethapi.PublicNetAPI//RPC的服务locksync.RWMutex//Protectsthevariadicfields(e.g.gaspriceandetherbase)}以太坊协议的创建New.暂时先不涉及core的内容。只是大概介绍一下。core里面的内容后续会分析。//NewcreatesanewEthereumobject(includingthe//initialisationofthecommonEthereumobject)funcNew(ctx*node.ServiceContext,config*Config)(*Ethereum,error){ifconfig.SyncMode==downloader.LightSync{returnnil,errors.New(can'truneth.Ethereuminlightsyncmode,useles.LightEthereum)}if!config.SyncMode.IsValid(){returnnil,fmt.Errorf(invalidsyncmode%d,config.SyncMode)}//创建leveldb。打开或者新建chaindata目录chainDb,err:=CreateDB(ctx,config,chaindata)iferr!=nil{returnnil,err}//数据库格式升级stopDbUpgrade:=upgradeDeduplicateData(chainDb)//设置创世区块。如果数据库里面已经有创世区块那么从数据库里面取出(私链)。或者是从代码里面获取默认值。4/34chainConfig,genesisHash,genesisErr:=core.SetupGenesisBlock(chainDb,config.Genesis)if_,ok:=genesisErr.(*params.ConfigCompatError);genesisErr!=nil&&!ok{returnnil,genesisErr}log.Info(Initialisedchainconfiguration,config,chainConfig)eth:=&Ethereum{config:config,chainDb:chainDb,chainConfig:chainConfig,eventMux:ctx.EventMux,accountManager:ctx.AccountManager,engine:CreateConsensusEngine(ctx,config,chainConfig,chainDb),//一致性引擎。这里我理解是PowshutdownChan:make(chanbool),stopDbUpgrade:stopDbUpgrade,networkId:config.NetworkId,//网络ID用来区别网路。测试网络是0.主网是1gasPrice:config.GasPrice,//可以通过配置--gasprice客户端接纳的交易的gasprice最小值。如果小于这个值那么会被节点丢弃。etherbase:config.Etherbase,//挖矿的受益者bloomRequests:make(chanchan*bloombits.Retrieval),//bloom的请求bloomIndexer:NewBloomIndexer(chainDb,params.BloomBitsBlocks),}log.Info(InitialisingEthereumprotocol,versions,ProtocolVersions,network,config.NetworkId)if!config.SkipBcVersionCheck{//检查数据库里面存储的BlockChainVersion和客户端的BlockChainVersion的版本是否一致bcVersion:=core.GetBlockChainVersion(chainDb)ifbcVersion!=core.BlockChainVersion&&bcVersion!=0{returnnil,fmt.Errorf(BlockchainDBversionmismatch(%d/%d).Rungethupgradedb.\n,bcVersion,core.BlockChainVersion)}core.WriteBlockChainVersion(chainDb,core.BlockChainVersion)}5/34vmConfig:=vm.Config{EnablePreimageRecording:config.EnablePreimageRecording}//使用数据库创建了区块链eth.blockchain,err=core.NewBlockChain(chainDb,eth.chainConfig,eth.engine,vmConfig)iferr!=nil{returnnil,err}//Rewindthechainincaseofanincompatibleconfigupgrade.ifcompat,ok:=genesisErr.(*params.ConfigCompatError);ok{log.Warn(Rewindingchaintoupgradeconfiguration,err,compat)eth.blockchain.SetHead(compat.RewindTo)core.WriteChainConfig(chainDb,genesisHash,chainConfig)}//bloomIndexer暂时不知道是什么东西这里面涉及得也不是很多。暂时先不管了eth.bloomIndexer.Start(eth.blockchain.CurrentHeader(),eth.blockchain.SubscribeChainEvent)ifconfig.TxPool.Journal!={config.TxPool.Journal=ctx.ResolvePath(config.TxPool.Journal)}//创建交易池。用来存储本地或者在网络上接收到的交易。eth.txPool=core.NewTxPool(config.TxPool,eth.chainConfig,eth.blockchain)//创建协议管理器ifeth.protocolManager,err=NewProtocolManager(eth.chainConfig,config.SyncMode,config.NetworkId,eth.eventMux,eth.txPool,eth.engine,eth.blockchain,chainDb);err!=nil{returnnil,err}//创建矿工eth.miner=miner.New(eth,eth.chainConfig,eth.EventMux(),eth.engin
本文标题:兄弟连Go语言+区块链技术培训以太坊源码分析(37)eth以太坊协议分析
链接地址:https://www.777doc.com/doc-5447083 .html