文章内容基于 Fabric v2.0.1 整理
Fabric 中所有与链相关的操作都通过 Chaincode
来实现,所有 Chaincode
的执行都是向 EndorserServer
提交 SignedProposal
来触发。
1. System Chaincode
Fabric 对于一些特殊功能(如 Chaincode
本身的管理,Channel
相关操作等)提供内置的 System Chaincode 来实现。有如下 System Chaincode :
cscc
:the configuration handler for the peer,对Channel
的管理qscc
:the ledger query functions,一些通用的查询功能:chaincode lifecycle and policies around it,1.x 版lscc
Chaincode
管理_lifecycle
:2.0 新增用于替代lscc
,实现更完善的Chaincode
lifecycle 管理(根据命令等的组织方式,个人臆测今后可能还会用于其他内容的lifecycle
管理)
另外还有两个 System Chaincode 通过插件的方式提供:
escc
:endorsement system chaincode,部署Chaincode
时指定,对Chaincode
执行结果进行背书vscc
:Validate system chaincode,validates the given envelope corresponding to a transaction with an endorsement policy as given in its serialized form.
2. Process Proposal
Proposal 处理流程主要分为三部分:
- Pre Process : 校验 Proposal 有效性,签名是否匹配等,对于非
System Chaincode
此阶段进行ACL
检查 - Simulate :此阶段会以当前
World State
为基础,使用提供的输入执行Chaincode
,并生成对World State
操作的读写集(RWSet
) - Endorse :当前
Peer
对此次Proposal
正确的执行结果进行签名背书,有些System Chaincode
不进行背书如_lifecycle InstallChaincode
大体流程如下:
3. Simulate Proposal
Simulate Proposal 过程负责 Chaincode
的模拟执行,所谓模拟执行指的是以当前的 World State 为基础来,传递输入参数执行 Chaincode
相关逻辑,Chaincode
对 World State 的插入、删除更新操作以及删除更新操作引用哪些值(基于当前状态值修改)由模拟器收集并记录,最终的结果即为读写集(RWSet
)。需要注意的是私有数据的读写集不直接返回到 Response
中,而是返回私有数据对应的 Hash
值,私有数据读写集本身通过 Gossip
网络进行分发。
Chaincode
调用过程中可能需要 build
And / Or launch
Chaincode ,自 2.0 起 Chaincode
(1.x 的 instantiate
过的,2.0 approve
& commit
的)会预加载并启动,所以大部分情况下 Chaincode
都是出于 Ready 状态,这里只关注 Chaincode 执行部分。
Peer 与 Chaincode 之间的交互由一对 Handler
进行处理,Application Chaincode 通过 gRPC
连接、System Chaincode 通过 两个 golang channel
模拟连接。2.0 之前只能由 Chaincode 主动连接 Peer,2.0 新增了 Chaincode as Service 由 Peer 主动连接 Chaincode,交互过程没有太多区别。两个成对的 Handler 代码见:Peer 侧 Handler 、Chaincode 侧 Handler 。