超级账本 Fabric交易提交过程详解

Peer 启动后会在后台执行 gossip 服务,包括若干 goroutine,实现位于 gossip/state/state.go#NewGossipStateProvider(chainID string, services *ServicesMediator, ledger ledgerResources) GossipStateProvider 方法。

其中一个协程专门负责处理收到的区块信息。

// Deliver in order messages into the incoming channel
go s.deliverPayloads()

deliverPayloads() 方法实现位于同一个文件的 GossipStateProviderImpl 结构下,其主要过程为循环从收到的 Gossip 消息载荷缓冲区按序拿到封装消息,解析后进行处理。核心代码逻辑如下:

// gossip/state/state.go#GossipStateProviderImpl.deliverPayloads()
for {
    select {
    case <-s.payloads.Ready(): // 等待消息
        // 依次处理收到的消息
        for payload := s.payloads.Pop(); payload != nil; payload = s.payloads.Pop() {
            rawBlock := &common.Block{}
            // 从载荷数据中尝试解析区块结构,失败则尝试下个消息
            if err := pb.Unmarshal(payload.Data, rawBlock); err != nil {
                logger.Errorf("Error getting block with seqNum = %d due to (%+v)...dropping block", payload.SeqNum, errors.WithStack(err))
                continue
            }
			// 检查区块结构是否完整,失败则尝试下个消息
            if rawBlock.Data == nil || rawBlock.Header == nil {
                logger.Errorf("Block with claimed sequence %d has no header (%v) or data (%v)",
                    payload.SeqNum, rawBlock.Header, rawBlock.Data)
                continue
            }
            // 从载荷中解析私密数据,失败则尝试下个消息
            var p util.PvtDataCollections
            if payload.PrivateData != nil {
                err := p.Unmarshal(payload.PrivateData)
                if err != nil {
                    logger.Errorf("Wasn't able to unmarshal private data for block seqNum = %d due to (%+v)...dropping block", payload.SeqNum, errors.WithStack(err))
                    continue
                }
            }
            // 核心部分:提交区块到本地账本
            if err := s.commitBlock(rawBlock, p); err != nil {
                if executionErr, isExecutionErr := err.(*vsccErrors.VSCCExecutionFailureError); isExecutionErr {
                    logger.Errorf("Failed executing VSCC due to %v. Aborting chain processing", executionErr)
                    return
                }
                logger.Panicf("Cannot commit block to the ledger due to %+v", errors.WithStack(err))
            }
        }
    case <-s.stopCh: // 停止处理消息
        s.stopCh <- struct{}{}
        logger.Debug("State provider has been stopped, finishing to push new blocks.")
        return
    }
}

整体逻辑

s.commitBlock(rawBlock, p) 是对区块进行处理和提交的核心逻辑,主要包括提交前准备、提交过程和提交后处理三部分,如下图所示。

Peer 提交区块过程

下面分别进行介绍三个阶段的实现过程。

提交前准备

主要完成对区块中交易格式的检查和获取关联该区块但缺失的私密数据,最后构建 blockAndPvtData 结构。

格式检查

对区块格式的检查主要在 core/committer/txvalidator/validator.go#TxValidator.Validate(block *common.Block) error 方法中完成,包括检查交易格式、对应账本是否存在、是否双花、满足 VSCC 和 Policy 等。核心逻辑如下。

// core/committer/txvalidator/validator.go#TxValidator.Validate(block *common.Block) error
// 并发验证交易有效性
go func() {
    for tIdx, d := range block.Data.Data {
        // ensure that we don't have too many concurrent validation workers
        v.Support.Acquire(context.Background(), 1)
 
        go func(index int, data []byte) {
            defer v.Support.Release(1)
 
            v.validateTx(&blockValidationRequest{
                d:     data,
                block: block,
                tIdx:  index,
            }, results)
        }(tIdx, d)
    }
}()
 
 
// 处理检查结果
for i := 0; i < len(block.Data.Data); i++ {
    res := <-results
    if res.err != nil {
        if err == nil || res.tIdx < errPos {
            err = res.err
            errPos = res.tIdx
        }
    } else { // 设置有效标记,记录链码名称,更新链码信息
        txsfltr.SetFlag(res.tIdx, res.validationCode)
        if res.validationCode == peer.TxValidationCode_VALID {
            if res.txsChaincodeName != nil {
                txsChaincodeNames[res.tIdx] = res.txsChaincodeName
            }
            if res.txsUpgradedChaincode != nil {
                txsUpgradedChaincodes[res.tIdx] = res.txsUpgradedChaincode
            }
            txidArray[res.tIdx] = res.txid
        }
    }
}
// 标记双花交易
if v.Support.Capabilities().ForbidDuplicateTXIdInBlock() {
    markTXIdDuplicates(txidArray, txsfltr)
}
// 防止多次升级操作
v.invalidTXsForUpgradeCC(txsChaincodeNames, txsUpgradedChaincodes, txsfltr)
// 确认所有交易都完成检查
err = v.allValidated(txsfltr, block)
if err != nil {
    return err
}
// 更新交易有效标签到元数据
utils.InitBlockMetadata(block)
block.Metadata.Metadata[common.BlockMetadataIndex_TRANSACTIONS_FILTER] = txsflt

获取缺失的私密数据

首先根据已有的私密数据计算区块中交易关联的读写集信息。如果仍有缺失,则尝试从其它节点获取。

// gossip/privdata/coordinator.go#coordinator.StoreBlock(block *common.Block, privateDataSets util.PvtDataCollections) error
// 利用已有的私密数据计算读写集
ownedRWsets, err := computeOwnedRWsets(block, privateDataSets)
privateInfo, err := c.listMissingPrivateData(block, ownedRWsets)
 
// 获取缺失私密数据
for len(privateInfo.missingKeys) > 0 && time.Now().Before(limit) {
    c.fetchFromPeers(block.Header.Number, ownedRWsets, privateInfo)
    if len(privateInfo.missingKeys) == 0 {
        break
    }
    time.Sleep(pullRetrySleepInterval)
}

构建 blockAndPvtData 结构

blockAndPvtData 结构用于后续的提交工作,因此,需要包括相关的区块和私密数据。

主要实现逻辑如下:

// gossip/privdata/coordinator.go#coordinator.StoreBlock(block *common.Block, privateDataSets util.PvtDataCollections) error
// 填充私密读写集信息
for seqInBlock, nsRWS := range ownedRWsets.bySeqsInBlock() {
    rwsets := nsRWS.toRWSet()
    blockAndPvtData.BlockPvtData[seqInBlock] = &ledger.TxPvtData{
        SeqInBlock: seqInBlock,
        WriteSet:   rwsets,
    }
}
 
// 填充缺失私密数据信息
for missingRWS := range privateInfo.missingKeys {
    blockAndPvtData.Missing = append(blockAndPvtData.Missing, ledger.MissingPrivateData{
        TxId:       missingRWS.txID,
        Namespace:  missingRWS.namespace,
        Collection: missingRWS.collection,
        SeqInBlock: int(missingRWS.seqInBlock),
    })
}

提交过程

提交过程是核心过程,主要包括预处理、验证交易、更新本地区块链结构、更新本地数据库结构四个步骤。

预处理

预处理阶段负责构造一个有效的内部区块结构。包括:

  • 处理 Endorser 交易:只保留有效的 Endorser 交易;
  • 处理配置交易:获取配置更新的模拟结果,放入读写集;
  • 校验写集合:如果状态数据库采用 CouchDB,要按照 CouchDB 约束检查键值的格式:Key 必须为非下划线开头的 UTF-8 字符串,Value 必须为合法的字典结构,且不包括下划线开头的键名。

核心实现代码位于

core/ledger/kvledger/txmgmt/validator/valimpl/helper.go#preprocessProtoBlock(txmgr txmgr.TxMgr, validateKVFunc func(key string, value []byte) error, block *common.Block, doMVCCValidation bool) (*valinternal.Block, error),如下所示:</p>

// core/ledger/kvledger/txmgmt/validator/valimpl/helper.go#preprocessProtoBlock(txmgr txmgr.TxMgr, validateKVFunc func(key string, value []byte) error, block *common.Block, doMVCCValidation bool) (*valinternal.Block, error)
// 处理 endorser 交易
if txType == common.HeaderType_ENDORSER_TRANSACTION {
    // extract actions from the envelope message
    respPayload, err := utils.GetActionFromEnvelope(envBytes)
    if err != nil {
        txsFilter.SetFlag(txIndex, peer.TxValidationCode_NIL_TXACTION)
        continue
    }
    txRWSet = &rwsetutil.TxRwSet{}
    if err = txRWSet.FromProtoBytes(respPayload.Results); err != nil {
        txsFilter.SetFlag(txIndex, peer.TxValidationCode_INVALID_OTHER_REASON)
        continue
    }
} else { // 处理配置更新交易
    rwsetProto, err := processNonEndorserTx(env, chdr.TxId, txType, txmgr, !doMVCCValidation)
    if _, ok := err.(*customtx.InvalidTxError); ok {
        txsFilter.SetFlag(txIndex, peer.TxValidationCode_INVALID_OTHER_REASON)
        continue
    }
    if err != nil {
        return nil, err
    }
    if rwsetProto != nil {
        if txRWSet, err = rwsetutil.TxRwSetFromProtoMsg(rwsetProto); err != nil {
            return nil, err
        }
    }
}
// 检查读写集是否符合数据库要求格式
if txRWSet != nil {
    if err := validateWriteset(txRWSet, validateKVFunc); err != nil {
        txsFilter.SetFlag(txIndex, peer.TxValidationCode_INVALID_WRITESET)
        continue
    }
    b.Txs = append(b.Txs, &valinternal.Transaction{IndexInBlock: txIndex, ID: chdr.TxId, RWSet: txRWSet})
}

验证交易

接下来,对区块中交易进行 MVCC 检查,并校验私密读写集,更新区块元数据中的交易有效标记列表。

MVCC 检查需要逐个验证块中的 Endorser 交易,满足下列条件者才认为有效:

  • 公共读集合中 key 版本在该交易前未变;
  • RangeQuery 的结果未变;
  • 私密读集合中 key 版本未变。

实现在 core/ledger/kvledger/txmgmt/validator/statebasedval/state_based_validator.go#Validator.ValidateAndPrepareBatch(block *valinternal.Block, doMVCCValidation bool) (*valinternal.PubAndHashUpdates, error) 方法中,主要逻辑如下:

// core/ledger/kvledger/txmgmt/validator/statebasedval/state_based_validator.go#Validator.ValidateAndPrepareBatch(block *valinternal.Block, doMVCCValidation bool) (*valinternal.PubAndHashUpdates, error)
 
// 依次顺序检查每个交易
for _, tx := range block.Txs {
    var validationCode peer.TxValidationCode
    var err error
    // 检查 Endorser 交易
    if validationCode, err = v.validateEndorserTX(tx.RWSet, doMVCCValidation, updates); err != nil {
        return nil, err
    }
 
    tx.ValidationCode = validationCode
    // 有效交易则将其读写集放到更新集合中
    if validationCode == peer.TxValidationCode_VALID {
        committingTxHeight := version.NewHeight(block.Num, uint64(tx.IndexInBlock))
        updates.ApplyWriteSet(tx.RWSet, committingTxHeight)
    } else {
        logger.Warningf("Block [%d] Transaction index [%d] TxId [%s] marked as invalid by state validator. Reason code [%s]",
            block.Num, tx.IndexInBlock, tx.ID, validationCode.String())
    }
}

对私密读写集的校验主要是再次检查 Hash 值是否匹配,实现在 core/ledger/kvledger/txmgmt/validator/valimpl/helper.go#validatePvtdata(tx *valinternal.Transaction, pvtdata *ledger.TxPvtData) error 方法中。


 
 
  1. // core/ledger/kvledger/txmgmt/validator/valimpl/helper.go#validatePvtdata(tx *valinternal.Transaction, pvtdata *ledger.TxPvtData) error
  2. for _, nsPvtdata := range pvtdata.WriteSet.NsPvtRwset {
  3. for _, collPvtdata := range nsPvtdata.CollectionPvtRwset {
  4. collPvtdataHash := util.ComputeHash(collPvtdata.Rwset)
  5. hashInPubdata := tx.RetrieveHash(nsPvtdata.Namespace, collPvtdata.CollectionName)
  6. // 重新计算私密数据 Hash 值,对比公共数据中的记录
  7. if !bytes.Equal(collPvtdataHash, hashInPubdata) {
  8. return &validator.ErrPvtdataHashMissmatch{
  9. Msg: fmt.Sprintf(`Hash of pvt data for collection [%s:%s] does not match with the corresponding hash in the public data.
  10. public hash = [%#v], pvt data hash = [%#v]`, nsPvtdata.Namespace, collPvtdata.CollectionName, hashInPubdata, collPvtdataHash),
  11. }
  12. }
  13. }
  14. }

最后,更新区块元数据中的交易有效标记列表,实现位于 core/ledger/kvledger/txmgmt/validator/valimpl/helper.go#postprocessProtoBlock(block *common.Block, validatedBlock *valinternal.Block) 方法,代码如下所示。


 
 
  1. // core/ledger/kvledger/txmgmt/validator/valimpl/helper.go#postprocessProtoBlock(block *common.Block, validatedBlock *valinternal.Block)
  2. func postprocessProtoBlock(block *common.Block, validatedBlock *valinternal.Block) {
  3. txsFilter := util.TxValidationFlags(block.Metadata.Metadata[common.BlockMetadataIndex_TRANSACTIONS_FILTER])
  4. for _, tx := range validatedBlock.Txs {
  5. txsFilter.SetFlag(tx.IndexInBlock, tx.ValidationCode)
  6. }
  7. block.Metadata.Metadata[common.BlockMetadataIndex_TRANSACTIONS_FILTER] = txsFilter
  8. }

接下来,需要更新本地的账本结构,包括区块链结构和相关的本地数据库。

更新本地区块链结构

入口在 core/ledger/ledgerstorage/store.go#Store.CommitWithPvtData(blockAndPvtdata *ledger.BlockAndPvtData) error 方法中,主要包括如下步骤:

  • 将区块写入本地 Chunk 文件;
  • 更新索引数据库(区块号、Hash值、文件指针、交易偏移、区块元数据);
  • 更新所提交的区块号到私密数据库;

区块写入 Chunk 文件主要实现在 common/ledger/blkstorage/fsblkstorage/blockfile_mgr.go#blockfileMgr.addBlock(block *common.Block) error 方法中,主要逻辑如下所示:


 
 
  1. // common/ledger/blkstorage/fsblkstorage/blockfile_mgr.go#blockfileMgr.addBlock(block *common.Block) error
  2. // 计算长度信息
  3. blockBytesLen := len(blockBytes)
  4. blockBytesEncodedLen := proto.EncodeVarint(uint64(blockBytesLen))
  5. totalBytesToAppend := blockBytesLen + len(blockBytesEncodedLen)
  6. // 添加长度信息到 Chunk 文件
  7. err = mgr.currentFileWriter.append(blockBytesEncodedLen, false)
  8. // 更新 checkpoint 信息
  9. newCPInfo := &checkpointInfo{
  10. latestFileChunkSuffixNum: currentCPInfo.latestFileChunkSuffixNum,
  11. latestFileChunksize: currentCPInfo.latestFileChunksize + totalBytesToAppend,
  12. isChainEmpty: false,
  13. lastBlockNumber: block.Header.Number}
  14. mgr.saveCurrentInfo(newCPInfo, false);
  15. // 更新区块在文件中索引位置和交易偏移量
  16. blockFLP := &fileLocPointer{fileSuffixNum: newCPInfo.latestFileChunkSuffixNum}
  17. blockFLP.offset = currentOffset
  18. for _, txOffset := range txOffsets {
  19. txOffset.loc.offset += len(blockBytesEncodedLen)
  20. }
  21. // 更新索引数据库
  22. mgr.index.indexBlock(&blockIdxInfo{
  23. blockNum: block.Header.Number, blockHash: blockHash,
  24. flp: blockFLP, txOffsets: txOffsets, metadata: block.Metadata})
  25. // 更新 checkpoint 信息和区块链信息
  26. mgr.updateCheckpoint(newCPInfo)
  27. mgr.updateBlockchainInfo(blockHash, block)

更新本地数据库结构

更新数据库是提交交易的最后一步,主要包括如下步骤:

  • 删除过期私密数据;
  • 更新私密数据生命周期记录数据库;
  • 更新本地公共状态数据库和私密状态数据库;
  • 如果启用了历史数据库,更新数据。

实现代码在 core/ledger/kvledger/txmgmt/txmgr/lockbasedtxmgr/lockbased_txmgr.go#LockBasedTxMgr.Commit() error 方法中,主要逻辑如下。


 
 
  1. // core/ledger/kvledger/txmgmt/txmgr/lockbasedtxmgr/lockbased_txmgr.go#LockBasedTxMgr.Commit() error
  2. // 准备过期的私密键值清理
  3. txmgr.pvtdataPurgeMgr.PrepareForExpiringKeys(txmgr.current.blockNum())
  4. // 更新私密数据生命周期记录数据库,这里记录了每个私密键值的存活期限
  5. if err := txmgr.pvtdataPurgeMgr.DeleteExpiredAndUpdateBookkeeping(
  6. txmgr.current.batch.PvtUpdates, txmgr.current.batch.HashUpdates); err != nil{
  7. return err
  8. }
  9. // 更新本地公共状态数据库和私密状态数据库
  10. if err := txmgr.db.ApplyPrivacyAwareUpdates(txmgr.current.batch, commitHeight); err != nil {
  11. return err
  12. }
  13. // 如果启用了历史数据库,更新数据
  14. if ledgerconfig.IsHistoryDBEnabled() {
  15. if err := l.historyDB.Commit(block); err != nil {
  16. panic(errors.WithMessage(err, "Error during commit to history db"))
  17. }
  18. }

提交后处理

提交后的处理比较简单,包括清理本地的临时状态数据库和更新账本高度信息。

清理工作包括区块关联的临时私密数据和旧区块关联的临时私密数据。

======关于本文 =======

更多源码剖析内容可参考 超级账本 Fabric 源码剖析 开源项目;

更多区块链深度技术可参考 区块链技术指南 开源项目。

转载请注明原文链接。

Peer 启动后会在后台执行 gossip 服务,包括若干 goroutine,实现位于 gossip/state/state.go#NewGossipStateProvider(chainID string, services *ServicesMediator, ledger ledgerResources) GossipStateProvider 方法。

其中一个协程专门负责处理收到的区块信息。


 
 
  1. // Deliver in order messages into the incoming channel
  2. go s.deliverPayloads()

deliverPayloads() 方法实现位于同一个文件的 GossipStateProviderImpl 结构下,其主要过程为循环从收到的 Gossip 消息载荷缓冲区按序拿到封装消息,解析后进行处理。核心代码逻辑如下:


 
 
  1. // gossip/state/state.go#GossipStateProviderImpl.deliverPayloads()
  2. for {
  3. select {
  4. case <-s.payloads.Ready(): // 等待消息
  5. // 依次处理收到的消息
  6. for payload := s.payloads.Pop(); payload != nil; payload = s.payloads.Pop() {
  7. rawBlock := &common.Block{}
  8. // 从载荷数据中尝试解析区块结构,失败则尝试下个消息
  9. if err := pb.Unmarshal(payload.Data, rawBlock); err != nil {
  10. logger.Errorf("Error getting block with seqNum = %d due to (%+v)...dropping block", payload.SeqNum, errors.WithStack(err))
  11. continue
  12. }
  13. // 检查区块结构是否完整,失败则尝试下个消息
  14. if rawBlock.Data == nil || rawBlock.Header == nil {
  15. logger.Errorf("Block with claimed sequence %d has no header (%v) or data (%v)",
  16. payload.SeqNum, rawBlock.Header, rawBlock.Data)
  17. continue
  18. }
  19. // 从载荷中解析私密数据,失败则尝试下个消息
  20. var p util.PvtDataCollections
  21. if payload.PrivateData != nil {
  22. err := p.Unmarshal(payload.PrivateData)
  23. if err != nil {
  24. logger.Errorf("Wasn't able to unmarshal private data for block seqNum = %d due to (%+v)...dropping block", payload.SeqNum, errors.WithStack(err))
  25. continue
  26. }
  27. }
  28. // 核心部分:提交区块到本地账本
  29. if err := s.commitBlock(rawBlock, p); err != nil {
  30. if executionErr, isExecutionErr := err.(*vsccErrors.VSCCExecutionFailureError); isExecutionErr {
  31. logger.Errorf("Failed executing VSCC due to %v. Aborting chain processing", executionErr)
  32. return
  33. }
  34. logger.Panicf("Cannot commit block to the ledger due to %+v", errors.WithStack(err))
  35. }
  36. }
  37. case <-s.stopCh: // 停止处理消息
  38. s.stopCh <- struct{}{}
  39. logger.Debug("State provider has been stopped, finishing to push new blocks.")
  40. return
  41. }
  42. }

整体逻辑

s.commitBlock(rawBlock, p) 是对区块进行处理和提交的核心逻辑,主要包括提交前准备、提交过程和提交后处理三部分,如下图所示。

Peer 提交区块过程

下面分别进行介绍三个阶段的实现过程。

提交前准备

主要完成对区块中交易格式的检查和获取关联该区块但缺失的私密数据,最后构建 blockAndPvtData 结构。

格式检查

对区块格式的检查主要在 core/committer/txvalidator/validator.go#TxValidator.Validate(block *common.Block) error 方法中完成,包括检查交易格式、对应账本是否存在、是否双花、满足 VSCC 和 Policy 等。核心逻辑如下。


 
 
  1. // core/committer/txvalidator/validator.go#TxValidator.Validate(block *common.Block) error
  2. // 并发验证交易有效性
  3. go func() {
  4. for tIdx, d := range block.Data.Data {
  5. // ensure that we don't have too many concurrent validation workers
  6. v.Support.Acquire(context.Background(), 1)
  7. go func(index int, data []byte) {
  8. defer v.Support.Release(1)
  9. v.validateTx(&blockValidationRequest{
  10. d: data,
  11. block: block,
  12. tIdx: index,
  13. }, results)
  14. }(tIdx, d)
  15. }
  16. }()
  17. // 处理检查结果
  18. for i := 0; i < len(block.Data.Data); i++ {
  19. res := <-results
  20. if res.err != nil {
  21. if err == nil || res.tIdx < errPos {
  22. err = res.err
  23. errPos = res.tIdx
  24. }
  25. } else { // 设置有效标记,记录链码名称,更新链码信息
  26. txsfltr.SetFlag(res.tIdx, res.validationCode)
  27. if res.validationCode == peer.TxValidationCode_VALID {
  28. if res.txsChaincodeName != nil {
  29. txsChaincodeNames[res.tIdx] = res.txsChaincodeName
  30. }
  31. if res.txsUpgradedChaincode != nil {
  32. txsUpgradedChaincodes[res.tIdx] = res.txsUpgradedChaincode
  33. }
  34. txidArray[res.tIdx] = res.txid
  35. }
  36. }
  37. }
  38. // 标记双花交易
  39. if v.Support.Capabilities().ForbidDuplicateTXIdInBlock() {
  40. markTXIdDuplicates(txidArray, txsfltr)
  41. }
  42. // 防止多次升级操作
  43. v.invalidTXsForUpgradeCC(txsChaincodeNames, txsUpgradedChaincodes, txsfltr)
  44. // 确认所有交易都完成检查
  45. err = v.allValidated(txsfltr, block)
  46. if err != nil {
  47. return err
  48. }
  49. // 更新交易有效标签到元数据
  50. utils.InitBlockMetadata(block)
  51. block.Metadata.Metadata[common.BlockMetadataIndex_TRANSACTIONS_FILTER] = txsflt

获取缺失的私密数据

首先根据已有的私密数据计算区块中交易关联的读写集信息。如果仍有缺失,则尝试从其它节点获取。


 
 
  1. // gossip/privdata/coordinator.go#coordinator.StoreBlock(block *common.Block, privateDataSets util.PvtDataCollections) error
  2. // 利用已有的私密数据计算读写集
  3. ownedRWsets, err := computeOwnedRWsets(block, privateDataSets)
  4. privateInfo, err := c.listMissingPrivateData(block, ownedRWsets)
  5. // 获取缺失私密数据
  6. for len(privateInfo.missingKeys) > 0 && time.Now().Before(limit) {
  7. c.fetchFromPeers(block.Header.Number, ownedRWsets, privateInfo)
  8. if len(privateInfo.missingKeys) == 0 {
  9. break
  10. }
  11. time.Sleep(pullRetrySleepInterval)
  12. }

构建 blockAndPvtData 结构

blockAndPvtData 结构用于后续的提交工作,因此,需要包括相关的区块和私密数据。

主要实现逻辑如下:


 
 
  1. // gossip/privdata/coordinator.go#coordinator.StoreBlock(block *common.Block, privateDataSets util.PvtDataCollections) error
  2. // 填充私密读写集信息
  3. for seqInBlock, nsRWS := range ownedRWsets.bySeqsInBlock() {
  4. rwsets := nsRWS.toRWSet()
  5. blockAndPvtData.BlockPvtData[seqInBlock] = &ledger.TxPvtData{
  6. SeqInBlock: seqInBlock,
  7. WriteSet: rwsets,
  8. }
  9. }
  10. // 填充缺失私密数据信息
  11. for missingRWS := range privateInfo.missingKeys {
  12. blockAndPvtData.Missing = append(blockAndPvtData.Missing, ledger.MissingPrivateData{
  13. TxId: missingRWS.txID,
  14. Namespace: missingRWS.namespace,
  15. Collection: missingRWS.collection,
  16. SeqInBlock: int(missingRWS.seqInBlock),
  17. })
  18. }

提交过程

提交过程是核心过程,主要包括预处理、验证交易、更新本地区块链结构、更新本地数据库结构四个步骤。

预处理

预处理阶段负责构造一个有效的内部区块结构。包括:

  • 处理 Endorser 交易:只保留有效的 Endorser 交易;
  • 处理配置交易:获取配置更新的模拟结果,放入读写集;
  • 校验写集合:如果状态数据库采用 CouchDB,要按照 CouchDB 约束检查键值的格式:Key 必须为非下划线开头的 UTF-8 字符串,Value 必须为合法的字典结构,且不包括下划线开头的键名。

核心实现代码位于 core/ledger/kvledger/txmgmt/validator/valimpl/helper.go#preprocessProtoBlock(txmgr txmgr.TxMgr, validateKVFunc func(key string, value []byte) error, block *common.Block, doMVCCValidation bool) (*valinternal.Block, error),如下所示:


 
 
  1. // core/ledger/kvledger/txmgmt/validator/valimpl/helper.go#preprocessProtoBlock(txmgr txmgr.TxMgr, validateKVFunc func(key string, value []byte) error, block *common.Block, doMVCCValidation bool) (*valinternal.Block, error)
  2. // 处理 endorser 交易
  3. if txType == common.HeaderType_ENDORSER_TRANSACTION {
  4. // extract actions from the envelope message
  5. respPayload, err := utils.GetActionFromEnvelope(envBytes)
  6. if err != nil {
  7. txsFilter.SetFlag(txIndex, peer.TxValidationCode_NIL_TXACTION)
  8. continue
  9. }
  10. txRWSet = &rwsetutil.TxRwSet{}
  11. if err = txRWSet.FromProtoBytes(respPayload.Results); err != nil {
  12. txsFilter.SetFlag(txIndex, peer.TxValidationCode_INVALID_OTHER_REASON)
  13. continue
  14. }
  15. } else { // 处理配置更新交易
  16. rwsetProto, err := processNonEndorserTx(env, chdr.TxId, txType, txmgr, !doMVCCValidation)
  17. if _, ok := err.(*customtx.InvalidTxError); ok {
  18. txsFilter.SetFlag(txIndex, peer.TxValidationCode_INVALID_OTHER_REASON)
  19. continue
  20. }
  21. if err != nil {
  22. return nil, err
  23. }
  24. if rwsetProto != nil {
  25. if txRWSet, err = rwsetutil.TxRwSetFromProtoMsg(rwsetProto); err != nil {
  26. return nil, err
  27. }
  28. }
  29. }
  30. // 检查读写集是否符合数据库要求格式
  31. if txRWSet != nil {
  32. if err := validateWriteset(txRWSet, validateKVFunc); err != nil {
  33. txsFilter.SetFlag(txIndex, peer.TxValidationCode_INVALID_WRITESET)
  34. continue
  35. }
  36. b.Txs = append(b.Txs, &valinternal.Transaction{IndexInBlock: txIndex, ID: chdr.TxId, RWSet: txRWSet})
  37. }

验证交易

接下来,对区块中交易进行 MVCC 检查,并校验私密读写集,更新区块元数据中的交易有效标记列表。

MVCC 检查需要逐个验证块中的 Endorser 交易,满足下列条件者才认为有效:

  • 公共读集合中 key 版本在该交易前未变;
  • RangeQuery 的结果未变;
  • 私密读集合中 key 版本未变。

实现在 core/ledger/kvledger/txmgmt/validator/statebasedval/state_based_validator.go#Validator.ValidateAndPrepareBatch(block *valinternal.Block, doMVCCValidation bool) (*valinternal.PubAndHashUpdates, error) 方法中,主要逻辑如下:


 
 
  1. // core/ledger/kvledger/txmgmt/validator/statebasedval/state_based_validator.go#Validator.ValidateAndPrepareBatch(block *valinternal.Block, doMVCCValidation bool) (*valinternal.PubAndHashUpdates, error)
  2. // 依次顺序检查每个交易
  3. for _, tx := range block.Txs {
  4. var validationCode peer.TxValidationCode
  5. var err error
  6. // 检查 Endorser 交易
  7. if validationCode, err = v.validateEndorserTX(tx.RWSet, doMVCCValidation, updates); err != nil {
  8. return nil, err
  9. }
  10. tx.ValidationCode = validationCode
  11. // 有效交易则将其读写集放到更新集合中
  12. if validationCode == peer.TxValidationCode_VALID {
  13. committingTxHeight := version.NewHeight(block.Num, uint64(tx.IndexInBlock))
  14. updates.ApplyWriteSet(tx.RWSet, committingTxHeight)
  15. } else {
  16. logger.Warningf("Block [%d] Transaction index [%d] TxId [%s] marked as invalid by state validator. Reason code [%s]",
  17. block.Num, tx.IndexInBlock, tx.ID, validationCode.String())
  18. }
  19. }

对私密读写集的校验主要是再次检查 Hash 值是否匹配,实现在 core/ledger/kvledger/txmgmt/validator/valimpl/helper.go#validatePvtdata(tx *valinternal.Transaction, pvtdata *ledger.TxPvtData) error 方法中。


 
 
  1. // core/ledger/kvledger/txmgmt/validator/valimpl/helper.go#validatePvtdata(tx *valinternal.Transaction, pvtdata *ledger.TxPvtData) error
  2. for _, nsPvtdata := range pvtdata.WriteSet.NsPvtRwset {
  3. for _, collPvtdata := range nsPvtdata.CollectionPvtRwset {
  4. collPvtdataHash := util.ComputeHash(collPvtdata.Rwset)
  5. hashInPubdata := tx.RetrieveHash(nsPvtdata.Namespace, collPvtdata.CollectionName)
  6. // 重新计算私密数据 Hash 值,对比公共数据中的记录
  7. if !bytes.Equal(collPvtdataHash, hashInPubdata) {
  8. return &validator.ErrPvtdataHashMissmatch{
  9. Msg: fmt.Sprintf(`Hash of pvt data for collection [%s:%s] does not match with the corresponding hash in the public data.
  10. public hash = [%#v], pvt data hash = [%#v]`, nsPvtdata.Namespace, collPvtdata.CollectionName, hashInPubdata, collPvtdataHash),
  11. }
  12. }
  13. }
  14. }

最后,更新区块元数据中的交易有效标记列表,实现位于 core/ledger/kvledger/txmgmt/validator/valimpl/helper.go#postprocessProtoBlock(block *common.Block, validatedBlock *valinternal.Block) 方法,代码如下所示。


 
 
  1. // core/ledger/kvledger/txmgmt/validator/valimpl/helper.go#postprocessProtoBlock(block *common.Block, validatedBlock *valinternal.Block)
  2. func postprocessProtoBlock(block *common.Block, validatedBlock *valinternal.Block) {
  3. txsFilter := util.TxValidationFlags(block.Metadata.Metadata[common.BlockMetadataIndex_TRANSACTIONS_FILTER])
  4. for _, tx := range validatedBlock.Txs {
  5. txsFilter.SetFlag(tx.IndexInBlock, tx.ValidationCode)
  6. }
  7. block.Metadata.Metadata[common.BlockMetadataIndex_TRANSACTIONS_FILTER] = txsFilter
  8. }

接下来,需要更新本地的账本结构,包括区块链结构和相关的本地数据库。

更新本地区块链结构

入口在 core/ledger/ledgerstorage/store.go#Store.CommitWithPvtData(blockAndPvtdata *ledger.BlockAndPvtData) error 方法中,主要包括如下步骤:

  • 将区块写入本地 Chunk 文件;
  • 更新索引数据库(区块号、Hash值、文件指针、交易偏移、区块元数据);
  • 更新所提交的区块号到私密数据库;

区块写入 Chunk 文件主要实现在 common/ledger/blkstorage/fsblkstorage/blockfile_mgr.go#blockfileMgr.addBlock(block *common.Block) error 方法中,主要逻辑如下所示:

// common/ledger/blkstorage/fsblkstorage/blockfile_mgr.go#blockfileMgr.addBlock(block *common.Block) error
// 计算长度信息
blockBytesLen := len(blockBytes)
blockBytesEncodedLen := proto.EncodeVarint(uint64(blockBytesLen))
totalBytesToAppend := blockBytesLen + len(blockBytesEncodedLen)
 
// 添加长度信息到 Chunk 文件
err = mgr.currentFileWriter.append(blockBytesEncodedLen, false)
 
// 更新 checkpoint 信息
newCPInfo := &checkpointInfo{
	latestFileChunkSuffixNum: currentCPInfo.latestFileChunkSuffixNum,
	latestFileChunksize:      currentCPInfo.latestFileChunksize + totalBytesToAppend,
	isChainEmpty:             false,
	lastBlockNumber:          block.Header.Number}
mgr.saveCurrentInfo(newCPInfo, false);
 
// 更新区块在文件中索引位置和交易偏移量
blockFLP := &fileLocPointer{fileSuffixNum: newCPInfo.latestFileChunkSuffixNum}
	blockFLP.offset = currentOffset
for _, txOffset := range txOffsets {
		txOffset.loc.offset += len(blockBytesEncodedLen)
}
 
// 更新索引数据库
mgr.index.indexBlock(&blockIdxInfo{
	blockNum: block.Header.Number, blockHash: blockHash,
	flp: blockFLP, txOffsets: txOffsets, metadata: block.Metadata})
 
// 更新 checkpoint 信息和区块链信息
mgr.updateCheckpoint(newCPInfo)
mgr.updateBlockchainInfo(blockHash, block)

更新本地数据库结构

更新数据库是提交交易的最后一步,主要包括如下步骤:

  • 删除过期私密数据;
  • 更新私密数据生命周期记录数据库;
  • 更新本地公共状态数据库和私密状态数据库;
  • 如果启用了历史数据库,更新数据。

实现代码在 core/ledger/kvledger/txmgmt/txmgr/lockbasedtxmgr/lockbased_txmgr.go#LockBasedTxMgr.Commit() error 方法中,主要逻辑如下。

// core/ledger/kvledger/txmgmt/txmgr/lockbasedtxmgr/lockbased_txmgr.go#LockBasedTxMgr.Commit() error
 
// 准备过期的私密键值清理
txmgr.pvtdataPurgeMgr.PrepareForExpiringKeys(txmgr.current.blockNum())
 
// 更新私密数据生命周期记录数据库,这里记录了每个私密键值的存活期限
if err := txmgr.pvtdataPurgeMgr.DeleteExpiredAndUpdateBookkeeping(
		txmgr.current.batch.PvtUpdates, txmgr.current.batch.HashUpdates); err != nil{
	return err
}
 
// 更新本地公共状态数据库和私密状态数据库
if err := txmgr.db.ApplyPrivacyAwareUpdates(txmgr.current.batch, commitHeight); err != nil {
	return err
}
 
// 如果启用了历史数据库,更新数据
if ledgerconfig.IsHistoryDBEnabled() {
	if err := l.historyDB.Commit(block); err != nil {
		panic(errors.WithMessage(err, "Error during commit to history db"))
	}
}

提交后处理

提交后的处理比较简单,包括清理本地的临时状态数据库和更新账本高度信息。

清理工作包括区块关联的临时私密数据和旧区块关联的临时私密数据。

======关于本文 =======

更多源码剖析内容可参考 超级账本 Fabric 源码剖析 开源项目;

更多区块链深度技术可参考 区块链技术指南 开源项目。

转载请注明原文链接。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Fabric是基于区块链技术的分布式账本平台,它提供了一个可编程的、安全的、模块化的架构,可以帮助企业构建和管理自己的区块链网络。在这里,我将简要介绍Fabric的运行过程。 1. 网络拓扑 Fabric网络由多个节点组成,每个节点可以是Peer节点、Orderer节点或CA节点,这些节点组成了一个分布式网络拓扑。Peer节点是网络中执行交易和维护账本状态的节点,Orderer节点是网络中负责排序交易的节点,CA节点是网络中负责管理身份认证的节点。 2. 安装部署 在部署Fabric网络之前,需要先安装Fabric的运行环境和依赖组件。然后,按照网络拓扑图的要求,在不同的节点上安装和配置相应的组件,例如Peer节点需要安装Peer组件、Chaincode组件和CouchDB组件,Orderer节点需要安装Orderer组件和Kafka组件等等。 3. 身份认证 在Fabric网络中,每个参与者都有一个身份标识,它可以是一个证书或者一个密钥对。在进行交易时,参与者需要通过身份认证才能进行操作。CA节点负责管理证书和密钥对,为参与者颁发数字身份。 4. 链码部署 链码是在Fabric网络中执行的智能合约,它定义了交易的规则和行为。在部署链码之前,需要先编写链码代码,并将其打包成一个tar包。然后,通过Peer节点的CLI工具将链码部署到网络中。 5. 交易执行 在Fabric网络中,交易的执行是通过链码来实现的。当一个参与者想要执行一个交易时,它需要向相应的Peer节点发送交易请求。Peer节点将交易请求发送到Orderer节点,然后Orderer节点将交易排序后返回给Peer节点。最后,Peer节点执行交易并将结果存储到账本中。 6. 账本查询 在Fabric网络中,账本是一个持久化存储交易记录的数据库。参与者可以通过Peer节点的CLI工具查询账本中的交易记录和状态信息。 7. 历史记录查询 在Fabric网络中,每个交易都有一个唯一的交易ID,参与者可以通过Peer节点的CLI工具查询交易的详细信息,包括交易执行的时间、交易的输入输出等等。此外,参与者还可以查询账本中某个key的历史记录,包括该key的所有版本和对应的交易ID。 这些是Fabric的运行过程中的主要步骤,每个步骤都需要仔细地配置和调试,才能保证网络的正常运行。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值