在这篇文章中,作者将从Vapor节点的创建开始,进而拓展讲解Vapor节点出块过程中所涉及的源码。
做为Vapor源码解析系列的第一篇,本文首先对Vapor稍加介绍。Vapor是目前国内主流公链Bytom的高性能侧链,是从Bytom主链中发展出来的一条独立的高性能侧链。Vapor是平台最重要的区块链基础设施之一,目前采用DPoS的共识算法,具有高性能、高安全、可扩展等特点,用于搭建规模化的商业应用。
Vapor入口函数:
func main() {
cmd := cli.PrepareBaseCmd(commands.RootCmd, "TM", os.ExpandEnv(config.DefaultDataDir()))
cmd.Execute()
}
传入参数node后会调用runNode函数并新建一个节点。
vapor/cmd/vapord/commands/run_node.go
func runNode(cmd *cobra.Command, args []string) error {
startTime := time.Now()
setLogLevel(config.LogLevel)
// Create & start node
n := node.NewNode(config)
……
}
vapor节点的结构:
type Node struct {
cmn.BaseService
config *cfg.Config
eventDispatcher *event.Dispatcher
syncManager *netsync.SyncManager
wallet *w.Wallet
accessTokens *accesstoken.CredentialStore
notificationMgr *websocket.WSNotificationManager
api *api.API
chain *protocol.Chain
blockProposer *blockproposer.BlockProposer
miningEnable bool
}
其中与出块和共识相关的是blockProposer
字段
新建节点的部分源码
func NewNode(config *cfg.Config) *Node {
//……
node := &Node{
eventDispatcher: dispatcher,
config: config,
syncManager: syncManager,
accessTokens: accessTokens,
wallet: wallet,
chain: chain,
miningEnable: config.Mining,
notificationMgr: notificationMgr,
}
node.blockProposer = blockproposer.NewBlockProposer(chain, accounts, txPool, dispatcher)
node.BaseService = *cmn.NewBaseService(nil, "Node", node)
return node
}
从这可以看到node.blockProposer本质上是一个vapor的block生成器,实际控制node启动出块的模块是vapor/proposal/blockproposer/blockproposer.go中的:
func (b *BlockProposer) Start() {
b.Lock()
defer b.Unlock()
// Nothing to do if the miner is already running
if b.started {
return
}
b.quit = make(chan struct{})
go b.generateBlocks() //出块功能的关键模块
b.started = true
log.Infof("block proposer started")
}
出块模块可以通过api启动
func (a *API) startMining() Response {
a.blockProposer.Start()
if !a.IsMining() {
return NewErrorResponse(errors.New("Failed to start mining"))
}
return NewSuccessResponse("")
}
以上讲解的是节点创建和出块模块启动所涉及的源码。
从generateBlocks()
函数开始,将要讲解是Vapor出块过程的具体源码。
Vapor采用的是DPoS的共识机制进行出块。DPoS是由被社区选举的可信帐户(受托人,得票数排行前10位)来创建区块。为了成为正式受托人,用户要去社区拉票,获得足够多用户的信任。用户根据自己持有的加密货币数量占总量的百分比来投票。DPoS机制类似于股份制公司,普通股民进不了董事会,要投票选举代表(受托人)代他们做决策。在讲解Vapor的出块流程之前,要先了解Vapor在DPoS的参数设定。
DPoS的参数信息位于 vapor/consensus/general.go
type DPOSConfig struct {
NumOfConsensusNode int64
BlockNumEachNode uint64
RoundVoteBlockNums uint64
MinConsensusNodeVoteNum uint64
MinVoteOutputAmount uint64
BlockTimeInterval uint64
MaxTimeOffsetMs uint64
}
接下来对参数进行具体解释
讲完DPoS的参数设置后,就可以看看Vapor上出块的核心代码 generateBlocks
vapor/proposal/blockproposer/blockproposer.go
func (b *BlockProposer) generateBlocks() {
xpub := config.CommonConfig.PrivateKey().XPub()
xpubStr := hex.EncodeToString(xpub[:])
ticker := time.NewTicker(time.Duration(consensus.ActiveNetParams.BlockTimeInterval) * time.Millisecond)
defer ticker.Stop()
for {
select {
case <-b.quit:
return
case <-ticker.C:
}
//1
bestBlockHeader := b.chain.BestBlockHeader()
bestBlockHash := bestBlockHeader.Hash()
now := uint64(time.Now().UnixNano() / 1e6)
base := now
if now < bestBlockHeader.Timestamp {
base = bestBlockHeader.Timestamp
}
minTimeToNextBlock := consensus.ActiveNetParams.BlockTimeInterval - base%consensus.ActiveNetParams.BlockTimeInterval
nextBlockTime := base + minTimeToNextBlock
if (nextBlockTime - now) < consensus.ActiveNetParams.BlockTimeInterval/10 {
nextBlockTime += consensus.ActiveNetParams.BlockTimeInterval
}
//2
blocker, err := b.chain.GetBlocker(&bestBlockHash, nextBlockTime)
……
if xpubStr != blocker {
continue
}
//3
warnDuration := time.Duration(consensus.ActiveNetParams.BlockTimeInterval*warnTimeNum/warnTimeDenom) * time.Millisecond
criticalDuration := time.Duration(consensus.ActiveNetParams.BlockTimeInterval*criticalTimeNum/criticalTimeDenom) * time.Millisecond
block, err := proposal.NewBlockTemplate(b.chain, b.accountManager, nextBlockTime, warnDuration, criticalDuration)
……
//4
isOrphan, err := b.chain.ProcessBlock(block)
……
//5
log.WithFields(log.Fields{"module": logModule, "height": block.BlockHeader.Height, "isOrphan": isOrphan, "tx": len(block.Transactions)}).Info("proposer processed block")
if err = b.eventDispatcher.Post(event.NewProposedBlockEvent{Block: *block}); err != nil {
log.WithFields(log.Fields{"module": logModule, "height": block.BlockHeader.Height, "error": err}).Error("proposer fail on post block")
}
}
}
代码经过精简,省略了一些无关紧要的部分,并将重要的部分,分为5个模块。
GetBlocker
获取顺序下一个block的公钥,并与当前块比对,判断当前块的出块顺序是否合法。b.chain.ProcessBlock
根据模板生成了一个block。chain.ProcessBlock(block)
尝试把block加工处理后加到本机持有的区块链上。针对generateBlocks()
中几个重要的模块进行拆分讲解。
vapor/protocol/consensus_node_manager.go
GetBlocker()传入当前高度块的哈希和下一个块的出块时间。
// 返回一个特定时间戳的Blocker
func (c *Chain) GetBlocker(prevBlockHash *bc.Hash, timeStamp uint64) (string, error) {
consensusNodeMap, err := c.getConsensusNodes(prevBlockHash)
//……
prevVoteRoundLastBlock, err := c.getPrevRoundLastBlock(prevBlockHash)
//……
startTimestamp := prevVoteRoundLastBlock.Timestamp + consensus.ActiveNetParams.BlockTimeInterval
//获取order,xpub为公钥
order := getBlockerOrder(startTimestamp, timeStamp, uint64(len(consensusNodeMap)))
for xPub, consensusNode := range consensusNodeMap {
if consensusNode.Order == order {
return xPub, nil
}
}
//……
}
c.getConsensusNodes()
获得一个存储共识节点的Map。getBlockerOrder
,通过开始时间戳和当前要出块的时间戳计算出这个时间点出块的order。consensusNodeMap
中consensusNode.Order
,并返回公钥。这个模块是为了找出当前时间戳对应出块的共识节点,并返回节点的公钥。因为DPoS中出块的节点和顺序必须是固定的,而使用generateBlocks()
模块尝试出块的共识节点不一定是当前时间的合法出块节点,因此需要本模块通过对比公钥进行节点资格的验证。
func NewBlockTemplate(chain *protocol.Chain, accountManager *account.Manager, timestamp uint64, warnDuration, criticalDuration time.Duration) (*types.Block, error) {
builder := newBlockBuilder(chain, accountManager, timestamp, warnDuration, criticalDuration)
return builder.build()
}
func newBlockBuilder(chain *protocol.Chain, accountManager *account.Manager, timestamp uint64, warnDuration, criticalDuration time.Duration) *blockBuilder {
preBlockHeader := chain.BestBlockHeader()
block := &types.Block{
BlockHeader: types.BlockHeader{
Version: 1,
Height: preBlockHeader.Height + 1,
PreviousBlockHash: preBlockHeader.Hash(),
Timestamp: timestamp,
BlockCommitment: types.BlockCommitment{},
BlockWitness: types.BlockWitness{Witness: make([][]byte, consensus.ActiveNetParams.NumOfConsensusNode)},
},
}
builder := &blockBuilder{
chain: chain,
accountManager: accountManager,
block: block,
txStatus: bc.NewTransactionStatus(),
utxoView: state.NewUtxoViewpoint(),
warnTimeoutCh: time.After(warnDuration),
criticalTimeoutCh: time.After(criticalDuration),
gasLeft: int64(consensus.ActiveNetParams.MaxBlockGas),
timeoutStatus: timeoutOk,
}
return builder
}
在Vapor上每个区块有区块头和区块的主体,区块头中包含版本号、高度、上一区块的hash、时间戳等等,主体包括区块链的引用模块、账户管理器、区块头、Transaction状态(版本号和验证状态)、utxo视图等。这一部分的目的是将,区块的各种信息通过模板包装成一个block交给后面的ProcessBlock(block)
加工处理。
func (c *Chain) ProcessBlock(block *types.Block) (bool, error) {
reply := make(chan processBlockResponse, 1)
c.processBlockCh <- &processBlockMsg{block: block, reply: reply}
response := <-reply
return response.isOrphan, response.err
}
func (c *Chain) blockProcesser() {
for msg := range c.processBlockCh {
isOrphan, err := c.processBlock(msg.block)
msg.reply <- processBlockResponse{isOrphan: isOrphan, err: err}
}
}
很显然,这只是链更新的入口,block数据通过processBlockMsg
结构传入了c.processBlockCh
这个管道。随后数据通过blockProcesser()
处理后存入了msg.reply
管道,而最后处理这个block的是processBlock()
函数:
func (c *Chain) processBlock(block *types.Block) (bool, error) {
//1
blockHash := block.Hash()
if c.BlockExist(&blockHash) {
log.WithFields(log.Fields{"module": logModule, "hash": blockHash.String(), "height": block.Height}).Debug("block has been processed")
return c.orphanManage.BlockExist(&blockHash), nil
}
//2
c.markTransactions(block.Transactions...)
//3
if _, err := c.store.GetBlockHeader(&block.PreviousBlockHash); err != nil {
c.orphanManage.Add(block)
return true, nil
}
//4
if err := c.saveBlock(block); err != nil {
return false, err
}
bestBlock := c.saveSubBlock(block)
bestBlockHeader := &bestBlock.BlockHeader
c.cond.L.Lock()
defer c.cond.L.Unlock()
//5
if bestBlockHeader.PreviousBlockHash == c.bestBlockHeader.Hash() {
log.WithFields(log.Fields{"module": logModule}).Debug("append block to the end of mainchain")
return false, c.connectBlock(bestBlock)
}
//6
if bestBlockHeader.Height > c.bestBlockHeader.Height {
log.WithFields(log.Fields{"module": logModule}).Debug("start to reorganize chain")
return false, c.reorganizeChain(bestBlockHeader)
}
return false, nil
}
processBlock()
函数返回的bool
表示的是block是否为孤块。
c.knownTxs.Add()
将Transactions加入到Transaction集合中。saveBlock()
中会对签名和区块进行验证。bestBlockHeader.PreviousBlockHash == c.bestBlockHeader.Hash()
的情况说明一切正常,新block被添加到链的末端。bestBlockHeader.Height > c.bestBlockHeader.Height
表示出现了分叉,需要回滚。本篇文章从Vapor设置出块开始,到出块流程结束,细节层层解析节点设置出块和出块部分所涉及的源码。虽然本文至此篇幅已经比较长,但仍有重要的问题没有讲解清楚。例如,generateBlocks()
中的第2点,程序会对出块的顺序进行查验,但这个出块的顺序是怎么获得还未做细致的解析。
那么,下一篇文章将针对Vapor中DPoS机制的细节进行源码级解析。